build-monaco-editor.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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. import path = require('path');
  6. import fs = require('fs');
  7. import { REPO_ROOT, readFiles, writeFiles, IFile, readFile } from '../build/utils';
  8. import { removeDir } from '../build/fs';
  9. import ts = require('typescript');
  10. import { generateMetadata } from './releaseMetadata';
  11. removeDir(`out/monaco-editor`);
  12. // dev folder
  13. AMD_releaseOne('dev');
  14. // min folder
  15. AMD_releaseOne('min');
  16. // esm folder
  17. ESM_release();
  18. // monaco.d.ts, editor.api.d.ts
  19. releaseDTS();
  20. // ThirdPartyNotices.txt
  21. releaseThirdPartyNotices();
  22. // esm/metadata.d.ts, esm/metadata.js
  23. generateMetadata();
  24. // package.json
  25. (() => {
  26. const packageJSON = readFiles('package.json', { base: '' })[0];
  27. const json = JSON.parse(packageJSON.contents.toString());
  28. json.private = false;
  29. delete json.scripts['postinstall'];
  30. packageJSON.contents = Buffer.from(JSON.stringify(json, null, ' '));
  31. writeFiles([packageJSON], `out/monaco-editor`);
  32. })();
  33. (() => {
  34. /** @type {IFile[]} */
  35. let otherFiles = [];
  36. otherFiles = otherFiles.concat(readFiles('README.md', { base: '' }));
  37. otherFiles = otherFiles.concat(readFiles('CHANGELOG.md', { base: '' }));
  38. otherFiles = otherFiles.concat(
  39. readFiles('node_modules/monaco-editor-core/min-maps/**/*', {
  40. base: 'node_modules/monaco-editor-core/'
  41. })
  42. );
  43. otherFiles = otherFiles.concat(
  44. readFiles('node_modules/monaco-editor-core/LICENSE', {
  45. base: 'node_modules/monaco-editor-core/'
  46. })
  47. );
  48. writeFiles(otherFiles, `out/monaco-editor`);
  49. })();
  50. /**
  51. * Release to `dev` or `min`.
  52. */
  53. function AMD_releaseOne(type: 'dev' | 'min') {
  54. let coreFiles = readFiles(`node_modules/monaco-editor-core/${type}/**/*`, {
  55. base: `node_modules/monaco-editor-core/${type}`
  56. });
  57. coreFiles = fixNlsFiles(coreFiles);
  58. AMD_addPluginContribs(type, coreFiles);
  59. writeFiles(coreFiles, `out/monaco-editor/${type}`);
  60. const pluginFiles = readFiles(`out/languages/bundled/amd-${type}/**/*`, {
  61. base: `out/languages/bundled/amd-${type}`,
  62. ignore: ['**/monaco.contribution.js']
  63. });
  64. writeFiles(pluginFiles, `out/monaco-editor/${type}`);
  65. }
  66. function fixNlsFiles(files: IFile[]): IFile[] {
  67. return files.map((f) => {
  68. if (!f.path.match(/nls\.messages\.[a-z\-]+\.js/)) {
  69. return f;
  70. }
  71. const dirName = path.dirname(f.path);
  72. const fileName = path.basename(f.path);
  73. const newPath = path.join(dirName, 'vs', fileName);
  74. let contentStr = f.contents.toString('utf-8');
  75. contentStr = `
  76. define([], function () {
  77. ${contentStr}
  78. });
  79. `;
  80. const newContents = Buffer.from(contentStr, 'utf-8');
  81. return {
  82. path: newPath,
  83. contents: newContents
  84. };
  85. });
  86. }
  87. /**
  88. * Edit editor.main.js:
  89. * - rename the AMD module 'vs/editor/editor.main' to 'vs/editor/edcore.main'
  90. * - append monaco.contribution modules from plugins
  91. * - append new AMD module 'vs/editor/editor.main' that stiches things together
  92. */
  93. function AMD_addPluginContribs(type: 'dev' | 'min', files: IFile[]) {
  94. for (const file of files) {
  95. if (!/editor\.main\.js$/.test(file.path)) {
  96. continue;
  97. }
  98. let contents = file.contents.toString();
  99. // Rename the AMD module 'vs/editor/editor.main' to 'vs/editor/edcore.main'
  100. contents = contents.replace(/"vs\/editor\/editor\.main\"/, '"vs/editor/edcore.main"');
  101. // This ensures that old nls-plugin configurations are still respected by the new localization solution.
  102. const contentPrefixSource = readFile('src/nls-fix.js')
  103. .contents.toString('utf-8')
  104. .replace(/\r\n|\n/g, ' ');
  105. // TODO: Instead of adding this source to the header to maintain the source map indices, it should rewrite the sourcemap!
  106. const searchValue = 'https://github.com/microsoft/vscode/blob/main/LICENSE.txt';
  107. contents = contents.replace(searchValue, searchValue + ' */ ' + contentPrefixSource + ' /*');
  108. const pluginFiles = readFiles(`out/languages/bundled/amd-${type}/**/monaco.contribution.js`, {
  109. base: `out/languages/bundled/amd-${type}`
  110. });
  111. const extraContent = pluginFiles.map((file) => {
  112. return file.contents
  113. .toString()
  114. .replace(
  115. /define\((['"][a-z\/\-]+\/fillers\/monaco-editor-core['"]),\[\],/,
  116. "define($1,['vs/editor/editor.api'],"
  117. );
  118. });
  119. const allPluginsModuleIds = pluginFiles.map((file) => {
  120. return file.path.replace(/\.js$/, '');
  121. });
  122. extraContent.push(
  123. `define("vs/editor/editor.main", ["vs/editor/edcore.main","${allPluginsModuleIds.join(
  124. '","'
  125. )}"], function(api) { return api; });`
  126. );
  127. let insertIndex = contents.lastIndexOf('//# sourceMappingURL=');
  128. if (insertIndex === -1) {
  129. insertIndex = contents.length;
  130. }
  131. contents =
  132. contents.substring(0, insertIndex) +
  133. '\n' +
  134. extraContent.join('\n') +
  135. '\n' +
  136. contents.substring(insertIndex);
  137. file.contents = Buffer.from(contents);
  138. }
  139. }
  140. function ESM_release() {
  141. const coreFiles = readFiles(`node_modules/monaco-editor-core/esm/**/*`, {
  142. base: 'node_modules/monaco-editor-core/esm',
  143. // we will create our own editor.api.d.ts which also contains the plugins API
  144. ignore: ['node_modules/monaco-editor-core/esm/vs/editor/editor.api.d.ts']
  145. });
  146. ESM_addImportSuffix(coreFiles);
  147. ESM_addPluginContribs(coreFiles);
  148. writeFiles(coreFiles, `out/monaco-editor/esm`);
  149. ESM_releasePlugins();
  150. }
  151. /**
  152. * Release a plugin to `esm`.
  153. * Adds a dependency to 'vs/editor/editor.api' in contrib files in order for `monaco` to be defined.
  154. * Rewrites imports for 'monaco-editor-core/**'
  155. */
  156. function ESM_releasePlugins() {
  157. const files = readFiles(`out/languages/bundled/esm/**/*`, { base: 'out/languages/bundled/esm/' });
  158. for (const file of files) {
  159. if (!/(\.js$)|(\.ts$)/.test(file.path)) {
  160. continue;
  161. }
  162. let contents = file.contents.toString();
  163. const info = ts.preProcessFile(contents);
  164. for (let i = info.importedFiles.length - 1; i >= 0; i--) {
  165. let importText = info.importedFiles[i].fileName;
  166. const pos = info.importedFiles[i].pos;
  167. const end = info.importedFiles[i].end;
  168. if (!/(^\.\/)|(^\.\.\/)/.test(importText)) {
  169. // non-relative import
  170. if (!/^monaco-editor-core/.test(importText)) {
  171. console.error(`Non-relative import for unknown module: ${importText} in ${file.path}`);
  172. process.exit(1);
  173. }
  174. if (importText === 'monaco-editor-core') {
  175. importText = 'monaco-editor-core/esm/vs/editor/editor.api';
  176. }
  177. const importFilePath = importText.substring('monaco-editor-core/esm/'.length);
  178. let relativePath = path
  179. .relative(path.dirname(file.path), importFilePath)
  180. .replace(/\\/g, '/');
  181. if (!/(^\.\/)|(^\.\.\/)/.test(relativePath)) {
  182. relativePath = './' + relativePath;
  183. }
  184. contents = contents.substring(0, pos + 1) + relativePath + contents.substring(end + 1);
  185. }
  186. }
  187. file.contents = Buffer.from(contents);
  188. }
  189. for (const file of files) {
  190. if (!/monaco\.contribution\.js$/.test(file.path)) {
  191. continue;
  192. }
  193. const apiFilePath = 'vs/editor/editor.api';
  194. let relativePath = path.relative(path.dirname(file.path), apiFilePath).replace(/\\/g, '/');
  195. if (!/(^\.\/)|(^\.\.\/)/.test(relativePath)) {
  196. relativePath = './' + relativePath;
  197. }
  198. let contents = file.contents.toString();
  199. contents = `import '${relativePath}';\n` + contents;
  200. file.contents = Buffer.from(contents);
  201. }
  202. ESM_addImportSuffix(files);
  203. writeFiles(files, `out/monaco-editor/esm`);
  204. }
  205. /**
  206. * Adds `.js` to all import statements.
  207. */
  208. function ESM_addImportSuffix(files: IFile[]) {
  209. for (const file of files) {
  210. if (!/\.js$/.test(file.path)) {
  211. continue;
  212. }
  213. let contents = file.contents.toString();
  214. const info = ts.preProcessFile(contents);
  215. for (let i = info.importedFiles.length - 1; i >= 0; i--) {
  216. const importText = info.importedFiles[i].fileName;
  217. const pos = info.importedFiles[i].pos;
  218. const end = info.importedFiles[i].end;
  219. if (/(\.css)|(\.js)$/.test(importText)) {
  220. // A CSS import or an import already using .js
  221. continue;
  222. }
  223. contents = contents.substring(0, pos + 1) + importText + '.js' + contents.substring(end + 1);
  224. }
  225. file.contents = Buffer.from(contents);
  226. }
  227. }
  228. /**
  229. * - Rename esm/vs/editor/editor.main.js to esm/vs/editor/edcore.main.js
  230. * - Create esm/vs/editor/editor.main.js that that stiches things together
  231. */
  232. function ESM_addPluginContribs(files: IFile[]) {
  233. for (const file of files) {
  234. if (!/editor\.main\.js$/.test(file.path)) {
  235. continue;
  236. }
  237. file.path = file.path.replace(/editor\.main/, 'edcore.main');
  238. }
  239. const mainFileDestPath = 'vs/editor/editor.main.js';
  240. const mainFileImports = readFiles(`out/languages/bundled/esm/**/monaco.contribution.js`, {
  241. base: `out/languages/bundled/esm`
  242. }).map((file) => {
  243. let relativePath = path
  244. .relative(path.dirname(mainFileDestPath), file.path)
  245. .replace(/\\/g, '/')
  246. .replace(/\.js$/, '');
  247. if (!/(^\.\/)|(^\.\.\/)/.test(relativePath)) {
  248. relativePath = './' + relativePath;
  249. }
  250. return relativePath;
  251. });
  252. const mainFileContents =
  253. mainFileImports.map((name) => `import '${name}';`).join('\n') +
  254. `\n\nexport * from './edcore.main';`;
  255. files.push({
  256. path: mainFileDestPath,
  257. contents: Buffer.from(mainFileContents)
  258. });
  259. }
  260. /**
  261. * Edit monaco.d.ts:
  262. * - append monaco.d.ts from plugins
  263. */
  264. function releaseDTS() {
  265. const monacodts = readFiles('node_modules/monaco-editor-core/monaco.d.ts', {
  266. base: 'node_modules/monaco-editor-core'
  267. })[0];
  268. let contents = monacodts.contents.toString();
  269. const extraContent = readFiles('out/languages/bundled/*.d.ts', {
  270. base: 'out/languages/bundled/'
  271. }).map((file) => {
  272. return file.contents.toString().replace(/\/\/\/ <reference.*\n/m, '');
  273. });
  274. contents =
  275. [
  276. '/*!-----------------------------------------------------------',
  277. ' * Copyright (c) Microsoft Corporation. All rights reserved.',
  278. ' * Type definitions for monaco-editor',
  279. ' * Released under the MIT license',
  280. '*-----------------------------------------------------------*/'
  281. ].join('\n') +
  282. '\n' +
  283. contents +
  284. '\n' +
  285. extraContent.join('\n');
  286. // Ensure consistent indentation and line endings
  287. contents = cleanFile(contents);
  288. monacodts.contents = Buffer.from(contents);
  289. const editorapidts = {
  290. path: 'esm/vs/editor/editor.api.d.ts',
  291. contents: Buffer.from(toExternalDTS(contents))
  292. };
  293. writeFiles([monacodts, editorapidts], `out/monaco-editor`);
  294. // fs.writeFileSync('website/typedoc/monaco.d.ts', contents);
  295. }
  296. /**
  297. * Transforms a .d.ts which uses internal modules (namespaces) to one which is usable with external modules
  298. * This function is duplicated in the `vscode` repo.
  299. */
  300. function toExternalDTS(contents: string): string {
  301. let lines = contents.split(/\r\n|\r|\n/);
  302. let killNextCloseCurlyBrace = false;
  303. for (let i = 0; i < lines.length; i++) {
  304. let line = lines[i];
  305. if (killNextCloseCurlyBrace) {
  306. if ('}' === line) {
  307. lines[i] = '';
  308. killNextCloseCurlyBrace = false;
  309. continue;
  310. }
  311. if (line.indexOf(' ') === 0) {
  312. lines[i] = line.substr(4);
  313. } else if (line.charAt(0) === '\t') {
  314. lines[i] = line.substr(1);
  315. }
  316. continue;
  317. }
  318. if ('declare namespace monaco {' === line) {
  319. lines[i] = '';
  320. killNextCloseCurlyBrace = true;
  321. continue;
  322. }
  323. if (line.indexOf('declare namespace monaco.') === 0) {
  324. lines[i] = line.replace('declare namespace monaco.', 'export namespace ');
  325. }
  326. if (line.indexOf('declare let MonacoEnvironment') === 0) {
  327. lines[i] = [
  328. 'declare global {',
  329. ' let MonacoEnvironment: Environment | undefined;',
  330. '',
  331. ' interface Window {',
  332. ' MonacoEnvironment?: Environment | undefined;',
  333. ' }',
  334. '}',
  335. ''
  336. ].join('\n');
  337. }
  338. if (line.indexOf(' MonacoEnvironment?') === 0) {
  339. lines[i] = ` MonacoEnvironment?: Environment | undefined;`;
  340. }
  341. }
  342. return lines.join('\n').replace(/\n\n\n+/g, '\n\n');
  343. }
  344. /**
  345. * Normalize line endings and ensure consistent 4 spaces indentation
  346. */
  347. function cleanFile(contents: string): string {
  348. return contents
  349. .split(/\r\n|\r|\n/)
  350. .map(function (line) {
  351. const m = line.match(/^(\t+)/);
  352. if (!m) {
  353. return line;
  354. }
  355. const tabsCount = m[1].length;
  356. let newIndent = '';
  357. for (let i = 0; i < 4 * tabsCount; i++) {
  358. newIndent += ' ';
  359. }
  360. return newIndent + line.substring(tabsCount);
  361. })
  362. .join('\n');
  363. }
  364. /**
  365. * Edit ThirdPartyNotices.txt:
  366. * - append ThirdPartyNotices.txt from plugins
  367. */
  368. function releaseThirdPartyNotices() {
  369. const tpn = readFiles('node_modules/monaco-editor-core/ThirdPartyNotices.txt', {
  370. base: 'node_modules/monaco-editor-core'
  371. })[0];
  372. let contents = tpn.contents.toString();
  373. console.log('ADDING ThirdPartyNotices from ./ThirdPartyNotices.txt');
  374. let thirdPartyNoticeContent = fs
  375. .readFileSync(path.join(REPO_ROOT, 'ThirdPartyNotices.txt'))
  376. .toString();
  377. thirdPartyNoticeContent = thirdPartyNoticeContent.split('\n').slice(8).join('\n');
  378. contents += '\n' + thirdPartyNoticeContent;
  379. tpn.contents = Buffer.from(contents);
  380. writeFiles([tpn], `out/monaco-editor`);
  381. }