importTypescript.js 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. /*---------------------------------------------------------------------------------------------
  2. * Copyright (c) Microsoft Corporation. All rights reserved.
  3. * Licensed under the MIT License. See License.txt in the project root for license information.
  4. *--------------------------------------------------------------------------------------------*/
  5. const path = require('path');
  6. const fs = require('fs');
  7. const child_process = require('child_process');
  8. const TYPESCRIPT_LIB_SOURCE = path.join(__dirname, '../node_modules/typescript/lib');
  9. const TYPESCRIPT_LIB_DESTINATION = path.join(__dirname, '../src/lib');
  10. (function () {
  11. try {
  12. fs.statSync(TYPESCRIPT_LIB_DESTINATION);
  13. } catch (err) {
  14. fs.mkdirSync(TYPESCRIPT_LIB_DESTINATION);
  15. }
  16. importLibs();
  17. const npmLsOutput = JSON.parse(child_process.execSync("npm ls typescript --depth=0 --json=true").toString());
  18. const typeScriptDependencyVersion = npmLsOutput.dependencies.typescript.version;
  19. fs.writeFileSync(
  20. path.join(TYPESCRIPT_LIB_DESTINATION, 'typescriptServicesMetadata.ts'),
  21. `export const typescriptVersion = "${typeScriptDependencyVersion}";\n`
  22. );
  23. var tsServices = fs.readFileSync(path.join(TYPESCRIPT_LIB_SOURCE, 'typescriptServices.js')).toString();
  24. // Ensure we never run into the node system...
  25. // (this also removes require calls that trick webpack into shimming those modules...)
  26. tsServices = (
  27. tsServices.replace(/\n ts\.sys =([^]*)\n \}\)\(\);/m, `\n // MONACOCHANGE\n ts.sys = undefined;\n // END MONACOCHANGE`)
  28. );
  29. // Eliminate more require() calls...
  30. tsServices = tsServices.replace(/^( +)etwModule = require\(.*$/m, '$1// MONACOCHANGE\n$1etwModule = undefined;\n$1// END MONACOCHANGE');
  31. tsServices = tsServices.replace(/^( +)var result = ts\.sys\.require\(.*$/m, '$1// MONACOCHANGE\n$1var result = undefined;\n$1// END MONACOCHANGE');
  32. // Flag any new require calls (outside comments) so they can be corrected preemptively.
  33. // To avoid missing cases (or using an even more complex regex), temporarily remove comments
  34. // about require() and then check for lines actually calling require().
  35. // \/[*/] matches the start of a comment (single or multi-line).
  36. // ^\s+\*[^/] matches (presumably) a later line of a multi-line comment.
  37. const tsServicesNoCommentedRequire = tsServices.replace(/(\/[*/]|^\s+\*[^/]).*\brequire\(.*/gm, '');
  38. const linesWithRequire = tsServicesNoCommentedRequire.match(/^.*?\brequire\(.*$/gm);
  39. if (linesWithRequire && linesWithRequire.length) {
  40. console.error('Found new require() calls on the following lines. These should be removed to avoid breaking webpack builds.\n');
  41. console.error(linesWithRequire.join('\n'));
  42. process.exit(1);
  43. }
  44. // Make sure process.args don't get called in the browser, this
  45. // should only happen in TS 2.6.2
  46. const beforeProcess = `ts.perfLogger.logInfoEvent("Starting TypeScript v" + ts.versionMajorMinor + " with command line: " + JSON.stringify(process.argv));`
  47. const afterProcess = `// MONACOCHANGE\n ts.perfLogger.logInfoEvent("Starting TypeScript v" + ts.versionMajorMinor + " with command line: " + JSON.stringify([]));\n// END MONACOCHANGE`
  48. tsServices = tsServices.replace(beforeProcess, afterProcess);
  49. var tsServices_amd = tsServices +
  50. `
  51. // MONACOCHANGE
  52. // Defining the entire module name because r.js has an issue and cannot bundle this file
  53. // correctly with an anonymous define call
  54. define("vs/language/typescript/lib/typescriptServices", [], function() { return ts; });
  55. // END MONACOCHANGE
  56. `;
  57. fs.writeFileSync(path.join(TYPESCRIPT_LIB_DESTINATION, 'typescriptServices-amd.js'), tsServices_amd);
  58. var tsServices_esm = tsServices +
  59. `
  60. // MONACOCHANGE
  61. export var createClassifier = ts.createClassifier;
  62. export var createLanguageService = ts.createLanguageService;
  63. export var displayPartsToString = ts.displayPartsToString;
  64. export var EndOfLineState = ts.EndOfLineState;
  65. export var flattenDiagnosticMessageText = ts.flattenDiagnosticMessageText;
  66. export var IndentStyle = ts.IndentStyle;
  67. export var ScriptKind = ts.ScriptKind;
  68. export var ScriptTarget = ts.ScriptTarget;
  69. export var TokenClass = ts.TokenClass;
  70. // END MONACOCHANGE
  71. `;
  72. fs.writeFileSync(path.join(TYPESCRIPT_LIB_DESTINATION, 'typescriptServices.js'), tsServices_esm);
  73. var dtsServices = fs.readFileSync(path.join(TYPESCRIPT_LIB_SOURCE, 'typescriptServices.d.ts')).toString();
  74. dtsServices +=
  75. `
  76. // MONACOCHANGE
  77. export = ts;
  78. // END MONACOCHANGE
  79. `;
  80. fs.writeFileSync(path.join(TYPESCRIPT_LIB_DESTINATION, 'typescriptServices.d.ts'), dtsServices);
  81. })();
  82. function importLibs() {
  83. function getFileName(name) {
  84. return (name === '' ? 'lib.d.ts' : `lib.${name}.d.ts`);
  85. }
  86. function getVariableName(name) {
  87. return (name === '' ? 'lib_dts' : `lib_${name.replace(/\./g, '_')}_dts`);
  88. }
  89. function readLibFile(name) {
  90. var srcPath = path.join(TYPESCRIPT_LIB_SOURCE, getFileName(name));
  91. return fs.readFileSync(srcPath).toString();
  92. }
  93. var queue = [];
  94. var in_queue = {};
  95. var enqueue = function (name) {
  96. if (in_queue[name]) {
  97. return;
  98. }
  99. in_queue[name] = true;
  100. queue.push(name);
  101. };
  102. enqueue('');
  103. enqueue('es2015');
  104. var result = [];
  105. while (queue.length > 0) {
  106. var name = queue.shift();
  107. var contents = readLibFile(name);
  108. var lines = contents.split(/\r\n|\r|\n/);
  109. var output = '';
  110. var writeOutput = function (text) {
  111. if (output.length === 0) {
  112. output = text;
  113. } else {
  114. output += ` + ${text}`;
  115. }
  116. };
  117. var outputLines = [];
  118. var flushOutputLines = function () {
  119. writeOutput(`"${escapeText(outputLines.join('\n'))}"`);
  120. outputLines = [];
  121. };
  122. var deps = [];
  123. for (let i = 0; i < lines.length; i++) {
  124. let m = lines[i].match(/\/\/\/\s*<reference\s*lib="([^"]+)"/);
  125. if (m) {
  126. flushOutputLines();
  127. writeOutput(getVariableName(m[1]));
  128. deps.push(getVariableName(m[1]));
  129. enqueue(m[1]);
  130. continue;
  131. }
  132. outputLines.push(lines[i]);
  133. }
  134. flushOutputLines();
  135. result.push({
  136. name: getVariableName(name),
  137. deps: deps,
  138. output: output
  139. });
  140. }
  141. var strResult = `/*---------------------------------------------------------------------------------------------
  142. * Copyright (c) Microsoft Corporation. All rights reserved.
  143. * Licensed under the MIT License. See License.txt in the project root for license information.
  144. *--------------------------------------------------------------------------------------------*/
  145. `;
  146. // Do a topological sort
  147. while (result.length > 0) {
  148. for (let i = result.length - 1; i >= 0; i--) {
  149. if (result[i].deps.length === 0) {
  150. // emit this node
  151. strResult += `\nexport const ${result[i].name}: string = ${result[i].output};\n`;
  152. // mark dep as resolved
  153. for (let j = 0; j < result.length; j++) {
  154. for (let k = 0; k < result[j].deps.length; k++) {
  155. if (result[j].deps[k] === result[i].name) {
  156. result[j].deps.splice(k, 1);
  157. break;
  158. }
  159. }
  160. }
  161. // remove from result
  162. result.splice(i, 1);
  163. break;
  164. }
  165. }
  166. }
  167. var dstPath = path.join(TYPESCRIPT_LIB_DESTINATION, 'lib.ts');
  168. fs.writeFileSync(dstPath, strResult);
  169. }
  170. /**
  171. * Escape text such that it can be used in a javascript string enclosed by double quotes (")
  172. */
  173. function escapeText(text) {
  174. // See http://www.javascriptkit.com/jsref/escapesequence.shtml
  175. var _backspace = '\b'.charCodeAt(0);
  176. var _formFeed = '\f'.charCodeAt(0);
  177. var _newLine = '\n'.charCodeAt(0);
  178. var _nullChar = 0;
  179. var _carriageReturn = '\r'.charCodeAt(0);
  180. var _tab = '\t'.charCodeAt(0);
  181. var _verticalTab = '\v'.charCodeAt(0);
  182. var _backslash = '\\'.charCodeAt(0);
  183. var _doubleQuote = '"'.charCodeAt(0);
  184. var startPos = 0, chrCode, replaceWith = null, resultPieces = [];
  185. for (var i = 0, len = text.length; i < len; i++) {
  186. chrCode = text.charCodeAt(i);
  187. switch (chrCode) {
  188. case _backspace:
  189. replaceWith = '\\b';
  190. break;
  191. case _formFeed:
  192. replaceWith = '\\f';
  193. break;
  194. case _newLine:
  195. replaceWith = '\\n';
  196. break;
  197. case _nullChar:
  198. replaceWith = '\\0';
  199. break;
  200. case _carriageReturn:
  201. replaceWith = '\\r';
  202. break;
  203. case _tab:
  204. replaceWith = '\\t';
  205. break;
  206. case _verticalTab:
  207. replaceWith = '\\v';
  208. break;
  209. case _backslash:
  210. replaceWith = '\\\\';
  211. break;
  212. case _doubleQuote:
  213. replaceWith = '\\"';
  214. break;
  215. }
  216. if (replaceWith !== null) {
  217. resultPieces.push(text.substring(startPos, i));
  218. resultPieces.push(replaceWith);
  219. startPos = i + 1;
  220. replaceWith = null;
  221. }
  222. }
  223. resultPieces.push(text.substring(startPos, len));
  224. return resultPieces.join('');
  225. }