├── .gitignore ├── .npmignore ├── LICENSE ├── README.md ├── bin └── tspack ├── lib └── tspack.js ├── package.json ├── scripts ├── loader.js ├── loader.min.js ├── loader.ts ├── reflection.d.ts ├── reflection.min.js ├── reflection.ts └── tsconfig.json └── src ├── lib ├── chokidar.d.ts └── node.d.ts ├── packer ├── CommandLine.js ├── CommandLine.ts ├── Compiler.js ├── Compiler.ts ├── Config.js ├── Config.ts ├── Program.js ├── Program.ts ├── Service.js ├── Service.ts ├── Utils.js └── Utils.ts └── tsconfig.json /.gitignore: -------------------------------------------------------------------------------- 1 | # Build and Release Folders 2 | /bin-debug 3 | .settings/ 4 | node_modules 5 | /test 6 | .idea/ 7 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | doc 2 | #src 3 | .settings/ 4 | *.ts -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015-present, Dom Chen. 4 | All rights reserved. 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining a copy of 7 | this software and associated documentation files (the "Software"), to deal in the 8 | Software without restriction, including without limitation the rights to use, copy, 9 | modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, 10 | and to permit persons to whom the Software is furnished to do so, subject to the 11 | following conditions: 12 | 13 | The above copyright notice and this permission notice shall be included in all 14 | copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 17 | INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 18 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 19 | HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 20 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 21 | SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![npm version](https://badge.fury.io/js/tspack.svg)](https://badge.fury.io/js/tspack) 2 | 3 | # Introduction 4 | 5 | tspack is a bundler for typescript modules. Packs many modules into a few bundled assets. Allows to split your codebase into multiple bundles, which can be loaded on demand. 6 | 7 | 8 | # Installation 9 | 10 | project: 11 | `npm install tspack` 12 | 13 | global: 14 | `npm install tspack -g` 15 | 16 | 17 | # Example 18 | 19 | tsconfig.json : 20 | 21 | ``` 22 | { 23 | "compilerOptions": { 24 | "outDir": "bin-debug", 25 | "target": "ES5", 26 | "declaration": true, 27 | "accessorOptimization": true, 28 | "emitReflection": true, 29 | "reorderFiles": true, 30 | "defines": { 31 | "DEBUG": false, 32 | "LANGUAGE": "en_US" 33 | } 34 | }, 35 | "modules": [ 36 | { 37 | "name": "core", 38 | "include": [ 39 | "src/**/*" 40 | ], 41 | "exclude": [ 42 | "**/web/*", 43 | "node_modules" 44 | ], 45 | "dependencies": [] 46 | }, 47 | { 48 | "name": "web", 49 | "declaration": false, // Override the default compiler options defined above. 50 | "include": [ 51 | "src/**/web/*" 52 | ], 53 | "exclude": [ 54 | "node_modules" 55 | ], 56 | "dependencies": [ 57 | "core" 58 | ] 59 | } 60 | ] 61 | } 62 | 63 | ``` -------------------------------------------------------------------------------- /bin/tspack: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | //console.log("it works!"); 3 | require('../src/packer/Program.js'); 4 | -------------------------------------------------------------------------------- /lib/tspack.js: -------------------------------------------------------------------------------- 1 | console.log("it works!"); -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "tspack", 3 | "version": "1.0.5", 4 | "author": "Dom Chen", 5 | "homepage": "http://www.idom.me/", 6 | "description": "A bundler for typescript. Packs many modules into a few bundled assets. Allows to split your codebase into multiple bundles, which can be loaded on demand.", 7 | "license": "MIT", 8 | "keywords": [ 9 | "typescript", 10 | "tspack", 11 | "bundle", 12 | "module", 13 | "javascript" 14 | ], 15 | "bugs": { 16 | "url": "https://github.com/domchen/tspack/issues" 17 | }, 18 | "repository": { 19 | "type": "git", 20 | "url": "https://github.com/domchen/tspack.git" 21 | }, 22 | "main": "./lib/tspack.js", 23 | "bin": { 24 | "tspack": "./bin/tspack" 25 | }, 26 | "engines": { 27 | "node": ">=0.8.0" 28 | }, 29 | "dependencies": { 30 | "chokidar": "latest", 31 | "typescript-plus": "latest" 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /scripts/loader.js: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////////////////// 2 | // 3 | // The MIT License (MIT) 4 | // 5 | // Copyright (c) 2015-present, Dom Chen. 6 | // All rights reserved. 7 | // 8 | // Permission is hereby granted, free of charge, to any person obtaining a copy of 9 | // this software and associated documentation files (the "Software"), to deal in the 10 | // Software without restriction, including without limitation the rights to use, copy, 11 | // modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, 12 | // and to permit persons to whom the Software is furnished to do so, subject to the 13 | // following conditions: 14 | // 15 | // The above copyright notice and this permission notice shall be included in all 16 | // copies or substantial portions of the Software. 17 | // 18 | // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 19 | // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 21 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 22 | // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 23 | // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 24 | // 25 | ////////////////////////////////////////////////////////////////////////////////////// 26 | var ts; 27 | (function (ts) { 28 | /** 29 | * Start loading a json file. 30 | */ 31 | function loadJSON(url, callback) { 32 | var xhr = window["XMLHttpRequest"] ? new XMLHttpRequest() : 33 | new ActiveXObject('Microsoft.XMLHTTP'); 34 | xhr.open('get', url, true); 35 | xhr.onreadystatechange = function () { 36 | if (xhr.readyState == 4) { 37 | var status_1 = xhr.status; 38 | if (status_1 == 200) { 39 | var data = JSON.parse(xhr.responseText); 40 | callback(data); 41 | } 42 | } 43 | }; 44 | xhr.send(); 45 | } 46 | /** 47 | * Start loading all scripts in the list. 48 | */ 49 | function loadAll(list, callback) { 50 | var loadNext = function () { 51 | var url = list.shift(); 52 | loadScript(url, function () { 53 | if (list.length > 0) { 54 | loadNext(); 55 | } 56 | else { 57 | callback && callback(); 58 | } 59 | }); 60 | }; 61 | loadNext(); 62 | } 63 | /** 64 | * Start loading one script. 65 | */ 66 | function loadScript(src, callback) { 67 | var node = document.createElement('script'); 68 | node.type = "text/javascript"; 69 | node.async = true; 70 | node.charset = 'utf-8'; 71 | node.addEventListener('load', function () { 72 | node.parentNode.removeChild(node); 73 | this.removeEventListener('load', arguments.callee, false); 74 | callback(); 75 | }, false); 76 | node.src = src; 77 | document.body.appendChild(node); 78 | } 79 | /** 80 | * @language en_US 81 | * Start loading the manifest.json file and all script files in it. 82 | * @param url The path of the manifest.json file. 83 | * @param callback The function to be called when load is complete. 84 | */ 85 | /** 86 | * @language zh_CN 87 | * 开始加载manifest.json文件以及它内部记录的脚本文件列表。 88 | * @param url manifest.json的文件路径。 89 | * @param callback 当加载完成时的回调函数。 90 | */ 91 | function loadManifest(url, callback) { 92 | loadJSON(url, function (data) { 93 | url = url.split("\\").join("/"); 94 | var index = url.lastIndexOf("/"); 95 | var files = data.files; 96 | if (index != -1) { 97 | var baseURL = url.substring(0, index + 1); 98 | for (var i = 0; i < files.length; i++) { 99 | files[i] = baseURL + files[i]; 100 | } 101 | } 102 | loadAll(files, callback); 103 | }); 104 | } 105 | ts.loadManifest = loadManifest; 106 | })(ts || (ts = {})); 107 | //check the data-manifest property in script node, and load it automatically if find one. 108 | var scripts = document.getElementsByTagName('script'); 109 | for (var i = 0, l = scripts.length; i < l; i++) { 110 | var node = scripts[i]; 111 | var url = node.getAttribute('data-manifest'); 112 | if (url) { 113 | ts.loadManifest(url); 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /scripts/loader.min.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-present, Dom Chen, All rights reserved. 3 | * Released under the MIT license, See LICENSE file in the project root for license information. 4 | */ 5 | var ts,scripts,i,l,node,url 6 | for(function(t){function e(t,e){var n=window.XMLHttpRequest?new XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP") 7 | n.open("get",t,!0),n.onreadystatechange=function(){var t,s 8 | 4==n.readyState&&(t=n.status,200==t&&(s=JSON.parse(n.responseText),e(s)))},n.send()}function n(t,e){var n=function(){var i=t.shift() 9 | s(i,function(){t.length>0?n():e&&e()})} 10 | n()}function s(t,e){var n=document.createElement("script") 11 | n.type="text/javascript",n.async=!0,n.charset="utf-8",n.addEventListener("load",function(){n.parentNode.removeChild(n),this.removeEventListener("load",arguments.callee,!1),e()},!1),n.src=t,document.body.appendChild(n)}function i(t,s){e(t,function(e){var i,a,r,o 12 | if(t=t.split("\\").join("/"),i=t.lastIndexOf("/"),a=e.files,-1!=i)for(r=t.substring(0,i+1),o=0;oi;i++)node=scripts[i],url=node.getAttribute("data-manifest"),url&&ts.loadManifest(url) 14 | -------------------------------------------------------------------------------- /scripts/loader.ts: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////////////////// 2 | // 3 | // The MIT License (MIT) 4 | // 5 | // Copyright (c) 2015-present, Dom Chen. 6 | // All rights reserved. 7 | // 8 | // Permission is hereby granted, free of charge, to any person obtaining a copy of 9 | // this software and associated documentation files (the "Software"), to deal in the 10 | // Software without restriction, including without limitation the rights to use, copy, 11 | // modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, 12 | // and to permit persons to whom the Software is furnished to do so, subject to the 13 | // following conditions: 14 | // 15 | // The above copyright notice and this permission notice shall be included in all 16 | // copies or substantial portions of the Software. 17 | // 18 | // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 19 | // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 21 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 22 | // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 23 | // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 24 | // 25 | ////////////////////////////////////////////////////////////////////////////////////// 26 | 27 | 28 | namespace ts { 29 | /** 30 | * Start loading a json file. 31 | */ 32 | function loadJSON(url:string, callback:(data:any)=>void):void { 33 | let xhr = window["XMLHttpRequest"] ? new XMLHttpRequest() : 34 | new ActiveXObject('Microsoft.XMLHTTP'); 35 | xhr.open('get', url, true); 36 | xhr.onreadystatechange = function () { 37 | if (xhr.readyState == 4) { 38 | let status = xhr.status; 39 | if (status == 200) { 40 | let data = JSON.parse(xhr.responseText); 41 | callback(data); 42 | } 43 | } 44 | }; 45 | xhr.send(); 46 | } 47 | /** 48 | * Start loading all scripts in the list. 49 | */ 50 | function loadAll(list:string[], callback:()=>void) { 51 | let loadNext = ()=> { 52 | let url = list.shift(); 53 | loadScript(url, () => { 54 | if (list.length > 0) { 55 | loadNext(); 56 | } 57 | else { 58 | callback && callback(); 59 | } 60 | }) 61 | }; 62 | loadNext(); 63 | } 64 | /** 65 | * Start loading one script. 66 | */ 67 | function loadScript(src:string, callback:()=>void):void { 68 | let node = document.createElement('script'); 69 | node.type = "text/javascript"; 70 | node.async = true; 71 | node.charset = 'utf-8'; 72 | node.addEventListener('load', function () { 73 | node.parentNode.removeChild(node); 74 | this.removeEventListener('load', arguments.callee, false); 75 | callback(); 76 | }, false); 77 | node.src = src; 78 | document.body.appendChild(node); 79 | } 80 | /** 81 | * @language en_US 82 | * Start loading the manifest.json file and all script files in it. 83 | * @param url The path of the manifest.json file. 84 | * @param callback The function to be called when load is complete. 85 | */ 86 | /** 87 | * @language zh_CN 88 | * 开始加载manifest.json文件以及它内部记录的脚本文件列表。 89 | * @param url manifest.json的文件路径。 90 | * @param callback 当加载完成时的回调函数。 91 | */ 92 | export function loadManifest(url:string, callback?:()=>void):void { 93 | loadJSON(url, (data:any)=> { 94 | url = url.split("\\").join("/"); 95 | let index = url.lastIndexOf("/"); 96 | let files:string[] = data.files; 97 | if (index != -1) { 98 | let baseURL = url.substring(0, index + 1); 99 | for (let i = 0; i < files.length; i++) { 100 | files[i] = baseURL + files[i]; 101 | } 102 | } 103 | loadAll(files, callback); 104 | }) 105 | } 106 | } 107 | 108 | //check the data-manifest property in script node, and load it automatically if find one. 109 | let scripts = document.getElementsByTagName('script'); 110 | for (let i = 0, l = scripts.length; i < l; i++) { 111 | let node = scripts[i]; 112 | let url = node.getAttribute('data-manifest'); 113 | if (url) { 114 | ts.loadManifest(url); 115 | } 116 | } -------------------------------------------------------------------------------- /scripts/reflection.d.ts: -------------------------------------------------------------------------------- 1 | declare namespace ts { 2 | /** 3 | * Returns a reference to the class object of the class specified by the name parameter. 4 | * @param name The name of a class. 5 | */ 6 | function getDefinitionByName(name: string): any; 7 | /** 8 | * Return the fully qualified class name of an object 9 | * @param value The object for which a fully qualified class name is desired. Any JavaScript value may be passed to 10 | * this method including all available JavaScript types, object instances, primitive types such as number, and class objects. 11 | * @returns A string containing the fully qualified class name. 12 | */ 13 | function getQualifiedClassName(value: any): string; 14 | /** 15 | * Returns the fully qualified class name of the base class of the object specified by the value parameter. 16 | * @param value The object for which a parent class is desired. Any JavaScript value may be passed to this method including 17 | * all available JavaScript types, object instances, primitive types such as number, and class objects. 18 | * @returns A fully qualified base class name, or null if none exists. 19 | */ 20 | function getQualifiedSuperclassName(value: any): string; 21 | /** 22 | * Indicates whether an object is a instance of the class or interface specified as the parameter.This method can indicate 23 | * whether an object is a instance of the specific interface even though the interface does not exist at JavaScript runtime. 24 | * @param instance the instance to be checked. 25 | * @param typeName the string value representing a specific class or interface. 26 | * @returns A value of true if the object is a instance of the class or interface specified as the parameter. 27 | * @example 28 | *
29 |      *     var instance = new ts.Sprite();
30 |      *     console.log(ts.is(instance,"ts.Sprite"))                  // true
31 |      *     console.log(ts.is(instance,"ts.DisplayObjectContainer"))  // true, because ts.DisplayObjectContainer is the superclass of ts.Sprite.
32 |      *     console.log(ts.is(instance,"ts.Bitmap"))                  // false, because ts.Bitmap is not the superclass of ts.Sprite.
33 |      * 
34 | */ 35 | function is(instance: any, typeName: string): boolean; 36 | } 37 | declare var __global: any; 38 | -------------------------------------------------------------------------------- /scripts/reflection.min.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-present, Dom Chen, All rights reserved. 3 | * Released under the MIT license, See LICENSE file in the project root for license information. 4 | */ 5 | var ts,__global 6 | !function(t){function e(t){var e,r,o,n,u 7 | if(!t)return null 8 | if(e=l[t])return e 9 | for(r=t.split("."),o=r.length,e=__global,n=0;o>n;n++)if(u=r[n],e=e[u],!e)return null 10 | return l[t]=e,e}function r(t){var e,r,o,n,l=typeof t 11 | return!t||"object"!=l&&!t.prototype?l:(e=t.prototype?t.prototype:Object.getPrototypeOf(t),e.hasOwnProperty("__class__")?e.__class__:(r=(""+e.constructor).trim(),o=r.indexOf("("),n=r.substring(9,o),Object.defineProperty(e,"__class__",{value:n,enumerable:!1,writable:!0}),n))}function o(t){var e,o,n 12 | return!t||"object"!=typeof t&&!t.prototype?null:(e=t.prototype?t.prototype:Object.getPrototypeOf(t),(o=Object.getPrototypeOf(e))?(n=r(o.constructor),n?n:null):null)}function n(t,e){var r,o 13 | return t&&"object"==typeof t?(r=Object.getPrototypeOf(t),o=r?r.__types__:null,o?-1!==o.indexOf(e):!1):!1}var l={} 14 | t.getDefinitionByName=e,t.getQualifiedClassName=r,t.getQualifiedSuperclassName=o,t.is=n}(ts||(ts={})),__global=this.__global||this 15 | 16 | -------------------------------------------------------------------------------- /scripts/reflection.ts: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////////////////// 2 | // 3 | // The MIT License (MIT) 4 | // 5 | // Copyright (c) 2015-present, Dom Chen. 6 | // All rights reserved. 7 | // 8 | // Permission is hereby granted, free of charge, to any person obtaining a copy of 9 | // this software and associated documentation files (the "Software"), to deal in the 10 | // Software without restriction, including without limitation the rights to use, copy, 11 | // modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, 12 | // and to permit persons to whom the Software is furnished to do so, subject to the 13 | // following conditions: 14 | // 15 | // The above copyright notice and this permission notice shall be included in all 16 | // copies or substantial portions of the Software. 17 | // 18 | // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 19 | // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 21 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 22 | // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 23 | // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 24 | // 25 | ////////////////////////////////////////////////////////////////////////////////////// 26 | 27 | 28 | namespace ts { 29 | 30 | /** 31 | * @private 32 | */ 33 | let getDefinitionByNameCache = {}; 34 | 35 | /** 36 | * Returns a reference to the class object of the class specified by the name parameter. 37 | * @param name The name of a class. 38 | */ 39 | export function getDefinitionByName(name:string):any { 40 | if (!name) 41 | return null; 42 | let definition = getDefinitionByNameCache[name]; 43 | if (definition) { 44 | return definition; 45 | } 46 | let paths = name.split("."); 47 | let length = paths.length; 48 | definition = __global; 49 | for (let i = 0; i < length; i++) { 50 | let path = paths[i]; 51 | definition = definition[path]; 52 | if (!definition) { 53 | return null; 54 | } 55 | } 56 | getDefinitionByNameCache[name] = definition; 57 | return definition; 58 | } 59 | 60 | /** 61 | * Return the fully qualified class name of an object 62 | * @param value The object for which a fully qualified class name is desired. Any JavaScript value may be passed to 63 | * this method including all available JavaScript types, object instances, primitive types such as number, and class objects. 64 | * @returns A string containing the fully qualified class name. 65 | */ 66 | export function getQualifiedClassName(value:any):string { 67 | let type = typeof value; 68 | if (!value || (type != "object" && !value.prototype)) { 69 | return type; 70 | } 71 | let prototype:any = value.prototype ? value.prototype : Object.getPrototypeOf(value); 72 | if (prototype.hasOwnProperty("__class__")) { 73 | return prototype["__class__"]; 74 | } 75 | let constructorString:string = prototype.constructor.toString().trim(); 76 | let index:number = constructorString.indexOf("("); 77 | let className:string = constructorString.substring(9, index); 78 | Object.defineProperty(prototype, "__class__", { 79 | value: className, 80 | enumerable: false, 81 | writable: true 82 | }); 83 | return className; 84 | } 85 | 86 | /** 87 | * Returns the fully qualified class name of the base class of the object specified by the value parameter. 88 | * @param value The object for which a parent class is desired. Any JavaScript value may be passed to this method including 89 | * all available JavaScript types, object instances, primitive types such as number, and class objects. 90 | * @returns A fully qualified base class name, or null if none exists. 91 | */ 92 | export function getQualifiedSuperclassName(value:any):string { 93 | if (!value || (typeof value != "object" && !value.prototype)) { 94 | return null; 95 | } 96 | let prototype:any = value.prototype ? value.prototype : Object.getPrototypeOf(value); 97 | let superProto = Object.getPrototypeOf(prototype); 98 | if (!superProto) { 99 | return null; 100 | } 101 | let superClass = getQualifiedClassName(superProto.constructor); 102 | if (!superClass) { 103 | return null; 104 | } 105 | return superClass; 106 | } 107 | 108 | /** 109 | * Indicates whether an object is a instance of the class or interface specified as the parameter.This method can indicate 110 | * whether an object is a instance of the specific interface even though the interface does not exist at JavaScript runtime. 111 | * @param instance the instance to be checked. 112 | * @param typeName the string value representing a specific class or interface. 113 | * @returns A value of true if the object is a instance of the class or interface specified as the parameter. 114 | * @example 115 | *
116 |      *     var instance = new ts.Sprite();
117 |      *     console.log(ts.is(instance,"ts.Sprite"))                  // true
118 |      *     console.log(ts.is(instance,"ts.DisplayObjectContainer"))  // true, because ts.DisplayObjectContainer is the superclass of ts.Sprite.
119 |      *     console.log(ts.is(instance,"ts.Bitmap"))                  // false, because ts.Bitmap is not the superclass of ts.Sprite.
120 |      * 
121 | */ 122 | export function is(instance:any, typeName:string):boolean { 123 | if (!instance || typeof instance != "object") { 124 | return false; 125 | } 126 | let prototype:any = Object.getPrototypeOf(instance); 127 | let types = prototype ? prototype.__types__ : null; 128 | if (!types) { 129 | return false; 130 | } 131 | return (types.indexOf(typeName) !== -1); 132 | } 133 | } 134 | 135 | var __global = this.__global || this; 136 | -------------------------------------------------------------------------------- /scripts/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "target": "es5", 5 | "sourceMap": false, 6 | "declaration": false 7 | }, 8 | "exclude": [ 9 | "node_modules" 10 | ] 11 | } -------------------------------------------------------------------------------- /src/lib/chokidar.d.ts: -------------------------------------------------------------------------------- 1 | // Type definitions for chokidar 1.4.3 2 | // Project: https://github.com/paulmillr/chokidar 3 | // Definitions by: Stefan Steinhart 4 | // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped 5 | 6 | declare module "fs" 7 | { 8 | interface FSWatcher 9 | { 10 | add(fileDirOrGlob:string):void; 11 | add(filesDirsOrGlobs:Array):void; 12 | unwatch(fileDirOrGlob:string):void; 13 | unwatch(filesDirsOrGlobs:Array):void; 14 | getWatched():any; 15 | } 16 | } 17 | 18 | declare module "chokidar" 19 | { 20 | interface WatchOptions 21 | { 22 | persistent?:boolean; 23 | ignored?:any; 24 | ignoreInitial?:boolean; 25 | followSymlinks?:boolean; 26 | cwd?:string; 27 | usePolling?:boolean; 28 | useFsEvents?:boolean; 29 | alwaysStat?:boolean; 30 | depth?:number; 31 | interval?:number; 32 | binaryInterval?:number; 33 | ignorePermissionErrors?:boolean; 34 | atomic?:boolean; 35 | awaitWriteFinish?:any; 36 | } 37 | 38 | import fs = require("fs"); 39 | 40 | function watch(fileDirOrGlob:string, options?:WatchOptions):fs.FSWatcher; 41 | function watch(filesDirsOrGlobs:Array, options?:WatchOptions):fs.FSWatcher; 42 | } 43 | -------------------------------------------------------------------------------- /src/lib/node.d.ts: -------------------------------------------------------------------------------- 1 | // Type definitions for Node.js v0.10.1 2 | // Project: http://nodejs.org/ 3 | // Definitions by: Microsoft TypeScript , DefinitelyTyped 4 | // Definitions: https://github.com/borisyankov/DefinitelyTyped 5 | 6 | /************************************************ 7 | * * 8 | * Node.js v0.10.1 API * 9 | * * 10 | ************************************************/ 11 | 12 | /************************************************ 13 | * * 14 | * GLOBAL * 15 | * * 16 | ************************************************/ 17 | declare var process: NodeJS.Process; 18 | declare var global: any; 19 | 20 | declare var __filename: string; 21 | declare var __dirname: string; 22 | 23 | declare function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; 24 | declare function clearTimeout(timeoutId: NodeJS.Timer): void; 25 | declare function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; 26 | declare function clearInterval(intervalId: NodeJS.Timer): void; 27 | declare function setImmediate(callback: (...args: any[]) => void, ...args: any[]): any; 28 | declare function clearImmediate(immediateId: any): void; 29 | 30 | declare var require: { 31 | (id: string): any; 32 | resolve(id:string): string; 33 | cache: any; 34 | extensions: any; 35 | main: any; 36 | }; 37 | 38 | declare var module: { 39 | exports: any; 40 | require(id: string): any; 41 | id: string; 42 | filename: string; 43 | loaded: boolean; 44 | parent: any; 45 | children: any[]; 46 | }; 47 | 48 | // Same as module.exports 49 | declare var exports: any; 50 | declare var SlowBuffer: { 51 | new (str: string, encoding?: string): Buffer; 52 | new (size: number): Buffer; 53 | new (array: any[]): Buffer; 54 | prototype: Buffer; 55 | isBuffer(obj: any): boolean; 56 | byteLength(string: string, encoding?: string): number; 57 | concat(list: Buffer[], totalLength?: number): Buffer; 58 | }; 59 | 60 | 61 | // Buffer class 62 | interface Buffer extends NodeBuffer {} 63 | declare var Buffer: { 64 | new (str: string, encoding?: string): Buffer; 65 | new (size: number): Buffer; 66 | new (array: any[]): Buffer; 67 | prototype: Buffer; 68 | isBuffer(obj: any): boolean; 69 | byteLength(string: string, encoding?: string): number; 70 | concat(list: Buffer[], totalLength?: number): Buffer; 71 | }; 72 | 73 | /************************************************ 74 | * * 75 | * GLOBAL INTERFACES * 76 | * * 77 | ************************************************/ 78 | declare module NodeJS { 79 | export interface ErrnoException extends Error { 80 | errno?: any; 81 | code?: string; 82 | path?: string; 83 | syscall?: string; 84 | } 85 | 86 | export interface EventEmitter { 87 | addListener(event: string, listener: Function): EventEmitter; 88 | on(event: string, listener: Function): EventEmitter; 89 | once(event: string, listener: Function): EventEmitter; 90 | removeListener(event: string, listener: Function): EventEmitter; 91 | removeAllListeners(event?: string): EventEmitter; 92 | setMaxListeners(n: number): void; 93 | listeners(event: string): Function[]; 94 | emit(event: string, ...args: any[]): boolean; 95 | } 96 | 97 | export interface ReadableStream extends EventEmitter { 98 | readable: boolean; 99 | read(size?: number): any; 100 | setEncoding(encoding: string): void; 101 | pause(): void; 102 | resume(): void; 103 | pipe(destination: T, options?: { end?: boolean; }): T; 104 | unpipe(destination?: T): void; 105 | unshift(chunk: string): void; 106 | unshift(chunk: Buffer): void; 107 | wrap(oldStream: ReadableStream): ReadableStream; 108 | } 109 | 110 | export interface WritableStream extends EventEmitter { 111 | writable: boolean; 112 | write(buffer: Buffer, cb?: Function): boolean; 113 | write(str: string, cb?: Function): boolean; 114 | write(str: string, encoding?: string, cb?: Function): boolean; 115 | end(): void; 116 | end(buffer: Buffer, cb?: Function): void; 117 | end(str: string, cb?: Function): void; 118 | end(str: string, encoding?: string, cb?: Function): void; 119 | } 120 | 121 | export interface ReadWriteStream extends ReadableStream, WritableStream {} 122 | 123 | export interface Process extends EventEmitter { 124 | stdout: WritableStream; 125 | stderr: WritableStream; 126 | stdin: ReadableStream; 127 | argv: string[]; 128 | execPath: string; 129 | abort(): void; 130 | chdir(directory: string): void; 131 | cwd(): string; 132 | env: any; 133 | exit(code?: number): void; 134 | getgid(): number; 135 | setgid(id: number): void; 136 | setgid(id: string): void; 137 | getuid(): number; 138 | setuid(id: number): void; 139 | setuid(id: string): void; 140 | version: string; 141 | versions: { 142 | http_parser: string; 143 | node: string; 144 | v8: string; 145 | ares: string; 146 | uv: string; 147 | zlib: string; 148 | openssl: string; 149 | }; 150 | config: { 151 | target_defaults: { 152 | cflags: any[]; 153 | default_configuration: string; 154 | defines: string[]; 155 | include_dirs: string[]; 156 | libraries: string[]; 157 | }; 158 | variables: { 159 | clang: number; 160 | host_arch: string; 161 | node_install_npm: boolean; 162 | node_install_waf: boolean; 163 | node_prefix: string; 164 | node_shared_openssl: boolean; 165 | node_shared_v8: boolean; 166 | node_shared_zlib: boolean; 167 | node_use_dtrace: boolean; 168 | node_use_etw: boolean; 169 | node_use_openssl: boolean; 170 | target_arch: string; 171 | v8_no_strict_aliasing: number; 172 | v8_use_snapshot: boolean; 173 | visibility: string; 174 | }; 175 | }; 176 | kill(pid: number, signal?: string): void; 177 | pid: number; 178 | title: string; 179 | arch: string; 180 | platform: string; 181 | memoryUsage(): { rss: number; heapTotal: number; heapUsed: number; }; 182 | nextTick(callback: Function): void; 183 | umask(mask?: number): number; 184 | uptime(): number; 185 | hrtime(time?:number[]): number[]; 186 | 187 | // Worker 188 | send?(message: any, sendHandle?: any): void; 189 | } 190 | 191 | export interface Timer { 192 | ref() : void; 193 | unref() : void; 194 | } 195 | } 196 | 197 | /** 198 | * @deprecated 199 | */ 200 | interface NodeBuffer { 201 | [index: number]: number; 202 | write(string: string, offset?: number, length?: number, encoding?: string): number; 203 | toString(encoding?: string, start?: number, end?: number): string; 204 | toJSON(): any; 205 | length: number; 206 | copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; 207 | slice(start?: number, end?: number): Buffer; 208 | readUInt8(offset: number, noAsset?: boolean): number; 209 | readUInt16LE(offset: number, noAssert?: boolean): number; 210 | readUInt16BE(offset: number, noAssert?: boolean): number; 211 | readUInt32LE(offset: number, noAssert?: boolean): number; 212 | readUInt32BE(offset: number, noAssert?: boolean): number; 213 | readInt8(offset: number, noAssert?: boolean): number; 214 | readInt16LE(offset: number, noAssert?: boolean): number; 215 | readInt16BE(offset: number, noAssert?: boolean): number; 216 | readInt32LE(offset: number, noAssert?: boolean): number; 217 | readInt32BE(offset: number, noAssert?: boolean): number; 218 | readFloatLE(offset: number, noAssert?: boolean): number; 219 | readFloatBE(offset: number, noAssert?: boolean): number; 220 | readDoubleLE(offset: number, noAssert?: boolean): number; 221 | readDoubleBE(offset: number, noAssert?: boolean): number; 222 | writeUInt8(value: number, offset: number, noAssert?: boolean): void; 223 | writeUInt16LE(value: number, offset: number, noAssert?: boolean): void; 224 | writeUInt16BE(value: number, offset: number, noAssert?: boolean): void; 225 | writeUInt32LE(value: number, offset: number, noAssert?: boolean): void; 226 | writeUInt32BE(value: number, offset: number, noAssert?: boolean): void; 227 | writeInt8(value: number, offset: number, noAssert?: boolean): void; 228 | writeInt16LE(value: number, offset: number, noAssert?: boolean): void; 229 | writeInt16BE(value: number, offset: number, noAssert?: boolean): void; 230 | writeInt32LE(value: number, offset: number, noAssert?: boolean): void; 231 | writeInt32BE(value: number, offset: number, noAssert?: boolean): void; 232 | writeFloatLE(value: number, offset: number, noAssert?: boolean): void; 233 | writeFloatBE(value: number, offset: number, noAssert?: boolean): void; 234 | writeDoubleLE(value: number, offset: number, noAssert?: boolean): void; 235 | writeDoubleBE(value: number, offset: number, noAssert?: boolean): void; 236 | fill(value: any, offset?: number, end?: number): void; 237 | } 238 | 239 | /************************************************ 240 | * * 241 | * MODULES * 242 | * * 243 | ************************************************/ 244 | declare module "buffer" { 245 | export var INSPECT_MAX_BYTES: number; 246 | } 247 | 248 | declare module "querystring" { 249 | export function stringify(obj: any, sep?: string, eq?: string): string; 250 | export function parse(str: string, sep?: string, eq?: string, options?: { maxKeys?: number; }): any; 251 | export function escape(): any; 252 | export function unescape(): any; 253 | } 254 | 255 | declare module "events" { 256 | export class EventEmitter implements NodeJS.EventEmitter { 257 | static listenerCount(emitter: EventEmitter, event: string): number; 258 | 259 | addListener(event: string, listener: Function): EventEmitter; 260 | on(event: string, listener: Function): EventEmitter; 261 | once(event: string, listener: Function): EventEmitter; 262 | removeListener(event: string, listener: Function): EventEmitter; 263 | removeAllListeners(event?: string): EventEmitter; 264 | setMaxListeners(n: number): void; 265 | listeners(event: string): Function[]; 266 | emit(event: string, ...args: any[]): boolean; 267 | } 268 | } 269 | 270 | declare module "http" { 271 | import events = require("events"); 272 | import net = require("net"); 273 | import stream = require("stream"); 274 | 275 | export interface Server extends events.EventEmitter { 276 | listen(port: number, hostname?: string, backlog?: number, callback?: Function): Server; 277 | listen(path: string, callback?: Function): Server; 278 | listen(handle: any, listeningListener?: Function): Server; 279 | close(cb?: any): Server; 280 | address(): { port: number; family: string; address: string; }; 281 | maxHeadersCount: number; 282 | } 283 | export interface ServerRequest extends events.EventEmitter, stream.Readable { 284 | method: string; 285 | url: string; 286 | headers: any; 287 | trailers: string; 288 | httpVersion: string; 289 | setEncoding(encoding?: string): void; 290 | pause(): void; 291 | resume(): void; 292 | connection: net.Socket; 293 | } 294 | export interface ServerResponse extends events.EventEmitter, stream.Writable { 295 | // Extended base methods 296 | write(buffer: Buffer): boolean; 297 | write(buffer: Buffer, cb?: Function): boolean; 298 | write(str: string, cb?: Function): boolean; 299 | write(str: string, encoding?: string, cb?: Function): boolean; 300 | write(str: string, encoding?: string, fd?: string): boolean; 301 | 302 | writeContinue(): void; 303 | writeHead(statusCode: number, reasonPhrase?: string, headers?: any): void; 304 | writeHead(statusCode: number, headers?: any): void; 305 | statusCode: number; 306 | setHeader(name: string, value: string): void; 307 | sendDate: boolean; 308 | getHeader(name: string): string; 309 | removeHeader(name: string): void; 310 | write(chunk: any, encoding?: string): any; 311 | addTrailers(headers: any): void; 312 | 313 | // Extended base methods 314 | end(): void; 315 | end(buffer: Buffer, cb?: Function): void; 316 | end(str: string, cb?: Function): void; 317 | end(str: string, encoding?: string, cb?: Function): void; 318 | end(data?: any, encoding?: string): void; 319 | } 320 | export interface ClientRequest extends events.EventEmitter, stream.Writable { 321 | // Extended base methods 322 | write(buffer: Buffer): boolean; 323 | write(buffer: Buffer, cb?: Function): boolean; 324 | write(str: string, cb?: Function): boolean; 325 | write(str: string, encoding?: string, cb?: Function): boolean; 326 | write(str: string, encoding?: string, fd?: string): boolean; 327 | 328 | write(chunk: any, encoding?: string): void; 329 | abort(): void; 330 | setTimeout(timeout: number, callback?: Function): void; 331 | setNoDelay(noDelay?: boolean): void; 332 | setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; 333 | 334 | // Extended base methods 335 | end(): void; 336 | end(buffer: Buffer, cb?: Function): void; 337 | end(str: string, cb?: Function): void; 338 | end(str: string, encoding?: string, cb?: Function): void; 339 | end(data?: any, encoding?: string): void; 340 | } 341 | export interface ClientResponse extends events.EventEmitter, stream.Readable { 342 | statusCode: number; 343 | httpVersion: string; 344 | headers: any; 345 | trailers: any; 346 | setEncoding(encoding?: string): void; 347 | pause(): void; 348 | resume(): void; 349 | } 350 | export interface Agent { maxSockets: number; sockets: any; requests: any; } 351 | 352 | export var STATUS_CODES: { 353 | [errorCode: number]: string; 354 | [errorCode: string]: string; 355 | }; 356 | export function createServer(requestListener?: (request: ServerRequest, response: ServerResponse) =>void ): Server; 357 | export function createClient(port?: number, host?: string): any; 358 | export function request(options: any, callback?: Function): ClientRequest; 359 | export function get(options: any, callback?: Function): ClientRequest; 360 | export var globalAgent: Agent; 361 | } 362 | 363 | declare module "cluster" { 364 | import child = require("child_process"); 365 | import events = require("events"); 366 | 367 | export interface ClusterSettings { 368 | exec?: string; 369 | args?: string[]; 370 | silent?: boolean; 371 | } 372 | 373 | export class Worker extends events.EventEmitter { 374 | id: string; 375 | process: child.ChildProcess; 376 | suicide: boolean; 377 | send(message: any, sendHandle?: any): void; 378 | kill(signal?: string): void; 379 | destroy(signal?: string): void; 380 | disconnect(): void; 381 | } 382 | 383 | export var settings: ClusterSettings; 384 | export var isMaster: boolean; 385 | export var isWorker: boolean; 386 | export function setupMaster(settings?: ClusterSettings): void; 387 | export function fork(env?: any): Worker; 388 | export function disconnect(callback?: Function): void; 389 | export var worker: Worker; 390 | export var workers: Worker[]; 391 | 392 | // Event emitter 393 | export function addListener(event: string, listener: Function): void; 394 | export function on(event: string, listener: Function): any; 395 | export function once(event: string, listener: Function): void; 396 | export function removeListener(event: string, listener: Function): void; 397 | export function removeAllListeners(event?: string): void; 398 | export function setMaxListeners(n: number): void; 399 | export function listeners(event: string): Function[]; 400 | export function emit(event: string, ...args: any[]): boolean; 401 | } 402 | 403 | declare module "zlib" { 404 | import stream = require("stream"); 405 | export interface ZlibOptions { chunkSize?: number; windowBits?: number; level?: number; memLevel?: number; strategy?: number; dictionary?: any; } 406 | 407 | export interface Gzip extends stream.Transform { } 408 | export interface Gunzip extends stream.Transform { } 409 | export interface Deflate extends stream.Transform { } 410 | export interface Inflate extends stream.Transform { } 411 | export interface DeflateRaw extends stream.Transform { } 412 | export interface InflateRaw extends stream.Transform { } 413 | export interface Unzip extends stream.Transform { } 414 | 415 | export function createGzip(options?: ZlibOptions): Gzip; 416 | export function createGunzip(options?: ZlibOptions): Gunzip; 417 | export function createDeflate(options?: ZlibOptions): Deflate; 418 | export function createInflate(options?: ZlibOptions): Inflate; 419 | export function createDeflateRaw(options?: ZlibOptions): DeflateRaw; 420 | export function createInflateRaw(options?: ZlibOptions): InflateRaw; 421 | export function createUnzip(options?: ZlibOptions): Unzip; 422 | 423 | export function deflate(buf: Buffer, callback: (error: Error, result: any) =>void ): void; 424 | export function deflateRaw(buf: Buffer, callback: (error: Error, result: any) =>void ): void; 425 | export function gzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; 426 | export function gunzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; 427 | export function inflate(buf: Buffer, callback: (error: Error, result: any) =>void ): void; 428 | export function inflateRaw(buf: Buffer, callback: (error: Error, result: any) =>void ): void; 429 | export function unzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; 430 | 431 | // Constants 432 | export var Z_NO_FLUSH: number; 433 | export var Z_PARTIAL_FLUSH: number; 434 | export var Z_SYNC_FLUSH: number; 435 | export var Z_FULL_FLUSH: number; 436 | export var Z_FINISH: number; 437 | export var Z_BLOCK: number; 438 | export var Z_TREES: number; 439 | export var Z_OK: number; 440 | export var Z_STREAM_END: number; 441 | export var Z_NEED_DICT: number; 442 | export var Z_ERRNO: number; 443 | export var Z_STREAM_ERROR: number; 444 | export var Z_DATA_ERROR: number; 445 | export var Z_MEM_ERROR: number; 446 | export var Z_BUF_ERROR: number; 447 | export var Z_VERSION_ERROR: number; 448 | export var Z_NO_COMPRESSION: number; 449 | export var Z_BEST_SPEED: number; 450 | export var Z_BEST_COMPRESSION: number; 451 | export var Z_DEFAULT_COMPRESSION: number; 452 | export var Z_FILTERED: number; 453 | export var Z_HUFFMAN_ONLY: number; 454 | export var Z_RLE: number; 455 | export var Z_FIXED: number; 456 | export var Z_DEFAULT_STRATEGY: number; 457 | export var Z_BINARY: number; 458 | export var Z_TEXT: number; 459 | export var Z_ASCII: number; 460 | export var Z_UNKNOWN: number; 461 | export var Z_DEFLATED: number; 462 | export var Z_NULL: number; 463 | } 464 | 465 | declare module "os" { 466 | export function tmpDir(): string; 467 | export function hostname(): string; 468 | export function type(): string; 469 | export function platform(): string; 470 | export function arch(): string; 471 | export function release(): string; 472 | export function uptime(): number; 473 | export function loadavg(): number[]; 474 | export function totalmem(): number; 475 | export function freemem(): number; 476 | export function cpus(): { model: string; speed: number; times: { user: number; nice: number; sys: number; idle: number; irq: number; }; }[]; 477 | export function networkInterfaces(): any; 478 | export var EOL: string; 479 | } 480 | 481 | declare module "https" { 482 | import tls = require("tls"); 483 | import events = require("events"); 484 | import http = require("http"); 485 | 486 | export interface ServerOptions { 487 | pfx?: any; 488 | key?: any; 489 | passphrase?: string; 490 | cert?: any; 491 | ca?: any; 492 | crl?: any; 493 | ciphers?: string; 494 | honorCipherOrder?: boolean; 495 | requestCert?: boolean; 496 | rejectUnauthorized?: boolean; 497 | NPNProtocols?: any; 498 | SNICallback?: (servername: string) => any; 499 | } 500 | 501 | export interface RequestOptions { 502 | host?: string; 503 | hostname?: string; 504 | port?: number; 505 | path?: string; 506 | method?: string; 507 | headers?: any; 508 | auth?: string; 509 | agent?: any; 510 | pfx?: any; 511 | key?: any; 512 | passphrase?: string; 513 | cert?: any; 514 | ca?: any; 515 | ciphers?: string; 516 | rejectUnauthorized?: boolean; 517 | } 518 | 519 | export interface Agent { 520 | maxSockets: number; 521 | sockets: any; 522 | requests: any; 523 | } 524 | export var Agent: { 525 | new (options?: RequestOptions): Agent; 526 | }; 527 | export interface Server extends tls.Server { } 528 | export function createServer(options: ServerOptions, requestListener?: Function): Server; 529 | export function request(options: RequestOptions, callback?: (res: events.EventEmitter) =>void ): http.ClientRequest; 530 | export function get(options: RequestOptions, callback?: (res: events.EventEmitter) =>void ): http.ClientRequest; 531 | export var globalAgent: Agent; 532 | } 533 | 534 | declare module "punycode" { 535 | export function decode(string: string): string; 536 | export function encode(string: string): string; 537 | export function toUnicode(domain: string): string; 538 | export function toASCII(domain: string): string; 539 | export var ucs2: ucs2; 540 | interface ucs2 { 541 | decode(string: string): string; 542 | encode(codePoints: number[]): string; 543 | } 544 | export var version: any; 545 | } 546 | 547 | declare module "repl" { 548 | import stream = require("stream"); 549 | import events = require("events"); 550 | 551 | export interface ReplOptions { 552 | prompt?: string; 553 | input?: NodeJS.ReadableStream; 554 | output?: NodeJS.WritableStream; 555 | terminal?: boolean; 556 | eval?: Function; 557 | useColors?: boolean; 558 | useGlobal?: boolean; 559 | ignoreUndefined?: boolean; 560 | writer?: Function; 561 | } 562 | export function start(options: ReplOptions): events.EventEmitter; 563 | } 564 | 565 | declare module "readline" { 566 | import events = require("events"); 567 | import stream = require("stream"); 568 | 569 | export interface ReadLine extends events.EventEmitter { 570 | setPrompt(prompt: string, length: number): void; 571 | prompt(preserveCursor?: boolean): void; 572 | question(query: string, callback: Function): void; 573 | pause(): void; 574 | resume(): void; 575 | close(): void; 576 | write(data: any, key?: any): void; 577 | } 578 | export interface ReadLineOptions { 579 | input: NodeJS.ReadableStream; 580 | output: NodeJS.WritableStream; 581 | completer?: Function; 582 | terminal?: boolean; 583 | } 584 | export function createInterface(options: ReadLineOptions): ReadLine; 585 | } 586 | 587 | declare module "vm" { 588 | export interface Context { } 589 | export interface Script { 590 | runInThisContext(): void; 591 | runInNewContext(sandbox?: Context): void; 592 | } 593 | export function runInThisContext(code: string, filename?: string): void; 594 | export function runInNewContext(code: string, sandbox?: Context, filename?: string): void; 595 | export function runInContext(code: string, context: Context, filename?: string): void; 596 | export function createContext(initSandbox?: Context): Context; 597 | export function createScript(code: string, filename?: string): Script; 598 | } 599 | 600 | declare module "child_process" { 601 | import events = require("events"); 602 | import stream = require("stream"); 603 | 604 | export interface ChildProcess extends events.EventEmitter { 605 | stdin: stream.Writable; 606 | stdout: stream.Readable; 607 | stderr: stream.Readable; 608 | pid: number; 609 | kill(signal?: string): void; 610 | send(message: any, sendHandle: any): void; 611 | disconnect(): void; 612 | } 613 | 614 | export function spawn(command: string, args?: string[], options?: { 615 | cwd?: string; 616 | stdio?: any; 617 | custom?: any; 618 | env?: any; 619 | detached?: boolean; 620 | }): ChildProcess; 621 | export function exec(command: string, options: { 622 | cwd?: string; 623 | stdio?: any; 624 | customFds?: any; 625 | env?: any; 626 | encoding?: string; 627 | timeout?: number; 628 | maxBuffer?: number; 629 | killSignal?: string; 630 | }, callback: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; 631 | export function exec(command: string, callback: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; 632 | export function execFile(file: string, args: string[], options: { 633 | cwd?: string; 634 | stdio?: any; 635 | customFds?: any; 636 | env?: any; 637 | encoding?: string; 638 | timeout?: number; 639 | maxBuffer?: string; 640 | killSignal?: string; 641 | }, callback: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; 642 | export function fork(modulePath: string, args?: string[], options?: { 643 | cwd?: string; 644 | env?: any; 645 | encoding?: string; 646 | }): ChildProcess; 647 | } 648 | 649 | declare module "url" { 650 | export interface Url { 651 | href: string; 652 | protocol: string; 653 | auth: string; 654 | hostname: string; 655 | port: string; 656 | host: string; 657 | pathname: string; 658 | search: string; 659 | query: string; 660 | slashes: boolean; 661 | hash?: string; 662 | path?: string; 663 | } 664 | 665 | export interface UrlOptions { 666 | protocol?: string; 667 | auth?: string; 668 | hostname?: string; 669 | port?: string; 670 | host?: string; 671 | pathname?: string; 672 | search?: string; 673 | query?: any; 674 | hash?: string; 675 | path?: string; 676 | } 677 | 678 | export function parse(urlStr: string, parseQueryString?: boolean , slashesDenoteHost?: boolean ): Url; 679 | export function format(url: UrlOptions): string; 680 | export function resolve(from: string, to: string): string; 681 | } 682 | 683 | declare module "dns" { 684 | export function lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) =>void ): string; 685 | export function lookup(domain: string, callback: (err: Error, address: string, family: number) =>void ): string; 686 | export function resolve(domain: string, rrtype: string, callback: (err: Error, addresses: string[]) =>void ): string[]; 687 | export function resolve(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; 688 | export function resolve4(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; 689 | export function resolve6(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; 690 | export function resolveMx(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; 691 | export function resolveTxt(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; 692 | export function resolveSrv(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; 693 | export function resolveNs(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; 694 | export function resolveCname(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; 695 | export function reverse(ip: string, callback: (err: Error, domains: string[]) =>void ): string[]; 696 | } 697 | 698 | declare module "net" { 699 | import stream = require("stream"); 700 | 701 | export interface Socket extends stream.Duplex { 702 | // Extended base methods 703 | write(buffer: Buffer): boolean; 704 | write(buffer: Buffer, cb?: Function): boolean; 705 | write(str: string, cb?: Function): boolean; 706 | write(str: string, encoding?: string, cb?: Function): boolean; 707 | write(str: string, encoding?: string, fd?: string): boolean; 708 | 709 | connect(port: number, host?: string, connectionListener?: Function): void; 710 | connect(path: string, connectionListener?: Function): void; 711 | bufferSize: number; 712 | setEncoding(encoding?: string): void; 713 | write(data: any, encoding?: string, callback?: Function): void; 714 | destroy(): void; 715 | pause(): void; 716 | resume(): void; 717 | setTimeout(timeout: number, callback?: Function): void; 718 | setNoDelay(noDelay?: boolean): void; 719 | setKeepAlive(enable?: boolean, initialDelay?: number): void; 720 | address(): { port: number; family: string; address: string; }; 721 | remoteAddress: string; 722 | remotePort: number; 723 | bytesRead: number; 724 | bytesWritten: number; 725 | 726 | // Extended base methods 727 | end(): void; 728 | end(buffer: Buffer, cb?: Function): void; 729 | end(str: string, cb?: Function): void; 730 | end(str: string, encoding?: string, cb?: Function): void; 731 | end(data?: any, encoding?: string): void; 732 | } 733 | 734 | export var Socket: { 735 | new (options?: { fd?: string; type?: string; allowHalfOpen?: boolean; }): Socket; 736 | }; 737 | 738 | export interface Server extends Socket { 739 | listen(port: number, host?: string, backlog?: number, listeningListener?: Function): Server; 740 | listen(path: string, listeningListener?: Function): Server; 741 | listen(handle: any, listeningListener?: Function): Server; 742 | close(callback?: Function): Server; 743 | address(): { port: number; family: string; address: string; }; 744 | maxConnections: number; 745 | connections: number; 746 | } 747 | export function createServer(connectionListener?: (socket: Socket) =>void ): Server; 748 | export function createServer(options?: { allowHalfOpen?: boolean; }, connectionListener?: (socket: Socket) =>void ): Server; 749 | export function connect(options: { allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; 750 | export function connect(port: number, host?: string, connectionListener?: Function): Socket; 751 | export function connect(path: string, connectionListener?: Function): Socket; 752 | export function createConnection(options: { allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; 753 | export function createConnection(port: number, host?: string, connectionListener?: Function): Socket; 754 | export function createConnection(path: string, connectionListener?: Function): Socket; 755 | export function isIP(input: string): number; 756 | export function isIPv4(input: string): boolean; 757 | export function isIPv6(input: string): boolean; 758 | } 759 | 760 | declare module "dgram" { 761 | import events = require("events"); 762 | 763 | export function createSocket(type: string, callback?: Function): Socket; 764 | 765 | interface Socket extends events.EventEmitter { 766 | send(buf: Buffer, offset: number, length: number, port: number, address: string, callback?: Function): void; 767 | bind(port: number, address?: string): void; 768 | close(): void; 769 | address: { address: string; family: string; port: number; }; 770 | setBroadcast(flag: boolean): void; 771 | setMulticastTTL(ttl: number): void; 772 | setMulticastLoopback(flag: boolean): void; 773 | addMembership(multicastAddress: string, multicastInterface?: string): void; 774 | dropMembership(multicastAddress: string, multicastInterface?: string): void; 775 | } 776 | } 777 | 778 | declare module "fs" { 779 | import stream = require("stream"); 780 | import events = require("events"); 781 | 782 | interface Stats { 783 | isFile(): boolean; 784 | isDirectory(): boolean; 785 | isBlockDevice(): boolean; 786 | isCharacterDevice(): boolean; 787 | isSymbolicLink(): boolean; 788 | isFIFO(): boolean; 789 | isSocket(): boolean; 790 | dev: number; 791 | ino: number; 792 | mode: number; 793 | nlink: number; 794 | uid: number; 795 | gid: number; 796 | rdev: number; 797 | size: number; 798 | blksize: number; 799 | blocks: number; 800 | atime: Date; 801 | mtime: Date; 802 | ctime: Date; 803 | } 804 | 805 | interface FSWatcher extends events.EventEmitter { 806 | close(): void; 807 | } 808 | 809 | export interface ReadStream extends stream.Readable {} 810 | export interface WriteStream extends stream.Writable {} 811 | 812 | export function rename(oldPath: string, newPath: string, callback?: (err?: NodeJS.ErrnoException) => void): void; 813 | export function renameSync(oldPath: string, newPath: string): void; 814 | export function truncate(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; 815 | export function truncate(path: string, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; 816 | export function truncateSync(path: string, len?: number): void; 817 | export function ftruncate(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; 818 | export function ftruncate(fd: number, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; 819 | export function ftruncateSync(fd: number, len?: number): void; 820 | export function chown(path: string, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; 821 | export function chownSync(path: string, uid: number, gid: number): void; 822 | export function fchown(fd: number, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; 823 | export function fchownSync(fd: number, uid: number, gid: number): void; 824 | export function lchown(path: string, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; 825 | export function lchownSync(path: string, uid: number, gid: number): void; 826 | export function chmod(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; 827 | export function chmod(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; 828 | export function chmodSync(path: string, mode: number): void; 829 | export function chmodSync(path: string, mode: string): void; 830 | export function fchmod(fd: number, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; 831 | export function fchmod(fd: number, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; 832 | export function fchmodSync(fd: number, mode: number): void; 833 | export function fchmodSync(fd: number, mode: string): void; 834 | export function lchmod(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; 835 | export function lchmod(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; 836 | export function lchmodSync(path: string, mode: number): void; 837 | export function lchmodSync(path: string, mode: string): void; 838 | export function stat(path: string, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; 839 | export function lstat(path: string, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; 840 | export function fstat(fd: number, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; 841 | export function statSync(path: string): Stats; 842 | export function lstatSync(path: string): Stats; 843 | export function fstatSync(fd: number): Stats; 844 | export function link(srcpath: string, dstpath: string, callback?: (err?: NodeJS.ErrnoException) => void): void; 845 | export function linkSync(srcpath: string, dstpath: string): void; 846 | export function symlink(srcpath: string, dstpath: string, type?: string, callback?: (err?: NodeJS.ErrnoException) => void): void; 847 | export function symlinkSync(srcpath: string, dstpath: string, type?: string): void; 848 | export function readlink(path: string, callback?: (err: NodeJS.ErrnoException, linkString: string) => any): void; 849 | export function readlinkSync(path: string): string; 850 | export function realpath(path: string, callback?: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; 851 | export function realpath(path: string, cache: {[path: string]: string}, callback: (err: NodeJS.ErrnoException, resolvedPath: string) =>any): void; 852 | export function realpathSync(path: string, cache?: {[path: string]: string}): string; 853 | export function unlink(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; 854 | export function unlinkSync(path: string): void; 855 | export function rmdir(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; 856 | export function rmdirSync(path: string): void; 857 | export function mkdir(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; 858 | export function mkdir(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; 859 | export function mkdir(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; 860 | export function mkdirSync(path: string, mode?: number): void; 861 | export function mkdirSync(path: string, mode?: string): void; 862 | export function readdir(path: string, callback?: (err: NodeJS.ErrnoException, files: string[]) => void): void; 863 | export function readdirSync(path: string): string[]; 864 | export function close(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; 865 | export function closeSync(fd: number): void; 866 | export function open(path: string, flags: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; 867 | export function open(path: string, flags: string, mode: number, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; 868 | export function open(path: string, flags: string, mode: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; 869 | export function openSync(path: string, flags: string, mode?: number): number; 870 | export function openSync(path: string, flags: string, mode?: string): number; 871 | export function utimes(path: string, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void; 872 | export function utimes(path: string, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void; 873 | export function utimesSync(path: string, atime: number, mtime: number): void; 874 | export function utimesSync(path: string, atime: Date, mtime: Date): void; 875 | export function futimes(fd: number, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void; 876 | export function futimes(fd: number, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void; 877 | export function futimesSync(fd: number, atime: number, mtime: number): void; 878 | export function futimesSync(fd: number, atime: Date, mtime: Date): void; 879 | export function fsync(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; 880 | export function fsyncSync(fd: number): void; 881 | export function write(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; 882 | export function writeSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number; 883 | export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, bytesRead: number, buffer: Buffer) => void): void; 884 | export function readSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number; 885 | export function readFile(filename: string, encoding: string, callback: (err: NodeJS.ErrnoException, data: string) => void): void; 886 | export function readFile(filename: string, options: { encoding: string; flag?: string; }, callback: (err: NodeJS.ErrnoException, data: string) => void): void; 887 | export function readFile(filename: string, options: { flag?: string; }, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; 888 | export function readFile(filename: string, callback: (err: NodeJS.ErrnoException, data: Buffer) => void ): void; 889 | export function readFileSync(filename: string, encoding: string): string; 890 | export function readFileSync(filename: string, options: { encoding: string; flag?: string; }): string; 891 | export function readFileSync(filename: string, options?: { flag?: string; }): Buffer; 892 | export function writeFile(filename: string, data: any, callback?: (err: NodeJS.ErrnoException) => void): void; 893 | export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; 894 | export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; 895 | export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void; 896 | export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void; 897 | export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; 898 | export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; 899 | export function appendFile(filename: string, data: any, callback?: (err: NodeJS.ErrnoException) => void): void; 900 | export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void; 901 | export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void; 902 | export function watchFile(filename: string, listener: (curr: Stats, prev: Stats) => void): void; 903 | export function watchFile(filename: string, options: { persistent?: boolean; interval?: number; }, listener: (curr: Stats, prev: Stats) => void): void; 904 | export function unwatchFile(filename: string, listener?: (curr: Stats, prev: Stats) => void): void; 905 | export function watch(filename: string, listener?: (event: string, filename: string) => any): FSWatcher; 906 | export function watch(filename: string, options: { persistent?: boolean; }, listener?: (event: string, filename: string) => any): FSWatcher; 907 | export function exists(path: string, callback?: (exists: boolean) => void): void; 908 | export function existsSync(path: string): boolean; 909 | export function createReadStream(path: string, options?: { 910 | flags?: string; 911 | encoding?: string; 912 | fd?: string; 913 | mode?: number; 914 | bufferSize?: number; 915 | }): ReadStream; 916 | export function createReadStream(path: string, options?: { 917 | flags?: string; 918 | encoding?: string; 919 | fd?: string; 920 | mode?: string; 921 | bufferSize?: number; 922 | }): ReadStream; 923 | export function createWriteStream(path: string, options?: { 924 | flags?: string; 925 | encoding?: string; 926 | string?: string; 927 | }): WriteStream; 928 | } 929 | 930 | declare module "path" { 931 | export function normalize(p: string): string; 932 | export function join(...paths: any[]): string; 933 | export function resolve(...pathSegments: any[]): string; 934 | export function relative(from: string, to: string): string; 935 | export function dirname(p: string): string; 936 | export function basename(p: string, ext?: string): string; 937 | export function extname(p: string): string; 938 | export var sep: string; 939 | } 940 | 941 | declare module "string_decoder" { 942 | export interface NodeStringDecoder { 943 | write(buffer: Buffer): string; 944 | detectIncompleteChar(buffer: Buffer): number; 945 | } 946 | export var StringDecoder: { 947 | new (encoding: string): NodeStringDecoder; 948 | }; 949 | } 950 | 951 | declare module "tls" { 952 | import crypto = require("crypto"); 953 | import net = require("net"); 954 | import stream = require("stream"); 955 | 956 | var CLIENT_RENEG_LIMIT: number; 957 | var CLIENT_RENEG_WINDOW: number; 958 | 959 | export interface TlsOptions { 960 | pfx?: any; //string or buffer 961 | key?: any; //string or buffer 962 | passphrase?: string; 963 | cert?: any; 964 | ca?: any; //string or buffer 965 | crl?: any; //string or string array 966 | ciphers?: string; 967 | honorCipherOrder?: any; 968 | requestCert?: boolean; 969 | rejectUnauthorized?: boolean; 970 | NPNProtocols?: any; //array or Buffer; 971 | SNICallback?: (servername: string) => any; 972 | } 973 | 974 | export interface ConnectionOptions { 975 | host?: string; 976 | port?: number; 977 | socket?: net.Socket; 978 | pfx?: any; //string | Buffer 979 | key?: any; //string | Buffer 980 | passphrase?: string; 981 | cert?: any; //string | Buffer 982 | ca?: any; //Array of string | Buffer 983 | rejectUnauthorized?: boolean; 984 | NPNProtocols?: any; //Array of string | Buffer 985 | servername?: string; 986 | } 987 | 988 | export interface Server extends net.Server { 989 | // Extended base methods 990 | listen(port: number, host?: string, backlog?: number, listeningListener?: Function): Server; 991 | listen(path: string, listeningListener?: Function): Server; 992 | listen(handle: any, listeningListener?: Function): Server; 993 | 994 | listen(port: number, host?: string, callback?: Function): Server; 995 | close(): Server; 996 | address(): { port: number; family: string; address: string; }; 997 | addContext(hostName: string, credentials: { 998 | key: string; 999 | cert: string; 1000 | ca: string; 1001 | }): void; 1002 | maxConnections: number; 1003 | connections: number; 1004 | } 1005 | 1006 | export interface ClearTextStream extends stream.Duplex { 1007 | authorized: boolean; 1008 | authorizationError: Error; 1009 | getPeerCertificate(): any; 1010 | getCipher: { 1011 | name: string; 1012 | version: string; 1013 | }; 1014 | address: { 1015 | port: number; 1016 | family: string; 1017 | address: string; 1018 | }; 1019 | remoteAddress: string; 1020 | remotePort: number; 1021 | } 1022 | 1023 | export interface SecurePair { 1024 | encrypted: any; 1025 | cleartext: any; 1026 | } 1027 | 1028 | export function createServer(options: TlsOptions, secureConnectionListener?: (cleartextStream: ClearTextStream) =>void ): Server; 1029 | export function connect(options: TlsOptions, secureConnectionListener?: () =>void ): ClearTextStream; 1030 | export function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () =>void ): ClearTextStream; 1031 | export function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () =>void ): ClearTextStream; 1032 | export function createSecurePair(credentials?: crypto.Credentials, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; 1033 | } 1034 | 1035 | declare module "crypto" { 1036 | export interface CredentialDetails { 1037 | pfx: string; 1038 | key: string; 1039 | passphrase: string; 1040 | cert: string; 1041 | ca: any; //string | string array 1042 | crl: any; //string | string array 1043 | ciphers: string; 1044 | } 1045 | export interface Credentials { context?: any; } 1046 | export function createCredentials(details: CredentialDetails): Credentials; 1047 | export function createHash(algorithm: string): Hash; 1048 | export function createHmac(algorithm: string, key: string): Hmac; 1049 | interface Hash { 1050 | update(data: any, input_encoding?: string): Hash; 1051 | digest(encoding?: string): string; 1052 | } 1053 | interface Hmac { 1054 | update(data: any, input_encoding?: string): Hmac; 1055 | digest(encoding?: string): string; 1056 | } 1057 | export function createCipher(algorithm: string, password: any): Cipher; 1058 | export function createCipheriv(algorithm: string, key: any, iv: any): Cipher; 1059 | interface Cipher { 1060 | update(data: any, input_encoding?: string, output_encoding?: string): string; 1061 | final(output_encoding?: string): string; 1062 | setAutoPadding(auto_padding: boolean): void; 1063 | createDecipher(algorithm: string, password: any): Decipher; 1064 | createDecipheriv(algorithm: string, key: any, iv: any): Decipher; 1065 | } 1066 | interface Decipher { 1067 | update(data: any, input_encoding?: string, output_encoding?: string): void; 1068 | final(output_encoding?: string): string; 1069 | setAutoPadding(auto_padding: boolean): void; 1070 | } 1071 | export function createSign(algorithm: string): Signer; 1072 | interface Signer { 1073 | update(data: any): void; 1074 | sign(private_key: string, output_format: string): string; 1075 | } 1076 | export function createVerify(algorith: string): Verify; 1077 | interface Verify { 1078 | update(data: any): void; 1079 | verify(object: string, signature: string, signature_format?: string): boolean; 1080 | } 1081 | export function createDiffieHellman(prime_length: number): DiffieHellman; 1082 | export function createDiffieHellman(prime: number, encoding?: string): DiffieHellman; 1083 | interface DiffieHellman { 1084 | generateKeys(encoding?: string): string; 1085 | computeSecret(other_public_key: string, input_encoding?: string, output_encoding?: string): string; 1086 | getPrime(encoding?: string): string; 1087 | getGenerator(encoding: string): string; 1088 | getPublicKey(encoding?: string): string; 1089 | getPrivateKey(encoding?: string): string; 1090 | setPublicKey(public_key: string, encoding?: string): void; 1091 | setPrivateKey(public_key: string, encoding?: string): void; 1092 | } 1093 | export function getDiffieHellman(group_name: string): DiffieHellman; 1094 | export function pbkdf2(password: string, salt: string, iterations: number, keylen: number, callback: (err: Error, derivedKey: string) => any): void; 1095 | export function pbkdf2Sync(password: string, salt: string, iterations: number, keylen: number) : Buffer; 1096 | export function randomBytes(size: number): Buffer; 1097 | export function randomBytes(size: number, callback: (err: Error, buf: Buffer) =>void ): void; 1098 | export function pseudoRandomBytes(size: number): Buffer; 1099 | export function pseudoRandomBytes(size: number, callback: (err: Error, buf: Buffer) =>void ): void; 1100 | } 1101 | 1102 | declare module "stream" { 1103 | import events = require("events"); 1104 | 1105 | export interface ReadableOptions { 1106 | highWaterMark?: number; 1107 | encoding?: string; 1108 | objectMode?: boolean; 1109 | } 1110 | 1111 | export class Readable extends events.EventEmitter implements NodeJS.ReadableStream { 1112 | readable: boolean; 1113 | constructor(opts?: ReadableOptions); 1114 | _read(size: number): void; 1115 | read(size?: number): any; 1116 | setEncoding(encoding: string): void; 1117 | pause(): void; 1118 | resume(): void; 1119 | pipe(destination: T, options?: { end?: boolean; }): T; 1120 | unpipe(destination?: T): void; 1121 | unshift(chunk: string): void; 1122 | unshift(chunk: Buffer): void; 1123 | wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; 1124 | push(chunk: any, encoding?: string): boolean; 1125 | } 1126 | 1127 | export interface WritableOptions { 1128 | highWaterMark?: number; 1129 | decodeStrings?: boolean; 1130 | } 1131 | 1132 | export class Writable extends events.EventEmitter implements NodeJS.WritableStream { 1133 | writable: boolean; 1134 | constructor(opts?: WritableOptions); 1135 | _write(data: Buffer, encoding: string, callback: Function): void; 1136 | _write(data: string, encoding: string, callback: Function): void; 1137 | write(buffer: Buffer, cb?: Function): boolean; 1138 | write(str: string, cb?: Function): boolean; 1139 | write(str: string, encoding?: string, cb?: Function): boolean; 1140 | end(): void; 1141 | end(buffer: Buffer, cb?: Function): void; 1142 | end(str: string, cb?: Function): void; 1143 | end(str: string, encoding?: string, cb?: Function): void; 1144 | } 1145 | 1146 | export interface DuplexOptions extends ReadableOptions, WritableOptions { 1147 | allowHalfOpen?: boolean; 1148 | } 1149 | 1150 | // Note: Duplex extends both Readable and Writable. 1151 | export class Duplex extends Readable implements NodeJS.ReadWriteStream { 1152 | writable: boolean; 1153 | constructor(opts?: DuplexOptions); 1154 | _write(data: Buffer, encoding: string, callback: Function): void; 1155 | _write(data: string, encoding: string, callback: Function): void; 1156 | write(buffer: Buffer, cb?: Function): boolean; 1157 | write(str: string, cb?: Function): boolean; 1158 | write(str: string, encoding?: string, cb?: Function): boolean; 1159 | end(): void; 1160 | end(buffer: Buffer, cb?: Function): void; 1161 | end(str: string, cb?: Function): void; 1162 | end(str: string, encoding?: string, cb?: Function): void; 1163 | } 1164 | 1165 | export interface TransformOptions extends ReadableOptions, WritableOptions {} 1166 | 1167 | // Note: Transform lacks the _read and _write methods of Readable/Writable. 1168 | export class Transform extends events.EventEmitter implements NodeJS.ReadWriteStream { 1169 | readable: boolean; 1170 | writable: boolean; 1171 | constructor(opts?: TransformOptions); 1172 | _transform(chunk: Buffer, encoding: string, callback: Function): void; 1173 | _transform(chunk: string, encoding: string, callback: Function): void; 1174 | _flush(callback: Function): void; 1175 | read(size?: number): any; 1176 | setEncoding(encoding: string): void; 1177 | pause(): void; 1178 | resume(): void; 1179 | pipe(destination: T, options?: { end?: boolean; }): T; 1180 | unpipe(destination?: T): void; 1181 | unshift(chunk: string): void; 1182 | unshift(chunk: Buffer): void; 1183 | wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; 1184 | push(chunk: any, encoding?: string): boolean; 1185 | write(buffer: Buffer, cb?: Function): boolean; 1186 | write(str: string, cb?: Function): boolean; 1187 | write(str: string, encoding?: string, cb?: Function): boolean; 1188 | end(): void; 1189 | end(buffer: Buffer, cb?: Function): void; 1190 | end(str: string, cb?: Function): void; 1191 | end(str: string, encoding?: string, cb?: Function): void; 1192 | } 1193 | 1194 | export class PassThrough extends Transform {} 1195 | } 1196 | 1197 | declare module "util" { 1198 | export interface InspectOptions { 1199 | showHidden?: boolean; 1200 | depth?: number; 1201 | colors?: boolean; 1202 | customInspect?: boolean; 1203 | } 1204 | 1205 | export function format(format: any, ...param: any[]): string; 1206 | export function debug(string: string): void; 1207 | export function error(...param: any[]): void; 1208 | export function puts(...param: any[]): void; 1209 | export function print(...param: any[]): void; 1210 | export function log(string: string): void; 1211 | export function inspect(object: any, showHidden?: boolean, depth?: number, color?: boolean): string; 1212 | export function inspect(object: any, options: InspectOptions): string; 1213 | export function isArray(object: any): boolean; 1214 | export function isRegExp(object: any): boolean; 1215 | export function isDate(object: any): boolean; 1216 | export function isError(object: any): boolean; 1217 | export function inherits(constructor: any, superConstructor: any): void; 1218 | } 1219 | 1220 | declare module "assert" { 1221 | function internal (value: any, message?: string): void; 1222 | module internal { 1223 | export class AssertionError implements Error { 1224 | name: string; 1225 | message: string; 1226 | actual: any; 1227 | expected: any; 1228 | operator: string; 1229 | generatedMessage: boolean; 1230 | 1231 | constructor(options?: {message?: string; actual?: any; expected?: any; 1232 | operator?: string; stackStartFunction?: Function}); 1233 | } 1234 | 1235 | export function fail(actual?: any, expected?: any, message?: string, operator?: string): void; 1236 | export function ok(value: any, message?: string): void; 1237 | export function equal(actual: any, expected: any, message?: string): void; 1238 | export function notEqual(actual: any, expected: any, message?: string): void; 1239 | export function deepEqual(actual: any, expected: any, message?: string): void; 1240 | export function notDeepEqual(acutal: any, expected: any, message?: string): void; 1241 | export function strictEqual(actual: any, expected: any, message?: string): void; 1242 | export function notStrictEqual(actual: any, expected: any, message?: string): void; 1243 | export var throws: { 1244 | (block: Function, message?: string): void; 1245 | (block: Function, error: Function, message?: string): void; 1246 | (block: Function, error: RegExp, message?: string): void; 1247 | (block: Function, error: (err: any) => boolean, message?: string): void; 1248 | }; 1249 | 1250 | export var doesNotThrow: { 1251 | (block: Function, message?: string): void; 1252 | (block: Function, error: Function, message?: string): void; 1253 | (block: Function, error: RegExp, message?: string): void; 1254 | (block: Function, error: (err: any) => boolean, message?: string): void; 1255 | }; 1256 | 1257 | export function ifError(value: any): void; 1258 | } 1259 | 1260 | export = internal; 1261 | } 1262 | 1263 | declare module "tty" { 1264 | import net = require("net"); 1265 | 1266 | export function isatty(fd: number): boolean; 1267 | export interface ReadStream extends net.Socket { 1268 | isRaw: boolean; 1269 | setRawMode(mode: boolean): void; 1270 | } 1271 | export interface WriteStream extends net.Socket { 1272 | columns: number; 1273 | rows: number; 1274 | } 1275 | } 1276 | 1277 | declare module "domain" { 1278 | import events = require("events"); 1279 | 1280 | export class Domain extends events.EventEmitter { 1281 | run(fn: Function): void; 1282 | add(emitter: events.EventEmitter): void; 1283 | remove(emitter: events.EventEmitter): void; 1284 | bind(cb: (err: Error, data: any) => any): any; 1285 | intercept(cb: (data: any) => any): any; 1286 | dispose(): void; 1287 | 1288 | addListener(event: string, listener: Function): Domain; 1289 | on(event: string, listener: Function): Domain; 1290 | once(event: string, listener: Function): Domain; 1291 | removeListener(event: string, listener: Function): Domain; 1292 | removeAllListeners(event?: string): Domain; 1293 | } 1294 | 1295 | export function create(): Domain; 1296 | } -------------------------------------------------------------------------------- /src/packer/CommandLine.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | exports.optionDeclarations = [ 3 | { 4 | name: "help", 5 | shortName: "h", 6 | type: "boolean", 7 | description: "Print help message." 8 | }, 9 | { 10 | name: "listFiles", 11 | shortName: "l", 12 | type: "boolean", 13 | description: "Print names of sorted files part of the compilation." 14 | }, 15 | { 16 | name: "project", 17 | shortName: "p", 18 | type: "string", 19 | description: "Compile the project in the given directory.." 20 | }, 21 | { 22 | name: "version", 23 | shortName: "v", 24 | type: "boolean", 25 | description: "Print the tspack’s version." 26 | } 27 | ]; 28 | var optionNameMapCache; 29 | function getOptionNameMap() { 30 | if (optionNameMapCache) { 31 | return optionNameMapCache; 32 | } 33 | var optionNameMap = {}; 34 | var shortOptionNames = {}; 35 | exports.optionDeclarations.forEach(function (option) { 36 | optionNameMap[option.name.toLowerCase()] = option; 37 | if (option.shortName) { 38 | shortOptionNames[option.shortName] = option.name; 39 | } 40 | }); 41 | optionNameMapCache = { optionNameMap: optionNameMap, shortOptionNames: shortOptionNames }; 42 | return optionNameMapCache; 43 | } 44 | function parse(args) { 45 | var options = {}; 46 | options.errors = []; 47 | var _a = getOptionNameMap(), optionNameMap = _a.optionNameMap, shortOptionNames = _a.shortOptionNames; 48 | var i = 0; 49 | while (i < args.length) { 50 | var s = args[i]; 51 | i++; 52 | if (s.charAt(0) == "-") { 53 | s = s.slice(s.charAt(1) == "-" ? 2 : 1).toLowerCase(); 54 | if (s in shortOptionNames) { 55 | s = shortOptionNames[s]; 56 | } 57 | if (s in optionNameMap) { 58 | var opt = optionNameMap[s]; 59 | if (!args[i] && opt.type !== "boolean") { 60 | options.errors.push("Option '" + opt.name + "' expects an argument."); 61 | } 62 | switch (opt.type) { 63 | case "number": 64 | options[opt.name] = parseInt(args[i]); 65 | i++; 66 | break; 67 | case "boolean": 68 | options[opt.name] = true; 69 | break; 70 | case "string": 71 | options[opt.name] = args[i] || ""; 72 | i++; 73 | break; 74 | } 75 | } 76 | else { 77 | options.errors.push("Unknown compiler option '" + s + "'."); 78 | } 79 | } 80 | } 81 | return options; 82 | } 83 | exports.parse = parse; 84 | -------------------------------------------------------------------------------- /src/packer/CommandLine.ts: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////////////////// 2 | // 3 | // The MIT License (MIT) 4 | // 5 | // Copyright (c) 2015-present, Dom Chen. 6 | // All rights reserved. 7 | // 8 | // Permission is hereby granted, free of charge, to any person obtaining a copy of 9 | // this software and associated documentation files (the "Software"), to deal in the 10 | // Software without restriction, including without limitation the rights to use, copy, 11 | // modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, 12 | // and to permit persons to whom the Software is furnished to do so, subject to the 13 | // following conditions: 14 | // 15 | // The above copyright notice and this permission notice shall be included in all 16 | // copies or substantial portions of the Software. 17 | // 18 | // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 19 | // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 21 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 22 | // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 23 | // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 24 | // 25 | ////////////////////////////////////////////////////////////////////////////////////// 26 | 27 | export interface OptionDeclaration { 28 | name:string; 29 | type:string; 30 | shortName?:string; 31 | description?:string; 32 | } 33 | 34 | export const optionDeclarations:OptionDeclaration[] = [ 35 | { 36 | name: "help", 37 | shortName: "h", 38 | type: "boolean", 39 | description: "Print help message." 40 | }, 41 | { 42 | name: "listFiles", 43 | shortName: "l", 44 | type: "boolean", 45 | description: "Print names of sorted files part of the compilation." 46 | }, 47 | { 48 | name: "project", 49 | shortName: "p", 50 | type: "string", 51 | description: "Compile the project in the given directory.." 52 | }, 53 | { 54 | name: "version", 55 | shortName: "v", 56 | type: "boolean", 57 | description: "Print the tspack’s version." 58 | }//, 59 | // { 60 | // name: "watch", 61 | // shortName: "w", 62 | // type: "boolean", 63 | // description: "Watch input files and trigger recompilation on changes." 64 | // } 65 | ]; 66 | 67 | export interface CommandLineOption { 68 | help?:boolean; 69 | listFiles?:boolean; 70 | project?:string; 71 | version?:boolean; 72 | watch?:boolean; 73 | errors?:string[] 74 | } 75 | 76 | interface Map { 77 | [index:string]:T; 78 | } 79 | 80 | interface OptionNameMap { 81 | optionNameMap:Map; 82 | shortOptionNames:Map; 83 | } 84 | 85 | let optionNameMapCache:OptionNameMap; 86 | 87 | function getOptionNameMap():OptionNameMap { 88 | if (optionNameMapCache) { 89 | return optionNameMapCache; 90 | } 91 | 92 | const optionNameMap:Map = {}; 93 | const shortOptionNames:Map = {}; 94 | optionDeclarations.forEach(option => { 95 | optionNameMap[option.name.toLowerCase()] = option; 96 | if (option.shortName) { 97 | shortOptionNames[option.shortName] = option.name; 98 | } 99 | }); 100 | optionNameMapCache = {optionNameMap, shortOptionNames}; 101 | return optionNameMapCache; 102 | } 103 | 104 | export function parse(args:string[]):CommandLineOption { 105 | const options:CommandLineOption = {}; 106 | options.errors = []; 107 | const {optionNameMap, shortOptionNames} = getOptionNameMap(); 108 | let i = 0; 109 | while (i < args.length) { 110 | let s = args[i]; 111 | i++; 112 | if (s.charAt(0) == "-") { 113 | s = s.slice(s.charAt(1) == "-" ? 2 : 1).toLowerCase(); 114 | if (s in shortOptionNames) { 115 | s = shortOptionNames[s]; 116 | } 117 | 118 | if (s in optionNameMap) { 119 | const opt = optionNameMap[s]; 120 | if (!args[i] && opt.type !== "boolean") { 121 | options.errors.push("Option '" + opt.name + "' expects an argument."); 122 | } 123 | switch (opt.type) { 124 | case "number": 125 | options[opt.name] = parseInt(args[i]); 126 | i++; 127 | break; 128 | case "boolean": 129 | options[opt.name] = true; 130 | break; 131 | case "string": 132 | options[opt.name] = args[i] || ""; 133 | i++; 134 | break; 135 | } 136 | } 137 | else { 138 | options.errors.push("Unknown compiler option '" + s + "'."); 139 | } 140 | } 141 | } 142 | return options; 143 | } -------------------------------------------------------------------------------- /src/packer/Compiler.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var ts = require("typescript-plus"); 3 | var config = require("./Config"); 4 | var utils = require("./Utils"); 5 | function emitModule(moduleConfig, compilerOptions, errors) { 6 | var options = config.getCompilerOptions(moduleConfig, compilerOptions); 7 | var fileNames = moduleConfig.fileNames; 8 | var program = ts.createProgram(fileNames, options); 9 | var sortResult = ts.reorderSourceFiles(program); 10 | if (sortResult.circularReferences.length > 0) { 11 | var error = ""; 12 | error += "error: circular references in '" + moduleConfig.name + "' :" + ts.sys.newLine; 13 | error += " at " + sortResult.circularReferences.join(ts.sys.newLine + " at ") + ts.sys.newLine + " at ..."; 14 | errors.push(error); 15 | return sortResult.sortedFileNames; 16 | } 17 | var emitResult = program.emit(); 18 | var diagnostics = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics); 19 | if (diagnostics.length > 0) { 20 | diagnostics.forEach(function (diagnostic) { 21 | errors.push(utils.formatDiagnostics([diagnostic])); 22 | }); 23 | } 24 | return sortResult.sortedFileNames; 25 | } 26 | exports.emitModule = emitModule; 27 | -------------------------------------------------------------------------------- /src/packer/Compiler.ts: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////////////////// 2 | // 3 | // The MIT License (MIT) 4 | // 5 | // Copyright (c) 2015-present, Dom Chen. 6 | // All rights reserved. 7 | // 8 | // Permission is hereby granted, free of charge, to any person obtaining a copy of 9 | // this software and associated documentation files (the "Software"), to deal in the 10 | // Software without restriction, including without limitation the rights to use, copy, 11 | // modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, 12 | // and to permit persons to whom the Software is furnished to do so, subject to the 13 | // following conditions: 14 | // 15 | // The above copyright notice and this permission notice shall be included in all 16 | // copies or substantial portions of the Software. 17 | // 18 | // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 19 | // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 21 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 22 | // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 23 | // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 24 | // 25 | ////////////////////////////////////////////////////////////////////////////////////// 26 | 27 | import * as ts from "typescript-plus"; 28 | import * as config from "./Config"; 29 | import * as utils from "./Utils"; 30 | 31 | 32 | export function emitModule(moduleConfig:config.ModuleConfig, compilerOptions:ts.CompilerOptions, errors:string[]):string[] { 33 | let options = config.getCompilerOptions(moduleConfig, compilerOptions); 34 | let fileNames = moduleConfig.fileNames; 35 | let program = ts.createProgram(fileNames, options); 36 | 37 | let sortResult = ts.reorderSourceFiles(program); 38 | if (sortResult.circularReferences.length > 0) { 39 | let error:string = ""; 40 | error += "error: circular references in '" + moduleConfig.name + "' :" + ts.sys.newLine; 41 | error += " at " + sortResult.circularReferences.join(ts.sys.newLine + " at ") + ts.sys.newLine + " at ..."; 42 | errors.push(error); 43 | return sortResult.sortedFileNames; 44 | } 45 | 46 | let emitResult = program.emit(); 47 | let diagnostics = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics); 48 | if (diagnostics.length > 0) { 49 | diagnostics.forEach(diagnostic => { 50 | errors.push(utils.formatDiagnostics([diagnostic])); 51 | }); 52 | } 53 | return sortResult.sortedFileNames; 54 | } -------------------------------------------------------------------------------- /src/packer/Config.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var path = require("path"); 3 | var ts = require("typescript-plus"); 4 | var utils = require("./Utils"); 5 | var compilerOptionKeys = [ 6 | "allowJs", 7 | "allowSyntheticDefaultImports", 8 | "allowUnreachableCode", 9 | "allowUnusedLabels", 10 | "baseUrl", 11 | "charset", 12 | "declaration", 13 | "declarationDir", 14 | "disableSizeLimit", 15 | "emitBOM", 16 | "emitDecoratorMetadata", 17 | "experimentalDecorators", 18 | "forceConsistentCasingInFileNames", 19 | "inlineSourceMap", 20 | "inlineSources", 21 | "isolatedModules", 22 | "lib", 23 | "locale", 24 | "mapRoot", 25 | "maxNodeModuleJsDepth", 26 | "noEmit", 27 | "noEmitHelpers", 28 | "noEmitOnError", 29 | "noErrorTruncation", 30 | "noFallthroughCasesInSwitch", 31 | "noImplicitAny", 32 | "noImplicitReturns", 33 | "noImplicitThis", 34 | "noUnusedLocals", 35 | "noUnusedParameters", 36 | "noImplicitUseStrict", 37 | "noLib", 38 | "noResolve", 39 | "outDir", 40 | "outFile", 41 | "preserveConstEnums", 42 | "project", 43 | "reactNamespace", 44 | "removeComments", 45 | "rootDir", 46 | "skipLibCheck", 47 | "skipDefaultLibCheck", 48 | "sourceMap", 49 | "sourceRoot", 50 | "strictNullChecks", 51 | "suppressExcessPropertyErrors", 52 | "suppressImplicitAnyIndexErrors", 53 | "traceResolution", 54 | "types", 55 | "typeRoots", 56 | "accessorOptimization", 57 | "defines", 58 | "emitReflection", 59 | "noEmitJs", 60 | "reorderFiles" 61 | ]; 62 | function getCompilerOptions(moduleConfig, existOptions) { 63 | var json = JSON.stringify(existOptions); 64 | var options = JSON.parse(json); 65 | for (var _i = 0, compilerOptionKeys_1 = compilerOptionKeys; _i < compilerOptionKeys_1.length; _i++) { 66 | var option = compilerOptionKeys_1[_i]; 67 | if (moduleConfig[option] !== undefined) { 68 | options[option] = moduleConfig[option]; 69 | } 70 | } 71 | if (moduleConfig.name) { 72 | options.module = ts.ModuleKind.None; 73 | } 74 | return options; 75 | } 76 | exports.getCompilerOptions = getCompilerOptions; 77 | function findConfigFile(searchPath) { 78 | while (true) { 79 | var fileName = utils.joinPath(searchPath, "tspack.json"); 80 | if (ts.sys.fileExists(fileName)) { 81 | return fileName; 82 | } 83 | fileName = utils.joinPath(searchPath, "tsconfig.json"); 84 | if (ts.sys.fileExists(fileName)) { 85 | return fileName; 86 | } 87 | var parentPath = path.dirname(searchPath); 88 | if (parentPath === searchPath) { 89 | break; 90 | } 91 | searchPath = parentPath; 92 | } 93 | return ""; 94 | } 95 | exports.findConfigFile = findConfigFile; 96 | function parseOptionsFromFile(configFileName) { 97 | var jsonResult = ts.parseConfigFileTextToJson(configFileName, ts.sys.readFile(configFileName)); 98 | var configObject = jsonResult.config; 99 | if (!configObject) { 100 | var result = {}; 101 | result.errors = [utils.formatDiagnostics([jsonResult.error])]; 102 | return result; 103 | } 104 | var baseDir = path.dirname(configFileName); 105 | return parseOptionsFromJson(configObject, baseDir, configFileName); 106 | } 107 | exports.parseOptionsFromFile = parseOptionsFromFile; 108 | function parseOptionsFromJson(jsonOptions, basePath, configFileName) { 109 | var result = {}; 110 | result.errors = []; 111 | var compilerResult = ts.convertCompilerOptionsFromJson(jsonOptions["compilerOptions"], basePath, configFileName); 112 | if (compilerResult.errors.length > 0) { 113 | result.errors.push(utils.formatDiagnostics(compilerResult.errors)); 114 | return result; 115 | } 116 | var compilerOptions = compilerResult.options; 117 | result.compilerOptions = compilerOptions; 118 | var outDir = basePath; 119 | if (compilerOptions.outDir) { 120 | outDir = compilerOptions.outDir; 121 | } 122 | var modules = jsonOptions["modules"]; 123 | if (modules) { 124 | formatModules(modules, outDir, basePath, result.errors); 125 | sortOnDependency(modules, result.errors); 126 | modules.forEach(function (moduleConfig) { 127 | moduleConfig.fileNames = getFileNames(moduleConfig, basePath, result.errors); 128 | }); 129 | } 130 | else { 131 | var module_1 = {}; 132 | var optionResult = ts.parseJsonConfigFileContent(jsonOptions, ts.sys, basePath); 133 | if (optionResult.errors.length > 0) { 134 | result.errors.push(utils.formatDiagnostics(optionResult.errors)); 135 | module_1.fileNames = []; 136 | } 137 | else { 138 | module_1.fileNames = optionResult.fileNames; 139 | } 140 | if (compilerOptions.outFile) { 141 | module_1.name = path.basename(compilerOptions.outFile); 142 | module_1.outFile = compilerOptions.outFile; 143 | } 144 | modules = [module_1]; 145 | } 146 | result.modules = modules; 147 | return result; 148 | } 149 | exports.parseOptionsFromJson = parseOptionsFromJson; 150 | function formatModules(moduleConfigs, outDir, basePath, errors) { 151 | var tsdMap = {}; 152 | moduleConfigs.forEach(function (moduleConfig) { 153 | tsdMap[moduleConfig.name] = moduleConfig; 154 | }); 155 | moduleConfigs.forEach(function (moduleConfig) { 156 | var outFile = moduleConfig.outFile = getModuleFileName(moduleConfig, outDir, basePath); 157 | if (outFile.substr(outFile.length - 3).toLowerCase() == ".js") { 158 | outFile = outFile.substr(0, outFile.length - 3); 159 | } 160 | moduleConfig.declarationFileName = outFile + ".d.ts"; 161 | if (isArray(moduleConfig.dependencies)) { 162 | var dependencies = moduleConfig.dependencies; 163 | moduleConfig.dependentModules = []; 164 | for (var i = 0; i < dependencies.length; i++) { 165 | var config = tsdMap[dependencies[i]]; 166 | if (!config) { 167 | errors.push("error : could not find the name of module dependency : " + dependencies[i]); 168 | continue; 169 | } 170 | moduleConfig.dependentModules.push(config); 171 | config.declaration = true; 172 | } 173 | } 174 | }); 175 | } 176 | function getModuleFileName(moduleConfig, outDir, basePath) { 177 | if (moduleConfig.outFile) { 178 | return utils.joinPath(basePath, moduleConfig.outFile); 179 | } 180 | return utils.joinPath(outDir || basePath, moduleConfig.name + ".js"); 181 | } 182 | function isArray(value) { 183 | return Array.isArray ? Array.isArray(value) : value instanceof Array; 184 | } 185 | function getFileNames(moduleConfig, baseDir, errors) { 186 | var optionResult = ts.parseJsonConfigFileContent(moduleConfig, ts.sys, baseDir); 187 | if (optionResult.errors.length > 0) { 188 | errors.push(utils.formatDiagnostics(optionResult.errors)); 189 | return []; 190 | } 191 | var fileNames = optionResult.fileNames; 192 | if (moduleConfig.dependentModules) { 193 | var declarations_1 = []; 194 | moduleConfig.dependentModules.forEach(function (config) { 195 | declarations_1.push(config.declarationFileName); 196 | }); 197 | fileNames = declarations_1.concat(fileNames); 198 | } 199 | return fileNames; 200 | } 201 | function sortOnDependency(modules, errors) { 202 | var dependencyMap = {}; 203 | for (var _i = 0, modules_1 = modules; _i < modules_1.length; _i++) { 204 | var module_2 = modules_1[_i]; 205 | dependencyMap[module_2.name] = module_2.dependencies; 206 | } 207 | var moduleWeightMap = {}; 208 | for (var _a = 0, modules_2 = modules; _a < modules_2.length; _a++) { 209 | var module_3 = modules_2[_a]; 210 | var moduleName = module_3.name; 211 | var references = updateModuleWeight(moduleName, 0, moduleWeightMap, dependencyMap, [moduleName]); 212 | if (references) { 213 | var errorText = "error : circular references in module dependencies configuration :" + ts.sys.newLine; 214 | errorText += " at " + references.join(ts.sys.newLine + " at ") + ts.sys.newLine + " at ..."; 215 | errors.push(errorText); 216 | return; 217 | } 218 | } 219 | modules.sort(function (a, b) { 220 | return moduleWeightMap[b.name] - moduleWeightMap[a.name]; 221 | }); 222 | } 223 | function updateModuleWeight(moduleName, weight, moduleWeightMap, dependencyMap, references) { 224 | if (moduleWeightMap[moduleName] === undefined) { 225 | moduleWeightMap[moduleName] = weight; 226 | } 227 | else { 228 | if (moduleWeightMap[moduleName] < weight) { 229 | moduleWeightMap[moduleName] = weight; 230 | } 231 | else { 232 | return null; 233 | } 234 | } 235 | var list = dependencyMap[moduleName]; 236 | if (!list) { 237 | return null; 238 | } 239 | for (var _i = 0, list_1 = list; _i < list_1.length; _i++) { 240 | var parentPath = list_1[_i]; 241 | if (references.indexOf(parentPath) != -1) { 242 | references.push(parentPath); 243 | return references; 244 | } 245 | var result = updateModuleWeight(parentPath, weight + 1, moduleWeightMap, dependencyMap, references.concat(parentPath)); 246 | if (result) { 247 | return result; 248 | } 249 | } 250 | return null; 251 | } 252 | -------------------------------------------------------------------------------- /src/packer/Config.ts: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////////////////// 2 | // 3 | // The MIT License (MIT) 4 | // 5 | // Copyright (c) 2015-present, Dom Chen. 6 | // All rights reserved. 7 | // 8 | // Permission is hereby granted, free of charge, to any person obtaining a copy of 9 | // this software and associated documentation files (the "Software"), to deal in the 10 | // Software without restriction, including without limitation the rights to use, copy, 11 | // modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, 12 | // and to permit persons to whom the Software is furnished to do so, subject to the 13 | // following conditions: 14 | // 15 | // The above copyright notice and this permission notice shall be included in all 16 | // copies or substantial portions of the Software. 17 | // 18 | // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 19 | // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 21 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 22 | // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 23 | // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 24 | // 25 | ////////////////////////////////////////////////////////////////////////////////////// 26 | 27 | import * as path from "path"; 28 | import * as ts from "typescript-plus"; 29 | import * as utils from "./Utils"; 30 | 31 | export interface ModuleConfig { 32 | name?:string; 33 | declaration?:boolean; 34 | outFile?:string; 35 | files?:string[]; 36 | include?:string[]; 37 | exclude?:string[]; 38 | dependencies?:string[]; 39 | /* @internal */ 40 | declarationFileName?:string; 41 | /* @internal */ 42 | dependentModules?:ModuleConfig[]; 43 | /* @internal */ 44 | fileNames?:string[]; 45 | } 46 | 47 | let compilerOptionKeys = [ 48 | "allowJs", 49 | "allowSyntheticDefaultImports", 50 | "allowUnreachableCode", 51 | "allowUnusedLabels", 52 | "baseUrl", 53 | "charset", 54 | "declaration", 55 | "declarationDir", 56 | "disableSizeLimit", 57 | "emitBOM", 58 | "emitDecoratorMetadata", 59 | "experimentalDecorators", 60 | "forceConsistentCasingInFileNames", 61 | "inlineSourceMap", 62 | "inlineSources", 63 | "isolatedModules", 64 | "lib", 65 | "locale", 66 | "mapRoot", 67 | "maxNodeModuleJsDepth", 68 | "noEmit", 69 | "noEmitHelpers", 70 | "noEmitOnError", 71 | "noErrorTruncation", 72 | "noFallthroughCasesInSwitch", 73 | "noImplicitAny", 74 | "noImplicitReturns", 75 | "noImplicitThis", 76 | "noUnusedLocals", 77 | "noUnusedParameters", 78 | "noImplicitUseStrict", 79 | "noLib", 80 | "noResolve", 81 | "outDir", 82 | "outFile", 83 | "preserveConstEnums", 84 | "project", 85 | "reactNamespace", 86 | "removeComments", 87 | "rootDir", 88 | "skipLibCheck", 89 | "skipDefaultLibCheck", 90 | "sourceMap", 91 | "sourceRoot", 92 | "strictNullChecks", 93 | "suppressExcessPropertyErrors", 94 | "suppressImplicitAnyIndexErrors", 95 | "traceResolution", 96 | "types", 97 | "typeRoots", 98 | "accessorOptimization", 99 | "defines", 100 | "emitReflection", 101 | "noEmitJs", 102 | "reorderFiles" 103 | ]; 104 | 105 | /* @internal */ 106 | export function getCompilerOptions(moduleConfig:ModuleConfig, existOptions:ts.CompilerOptions):ts.CompilerOptions { 107 | let json = JSON.stringify(existOptions); 108 | let options = JSON.parse(json); 109 | for (let option of compilerOptionKeys) { 110 | if (moduleConfig[option] !== undefined) { 111 | options[option] = moduleConfig[option]; 112 | } 113 | } 114 | if (moduleConfig.name) { 115 | options.module = ts.ModuleKind.None; 116 | } 117 | return options; 118 | } 119 | 120 | export interface OptionsResult { 121 | compilerOptions?:ts.CompilerOptions; 122 | modules?:ModuleConfig[]; 123 | errors?:string[]; 124 | } 125 | 126 | export function findConfigFile(searchPath:string):string { 127 | while (true) { 128 | let fileName = utils.joinPath(searchPath, "tspack.json"); 129 | if (ts.sys.fileExists(fileName)) { 130 | return fileName; 131 | } 132 | fileName = utils.joinPath(searchPath, "tsconfig.json"); 133 | if (ts.sys.fileExists(fileName)) { 134 | return fileName; 135 | } 136 | let parentPath = path.dirname(searchPath); 137 | if (parentPath === searchPath) { 138 | break; 139 | } 140 | searchPath = parentPath; 141 | } 142 | return ""; 143 | } 144 | 145 | export function parseOptionsFromFile(configFileName:string):OptionsResult { 146 | let jsonResult = ts.parseConfigFileTextToJson(configFileName, ts.sys.readFile(configFileName)); 147 | const configObject = jsonResult.config; 148 | if (!configObject) { 149 | let result:OptionsResult = {}; 150 | result.errors = [utils.formatDiagnostics([jsonResult.error])]; 151 | return result; 152 | } 153 | let baseDir = path.dirname(configFileName); 154 | return parseOptionsFromJson(configObject, baseDir, configFileName); 155 | } 156 | 157 | export function parseOptionsFromJson(jsonOptions:any, basePath:string, configFileName?:string):OptionsResult { 158 | let result:OptionsResult = {}; 159 | result.errors = []; 160 | let compilerResult = ts.convertCompilerOptionsFromJson(jsonOptions["compilerOptions"], basePath, configFileName); 161 | if (compilerResult.errors.length > 0) { 162 | result.errors.push(utils.formatDiagnostics(compilerResult.errors)); 163 | return result; 164 | } 165 | let compilerOptions = compilerResult.options; 166 | result.compilerOptions = compilerOptions; 167 | let outDir = basePath; 168 | if (compilerOptions.outDir) { 169 | outDir = compilerOptions.outDir; 170 | } 171 | let modules:ModuleConfig[] = jsonOptions["modules"]; 172 | if (modules) { 173 | formatModules(modules, outDir, basePath, result.errors); 174 | sortOnDependency(modules, result.errors); 175 | modules.forEach(moduleConfig=> { 176 | moduleConfig.fileNames = getFileNames(moduleConfig, basePath, result.errors); 177 | }); 178 | } 179 | else { 180 | let module:ModuleConfig = {}; 181 | let optionResult = ts.parseJsonConfigFileContent(jsonOptions, ts.sys, basePath); 182 | if (optionResult.errors.length > 0) { 183 | result.errors.push(utils.formatDiagnostics(optionResult.errors)); 184 | module.fileNames = []; 185 | } 186 | else { 187 | module.fileNames = optionResult.fileNames; 188 | } 189 | if (compilerOptions.outFile) { 190 | module.name = path.basename(compilerOptions.outFile); 191 | module.outFile = compilerOptions.outFile; 192 | } 193 | modules = [module]; 194 | } 195 | result.modules = modules; 196 | return result; 197 | } 198 | 199 | 200 | function formatModules(moduleConfigs:ModuleConfig[], outDir:string, basePath:string, errors:string[]):void { 201 | let tsdMap:{[key:string]:ModuleConfig} = {}; 202 | moduleConfigs.forEach(moduleConfig=> { 203 | tsdMap[moduleConfig.name] = moduleConfig; 204 | }); 205 | moduleConfigs.forEach(moduleConfig=> { 206 | let outFile = moduleConfig.outFile = getModuleFileName(moduleConfig, outDir, basePath); 207 | if (outFile.substr(outFile.length - 3).toLowerCase() == ".js") { 208 | outFile = outFile.substr(0, outFile.length - 3); 209 | } 210 | moduleConfig.declarationFileName = outFile + ".d.ts"; 211 | if (isArray(moduleConfig.dependencies)) { 212 | let dependencies = moduleConfig.dependencies; 213 | moduleConfig.dependentModules = []; 214 | for (let i = 0; i < dependencies.length; i++) { 215 | let config = tsdMap[dependencies[i]]; 216 | if (!config) { 217 | errors.push("error : could not find the name of module dependency : " + dependencies[i]); 218 | continue; 219 | } 220 | moduleConfig.dependentModules.push(config); 221 | config.declaration = true; 222 | } 223 | } 224 | }); 225 | } 226 | 227 | function getModuleFileName(moduleConfig:ModuleConfig, outDir:string, basePath:string):string { 228 | if (moduleConfig.outFile) { 229 | return utils.joinPath(basePath, moduleConfig.outFile); 230 | } 231 | return utils.joinPath(outDir || basePath, moduleConfig.name + ".js"); 232 | } 233 | 234 | function isArray(value:any):value is any[] { 235 | return Array.isArray ? Array.isArray(value) : value instanceof Array; 236 | } 237 | 238 | 239 | function getFileNames(moduleConfig:ModuleConfig, baseDir:string, errors:string[]):string[] { 240 | let optionResult = ts.parseJsonConfigFileContent(moduleConfig, ts.sys, baseDir); 241 | if (optionResult.errors.length > 0) { 242 | errors.push(utils.formatDiagnostics(optionResult.errors)); 243 | return []; 244 | } 245 | let fileNames = optionResult.fileNames; 246 | if (moduleConfig.dependentModules) { 247 | let declarations:string[] = []; 248 | moduleConfig.dependentModules.forEach(config=> { 249 | declarations.push(config.declarationFileName); 250 | }); 251 | fileNames = declarations.concat(fileNames); 252 | } 253 | return fileNames; 254 | } 255 | 256 | 257 | function sortOnDependency(modules:ModuleConfig[], errors:string[]):void { 258 | let dependencyMap:{[key:string]:string[]} = {}; 259 | for (let module of modules) { 260 | dependencyMap[module.name] = module.dependencies; 261 | } 262 | let moduleWeightMap:{[key:string]:number} = {}; 263 | for (let module of modules) { 264 | let moduleName = module.name; 265 | let references = updateModuleWeight(moduleName, 0, moduleWeightMap, dependencyMap, [moduleName]); 266 | if (references) { 267 | let errorText = "error : circular references in module dependencies configuration :" + ts.sys.newLine; 268 | errorText += " at " + references.join(ts.sys.newLine + " at ") + ts.sys.newLine + " at ..."; 269 | errors.push(errorText); 270 | return; 271 | } 272 | } 273 | modules.sort(function (a:ModuleConfig, b:ModuleConfig):number { 274 | return moduleWeightMap[b.name] - moduleWeightMap[a.name]; 275 | }); 276 | } 277 | 278 | function updateModuleWeight(moduleName:string, weight:number, moduleWeightMap:any, dependencyMap:any, references:string[]):string[] { 279 | if (moduleWeightMap[moduleName] === undefined) { 280 | moduleWeightMap[moduleName] = weight; 281 | } 282 | else { 283 | if (moduleWeightMap[moduleName] < weight) { 284 | moduleWeightMap[moduleName] = weight; 285 | } 286 | else { 287 | return null; 288 | } 289 | } 290 | let list = dependencyMap[moduleName]; 291 | if (!list) { 292 | return null; 293 | } 294 | for (let parentPath of list) { 295 | if (references.indexOf(parentPath) != -1) { 296 | references.push(parentPath); 297 | return references; 298 | } 299 | let result = updateModuleWeight(parentPath, weight + 1, moduleWeightMap, dependencyMap, references.concat(parentPath)); 300 | if (result) { 301 | return result; 302 | } 303 | } 304 | return null; 305 | } -------------------------------------------------------------------------------- /src/packer/Program.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var ts = require("typescript-plus"); 3 | var config = require("./Config"); 4 | var compiler = require("./Compiler"); 5 | var service = require("./Service"); 6 | var commandLine = require("./CommandLine"); 7 | var utils = require("./Utils"); 8 | exports.version = "1.0.5"; 9 | function run(args) { 10 | var commandOptions = commandLine.parse(args); 11 | if (commandOptions.errors.length > 0) { 12 | ts.sys.write(commandOptions.errors.join(ts.sys.newLine) + ts.sys.newLine); 13 | ts.sys.exit(1); 14 | return; 15 | } 16 | if (commandOptions.version) { 17 | printVersion(); 18 | ts.sys.exit(0); 19 | } 20 | if (commandOptions.help) { 21 | printVersion(); 22 | printHelp(); 23 | ts.sys.exit(0); 24 | } 25 | var configFileName = ""; 26 | if (commandOptions.project) { 27 | if (!commandOptions.project || ts.sys.directoryExists(commandOptions.project)) { 28 | configFileName = utils.joinPath(commandOptions.project, "tspack.json"); 29 | if (!ts.sys.fileExists(configFileName)) { 30 | configFileName = utils.joinPath(commandOptions.project, "tsconfig.json"); 31 | } 32 | } 33 | else { 34 | configFileName = commandOptions.project; 35 | } 36 | if (ts.sys.fileExists(configFileName)) { 37 | ts.sys.write("Cannot find a tsconfig.json file at the specified directory: " + commandOptions.project + ts.sys.newLine); 38 | ts.sys.exit(1); 39 | } 40 | } 41 | else { 42 | var searchPath = ts.sys.getCurrentDirectory(); 43 | configFileName = config.findConfigFile(searchPath); 44 | if (!configFileName) { 45 | printVersion(); 46 | printHelp(); 47 | ts.sys.exit(0); 48 | } 49 | } 50 | var result = config.parseOptionsFromFile(configFileName); 51 | if (result.errors.length > 0) { 52 | ts.sys.write(result.errors.join(ts.sys.newLine) + ts.sys.newLine); 53 | ts.sys.exit(1); 54 | } 55 | if (commandOptions.watch) { 56 | result.modules.forEach(function (moduleConfig) { 57 | service.watchModule(moduleConfig, result.compilerOptions); 58 | }); 59 | } 60 | else { 61 | var errors_1 = []; 62 | result.modules.forEach(function (moduleConfig) { 63 | var sortedFileNames = compiler.emitModule(moduleConfig, result.compilerOptions, errors_1); 64 | if (commandOptions.listFiles) { 65 | var output = "sorted files"; 66 | if (moduleConfig.name) { 67 | output += " of '" + moduleConfig.name + "' :"; 68 | } 69 | else { 70 | output += " :"; 71 | } 72 | ts.sys.write(output + ts.sys.newLine); 73 | ts.sys.write(" " + sortedFileNames.join(ts.sys.newLine + " ") + ts.sys.newLine); 74 | } 75 | }); 76 | if (errors_1.length > 0) { 77 | ts.sys.write(errors_1.join(ts.sys.newLine) + ts.sys.newLine); 78 | ts.sys.exit(1); 79 | } 80 | } 81 | } 82 | function printVersion() { 83 | ts.sys.write("Version " + exports.version + ts.sys.newLine); 84 | } 85 | function printHelp() { 86 | var newLine = ts.sys.newLine; 87 | var output = ""; 88 | output += "Syntax: tspack [options]" + newLine + newLine; 89 | output += "Examples: tspack --version" + newLine; 90 | output += "Examples: tspack --project /usr/local/test/" + newLine + newLine; 91 | output += "Options:" + newLine; 92 | commandLine.optionDeclarations.forEach(function (option) { 93 | var name = ""; 94 | if (option.shortName) { 95 | name += "-" + option.shortName + ", "; 96 | } 97 | name += "--" + option.name; 98 | name += makePadding(25 - name.length); 99 | output += name + option.description + newLine; 100 | }); 101 | ts.sys.write(output); 102 | } 103 | function makePadding(paddingLength) { 104 | return Array(paddingLength + 1).join(" "); 105 | } 106 | run(ts.sys.args); 107 | -------------------------------------------------------------------------------- /src/packer/Program.ts: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////////////////// 2 | // 3 | // The MIT License (MIT) 4 | // 5 | // Copyright (c) 2015-present, Dom Chen. 6 | // All rights reserved. 7 | // 8 | // Permission is hereby granted, free of charge, to any person obtaining a copy of 9 | // this software and associated documentation files (the "Software"), to deal in the 10 | // Software without restriction, including without limitation the rights to use, copy, 11 | // modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, 12 | // and to permit persons to whom the Software is furnished to do so, subject to the 13 | // following conditions: 14 | // 15 | // The above copyright notice and this permission notice shall be included in all 16 | // copies or substantial portions of the Software. 17 | // 18 | // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 19 | // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 21 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 22 | // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 23 | // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 24 | // 25 | ////////////////////////////////////////////////////////////////////////////////////// 26 | 27 | import * as ts from "typescript-plus"; 28 | import * as config from "./Config"; 29 | import * as compiler from "./Compiler"; 30 | import * as service from "./Service"; 31 | import * as commandLine from "./CommandLine"; 32 | import * as utils from "./Utils"; 33 | 34 | export const version = "1.0.5"; 35 | 36 | function run(args:string[]):void { 37 | let commandOptions = commandLine.parse(args); 38 | if (commandOptions.errors.length > 0) { 39 | ts.sys.write(commandOptions.errors.join(ts.sys.newLine) + ts.sys.newLine); 40 | ts.sys.exit(1); 41 | return; 42 | } 43 | 44 | if (commandOptions.version) { 45 | printVersion(); 46 | ts.sys.exit(0); 47 | } 48 | 49 | if (commandOptions.help) { 50 | printVersion(); 51 | printHelp(); 52 | ts.sys.exit(0); 53 | } 54 | let configFileName:string = ""; 55 | if (commandOptions.project) { 56 | if (!commandOptions.project || ts.sys.directoryExists(commandOptions.project)) { 57 | configFileName = utils.joinPath(commandOptions.project, "tspack.json"); 58 | if (!ts.sys.fileExists(configFileName)) { 59 | configFileName = utils.joinPath(commandOptions.project, "tsconfig.json"); 60 | } 61 | } 62 | else { 63 | configFileName = commandOptions.project; 64 | } 65 | if (ts.sys.fileExists(configFileName)) { 66 | ts.sys.write("Cannot find a tsconfig.json file at the specified directory: " + commandOptions.project + ts.sys.newLine); 67 | ts.sys.exit(1); 68 | } 69 | } 70 | else { 71 | let searchPath = ts.sys.getCurrentDirectory(); 72 | configFileName = config.findConfigFile(searchPath); 73 | if (!configFileName) { 74 | printVersion(); 75 | printHelp(); 76 | ts.sys.exit(0); 77 | } 78 | } 79 | 80 | let result = config.parseOptionsFromFile(configFileName); 81 | if (result.errors.length > 0) { 82 | ts.sys.write(result.errors.join(ts.sys.newLine) + ts.sys.newLine); 83 | ts.sys.exit(1); 84 | } 85 | 86 | if (commandOptions.watch) { 87 | result.modules.forEach(moduleConfig=> { 88 | service.watchModule(moduleConfig, result.compilerOptions); 89 | }); 90 | } 91 | else { 92 | let errors:string[] = []; 93 | result.modules.forEach(moduleConfig=> { 94 | let sortedFileNames = compiler.emitModule(moduleConfig, result.compilerOptions, errors); 95 | if (commandOptions.listFiles) { 96 | let output = "sorted files"; 97 | if (moduleConfig.name) { 98 | output += " of '" + moduleConfig.name + "' :"; 99 | } 100 | else { 101 | output += " :"; 102 | } 103 | ts.sys.write(output + ts.sys.newLine); 104 | ts.sys.write(" " + sortedFileNames.join(ts.sys.newLine + " ") + ts.sys.newLine); 105 | } 106 | }); 107 | if (errors.length > 0) { 108 | ts.sys.write(errors.join(ts.sys.newLine) + ts.sys.newLine); 109 | ts.sys.exit(1); 110 | } 111 | } 112 | } 113 | 114 | function printVersion():void { 115 | ts.sys.write("Version " + version + ts.sys.newLine); 116 | } 117 | 118 | function printHelp():void { 119 | const newLine = ts.sys.newLine; 120 | let output = ""; 121 | output += "Syntax: tspack [options]" + newLine + newLine; 122 | output += "Examples: tspack --version" + newLine; 123 | output += "Examples: tspack --project /usr/local/test/" + newLine + newLine; 124 | output += "Options:" + newLine; 125 | commandLine.optionDeclarations.forEach(option=> { 126 | let name = ""; 127 | if (option.shortName) { 128 | name += "-" + option.shortName + ", "; 129 | } 130 | name += "--" + option.name; 131 | name += makePadding(25 - name.length); 132 | output += name + option.description + newLine; 133 | }); 134 | ts.sys.write(output); 135 | } 136 | 137 | function makePadding(paddingLength:number):string { 138 | return Array(paddingLength + 1).join(" "); 139 | } 140 | 141 | run(ts.sys.args); -------------------------------------------------------------------------------- /src/packer/Service.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var fs = require("fs"); 3 | var ts = require("typescript-plus"); 4 | var chokidar = require("chokidar"); 5 | function watchModule(moduleConfig, compilerOptions) { 6 | var rootFileNames = moduleConfig.fileNames; 7 | var files = {}; 8 | rootFileNames.forEach(function (fileName) { 9 | files[fileName] = { version: 0 }; 10 | }); 11 | var servicesHost = { 12 | getScriptFileNames: function () { return rootFileNames; }, 13 | getScriptVersion: function (fileName) { return files[fileName] && files[fileName].version.toString(); }, 14 | getScriptSnapshot: function (fileName) { 15 | if (!fs.existsSync(fileName)) { 16 | return undefined; 17 | } 18 | return ts.ScriptSnapshot.fromString(fs.readFileSync(fileName).toString()); 19 | }, 20 | getCurrentDirectory: function () { return process.cwd(); }, 21 | getCompilationSettings: function () { return compilerOptions; }, 22 | getDefaultLibFileName: function (options) { return ts.getDefaultLibFilePath(options); }, 23 | }; 24 | var services = ts.createLanguageService(servicesHost, ts.createDocumentRegistry()); 25 | rootFileNames.forEach(function (fileName) { 26 | emitFile(fileName); 27 | var watcher = chokidar.watch(fileName, {}); 28 | watcher.on("change", function () { 29 | files[fileName].version++; 30 | emitFile(fileName); 31 | }); 32 | }); 33 | function emitFile(fileName) { 34 | var output = services.getEmitOutput(fileName); 35 | if (!output.emitSkipped) { 36 | console.log("Emitting " + fileName); 37 | } 38 | else { 39 | console.log("Emitting " + fileName + " failed"); 40 | logErrors(fileName); 41 | } 42 | output.outputFiles.forEach(function (o) { 43 | fs.writeFileSync(o.name, o.text, "utf8"); 44 | }); 45 | } 46 | function logErrors(fileName) { 47 | var allDiagnostics = services.getCompilerOptionsDiagnostics() 48 | .concat(services.getSyntacticDiagnostics(fileName)) 49 | .concat(services.getSemanticDiagnostics(fileName)); 50 | allDiagnostics.forEach(function (diagnostic) { 51 | var message = ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"); 52 | if (diagnostic.file) { 53 | var _a = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start), line = _a.line, character = _a.character; 54 | console.log(" Error " + diagnostic.file.fileName + " (" + (line + 1) + "," + (character + 1) + "): " + message); 55 | } 56 | else { 57 | console.log(" Error: " + message); 58 | } 59 | }); 60 | } 61 | } 62 | exports.watchModule = watchModule; 63 | -------------------------------------------------------------------------------- /src/packer/Service.ts: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////////////////// 2 | // 3 | // The MIT License (MIT) 4 | // 5 | // Copyright (c) 2015-present, Dom Chen. 6 | // All rights reserved. 7 | // 8 | // Permission is hereby granted, free of charge, to any person obtaining a copy of 9 | // this software and associated documentation files (the "Software"), to deal in the 10 | // Software without restriction, including without limitation the rights to use, copy, 11 | // modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, 12 | // and to permit persons to whom the Software is furnished to do so, subject to the 13 | // following conditions: 14 | // 15 | // The above copyright notice and this permission notice shall be included in all 16 | // copies or substantial portions of the Software. 17 | // 18 | // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 19 | // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 21 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 22 | // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 23 | // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 24 | // 25 | ////////////////////////////////////////////////////////////////////////////////////// 26 | 27 | import * as fs from "fs"; 28 | import * as ts from "typescript-plus"; 29 | import * as chokidar from "chokidar"; 30 | import * as config from "./Config"; 31 | 32 | export function watchModule(moduleConfig:config.ModuleConfig, compilerOptions:ts.CompilerOptions):void { 33 | let rootFileNames = moduleConfig.fileNames; 34 | const files:ts.Map<{ version:number }> = {}; 35 | 36 | // initialize the list of files 37 | rootFileNames.forEach(fileName => { 38 | files[fileName] = {version: 0}; 39 | }); 40 | 41 | // Create the language service host to allow the LS to communicate with the host 42 | const servicesHost:ts.LanguageServiceHost = { 43 | getScriptFileNames: () => rootFileNames, 44 | getScriptVersion: (fileName) => files[fileName] && files[fileName].version.toString(), 45 | getScriptSnapshot: (fileName) => { 46 | if (!fs.existsSync(fileName)) { 47 | return undefined; 48 | } 49 | 50 | return ts.ScriptSnapshot.fromString(fs.readFileSync(fileName).toString()); 51 | }, 52 | getCurrentDirectory: () => process.cwd(), 53 | getCompilationSettings: () => compilerOptions, 54 | getDefaultLibFileName: (options) => ts.getDefaultLibFilePath(options), 55 | }; 56 | 57 | // Create the language service files 58 | const services = ts.createLanguageService(servicesHost, ts.createDocumentRegistry()) 59 | // Now let's watch the files 60 | rootFileNames.forEach(fileName => { 61 | // First time around, emit all files 62 | emitFile(fileName); 63 | 64 | // Add a watch on the file to handle next change 65 | var watcher = chokidar.watch(fileName, {}); 66 | watcher.on("change", () => { 67 | // Update the version to signal a change in the file 68 | files[fileName].version++; 69 | 70 | // write the changes to disk 71 | emitFile(fileName); 72 | }); 73 | }); 74 | 75 | function emitFile(fileName:string) { 76 | let output = services.getEmitOutput(fileName); 77 | 78 | if (!output.emitSkipped) { 79 | console.log(`Emitting ${fileName}`); 80 | } 81 | else { 82 | console.log(`Emitting ${fileName} failed`); 83 | logErrors(fileName); 84 | } 85 | 86 | output.outputFiles.forEach(o => { 87 | fs.writeFileSync(o.name, o.text, "utf8"); 88 | }); 89 | } 90 | 91 | function logErrors(fileName:string) { 92 | let allDiagnostics = services.getCompilerOptionsDiagnostics() 93 | .concat(services.getSyntacticDiagnostics(fileName)) 94 | .concat(services.getSemanticDiagnostics(fileName)); 95 | 96 | allDiagnostics.forEach(diagnostic => { 97 | let message = ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"); 98 | if (diagnostic.file) { 99 | let {line, character} = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start); 100 | console.log(` Error ${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`); 101 | } 102 | else { 103 | console.log(` Error: ${message}`); 104 | } 105 | }); 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/packer/Utils.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | var ts = require("typescript-plus"); 3 | var defaultFormatDiagnosticsHost = { 4 | getCurrentDirectory: function () { return ts.sys.getCurrentDirectory(); }, 5 | getNewLine: function () { return ts.sys.newLine; }, 6 | getCanonicalFileName: createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames) 7 | }; 8 | function createGetCanonicalFileName(useCaseSensitivefileNames) { 9 | return useCaseSensitivefileNames 10 | ? (function (fileName) { return fileName; }) 11 | : (function (fileName) { return fileName.toLowerCase(); }); 12 | } 13 | function formatDiagnostics(diagnostics) { 14 | return ts.formatDiagnostics(diagnostics, defaultFormatDiagnosticsHost); 15 | } 16 | exports.formatDiagnostics = formatDiagnostics; 17 | function getRootLength(path) { 18 | if (path.charAt(0) == "/") { 19 | if (path.charAt(1) != "/") 20 | return 1; 21 | var p1 = path.indexOf("/", 2); 22 | if (p1 < 0) 23 | return 2; 24 | var p2 = path.indexOf("/", p1 + 1); 25 | if (p2 < 0) 26 | return p1 + 1; 27 | return p2 + 1; 28 | } 29 | if (path.charAt(1) == ":") { 30 | if (path.charAt(2) == "/") 31 | return 3; 32 | return 2; 33 | } 34 | if (path.lastIndexOf("file:///", 0) === 0) { 35 | return "file:///".length; 36 | } 37 | var idx = path.indexOf("://"); 38 | if (idx !== -1) { 39 | return idx + "://".length; 40 | } 41 | return 0; 42 | } 43 | var directorySeparator = "/"; 44 | function joinPath(path1, path2) { 45 | if (!(path1 && path1.length)) 46 | return path2; 47 | if (!(path2 && path2.length)) 48 | return path1; 49 | path1 = path1.split("\\").join(directorySeparator); 50 | path2 = path2.split("\\").join(directorySeparator); 51 | if (getRootLength(path2) !== 0) 52 | return path2; 53 | if (path1.charAt(path1.length - 1) === directorySeparator) 54 | return path1 + path2; 55 | return path1 + directorySeparator + path2; 56 | } 57 | exports.joinPath = joinPath; 58 | -------------------------------------------------------------------------------- /src/packer/Utils.ts: -------------------------------------------------------------------------------- 1 | ////////////////////////////////////////////////////////////////////////////////////// 2 | // 3 | // The MIT License (MIT) 4 | // 5 | // Copyright (c) 2015-present, Dom Chen. 6 | // All rights reserved. 7 | // 8 | // Permission is hereby granted, free of charge, to any person obtaining a copy of 9 | // this software and associated documentation files (the "Software"), to deal in the 10 | // Software without restriction, including without limitation the rights to use, copy, 11 | // modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, 12 | // and to permit persons to whom the Software is furnished to do so, subject to the 13 | // following conditions: 14 | // 15 | // The above copyright notice and this permission notice shall be included in all 16 | // copies or substantial portions of the Software. 17 | // 18 | // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 19 | // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 21 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 22 | // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 23 | // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 24 | // 25 | ////////////////////////////////////////////////////////////////////////////////////// 26 | 27 | import * as fs from "fs"; 28 | import * as ts from "typescript-plus"; 29 | 30 | const defaultFormatDiagnosticsHost:ts.FormatDiagnosticsHost = { 31 | getCurrentDirectory: () => ts.sys.getCurrentDirectory(), 32 | getNewLine: () => ts.sys.newLine, 33 | getCanonicalFileName: createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames) 34 | }; 35 | 36 | function createGetCanonicalFileName(useCaseSensitivefileNames:boolean):(fileName:string) => string { 37 | return useCaseSensitivefileNames 38 | ? ((fileName) => fileName) 39 | : ((fileName) => fileName.toLowerCase()); 40 | } 41 | 42 | export function formatDiagnostics(diagnostics:ts.Diagnostic[]):string { 43 | return ts.formatDiagnostics(diagnostics, defaultFormatDiagnosticsHost); 44 | } 45 | 46 | function getRootLength(path:string):number { 47 | if (path.charAt(0) == "/") { 48 | if (path.charAt(1) != "/") return 1; 49 | const p1 = path.indexOf("/", 2); 50 | if (p1 < 0) return 2; 51 | const p2 = path.indexOf("/", p1 + 1); 52 | if (p2 < 0) return p1 + 1; 53 | return p2 + 1; 54 | } 55 | if (path.charAt(1) == ":") { 56 | if (path.charAt(2) == "/") return 3; 57 | return 2; 58 | } 59 | if (path.lastIndexOf("file:///", 0) === 0) { 60 | return "file:///".length; 61 | } 62 | const idx = path.indexOf("://"); 63 | if (idx !== -1) { 64 | return idx + "://".length; 65 | } 66 | return 0; 67 | } 68 | 69 | let directorySeparator = "/"; 70 | 71 | export function joinPath(path1:string, path2:string):string { 72 | if (!(path1 && path1.length)) return path2; 73 | if (!(path2 && path2.length)) return path1; 74 | path1 = path1.split("\\").join(directorySeparator); 75 | path2 = path2.split("\\").join(directorySeparator); 76 | if (getRootLength(path2) !== 0) return path2; 77 | if (path1.charAt(path1.length - 1) === directorySeparator) return path1 + path2; 78 | return path1 + directorySeparator + path2; 79 | } 80 | 81 | -------------------------------------------------------------------------------- /src/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "target": "es5", 5 | "noImplicitAny": false, 6 | "removeComments": true, 7 | "preserveConstEnums": true, 8 | "sourceMap": false 9 | }, 10 | "exclude": [ 11 | "node_modules" 12 | ] 13 | } 14 | --------------------------------------------------------------------------------