importTypescript.js 7.9 KB

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