release.js 13 KB

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