utils.js 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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. const fs = require('fs');
  7. const path = require('path');
  8. const cp = require('child_process');
  9. const esbuild = require('esbuild');
  10. /** @type {any} */
  11. const alias = require('esbuild-plugin-alias');
  12. const glob = require('glob');
  13. const { ensureDir } = require('./fs');
  14. const REPO_ROOT = path.join(__dirname, '../');
  15. exports.REPO_ROOT = REPO_ROOT;
  16. /**
  17. * Launch the typescript compiler synchronously over a project.
  18. *
  19. * @param {string} _projectPath
  20. */
  21. function tsc(_projectPath) {
  22. const projectPath = path.join(REPO_ROOT, _projectPath);
  23. console.log(`Launching compiler at ${_projectPath}...`);
  24. const res = cp.spawnSync(
  25. process.execPath,
  26. [path.join(__dirname, '../node_modules/typescript/lib/tsc.js'), '-p', projectPath],
  27. { stdio: 'inherit' }
  28. );
  29. console.log(`Compiled ${_projectPath}`);
  30. if (res.status !== 0) {
  31. process.exit(res.status);
  32. }
  33. }
  34. exports.tsc = tsc;
  35. /**
  36. * Launch prettier on a specific file.
  37. *
  38. * @param {string} _filePath
  39. */
  40. function prettier(_filePath) {
  41. const filePath = path.join(REPO_ROOT, _filePath);
  42. cp.spawnSync(
  43. process.execPath,
  44. [path.join(__dirname, '../node_modules/prettier/bin-prettier.js'), '--write', filePath],
  45. { stdio: 'inherit' }
  46. );
  47. console.log(`Ran prettier over ${_filePath}`);
  48. }
  49. exports.prettier = prettier;
  50. /**
  51. * Transform an external .d.ts file to an internal .d.ts file
  52. *
  53. * @param {string} _source
  54. * @param {string} _destination
  55. * @param {string} namespace
  56. */
  57. function dts(_source, _destination, namespace) {
  58. const source = path.join(REPO_ROOT, _source);
  59. const destination = path.join(REPO_ROOT, _destination);
  60. const lines = fs
  61. .readFileSync(source)
  62. .toString()
  63. .split(/\r\n|\r|\n/);
  64. let result = [
  65. `/*---------------------------------------------------------------------------------------------`,
  66. ` * Copyright (c) Microsoft Corporation. All rights reserved.`,
  67. ` * Licensed under the MIT License. See License.txt in the project root for license information.`,
  68. ` *--------------------------------------------------------------------------------------------*/`,
  69. ``,
  70. `declare namespace ${namespace} {`
  71. ];
  72. for (let line of lines) {
  73. if (/^import/.test(line)) {
  74. continue;
  75. }
  76. if (line === 'export {};') {
  77. continue;
  78. }
  79. line = line.replace(/ /g, '\t');
  80. line = line.replace(/declare /g, '');
  81. if (line.length > 0) {
  82. line = `\t${line}`;
  83. result.push(line);
  84. }
  85. }
  86. result.push(`}`);
  87. result.push(``);
  88. ensureDir(path.dirname(destination));
  89. fs.writeFileSync(destination, result.join('\n'));
  90. prettier(_destination);
  91. }
  92. exports.dts = dts;
  93. /**
  94. * @param {import('esbuild').BuildOptions} options
  95. */
  96. function build(options) {
  97. esbuild.build(options).then((result) => {
  98. if (result.errors.length > 0) {
  99. console.error(result.errors);
  100. }
  101. if (result.warnings.length > 0) {
  102. console.error(result.warnings);
  103. }
  104. });
  105. }
  106. exports.build = build;
  107. /**
  108. * @param {{
  109. * base: string;
  110. * entryPoints: string[];
  111. * external: string[];
  112. * }} options
  113. */
  114. function buildESM(options) {
  115. build({
  116. entryPoints: options.entryPoints,
  117. bundle: true,
  118. target: 'esnext',
  119. format: 'esm',
  120. define: {
  121. AMD: 'false'
  122. },
  123. banner: {
  124. js: bundledFileHeader
  125. },
  126. external: options.external,
  127. outbase: `src/${options.base}`,
  128. outdir: `out/release/${options.base}/esm/`,
  129. plugins: [
  130. alias({
  131. 'vscode-nls': path.join(__dirname, 'fillers/vscode-nls.ts')
  132. })
  133. ]
  134. });
  135. }
  136. exports.buildESM = buildESM;
  137. /**
  138. * @param {'dev'|'min'} type
  139. * @param {{
  140. * base: string;
  141. * entryPoint: string;
  142. * amdModuleId: string;
  143. * amdDependencies?: string[];
  144. * external?: string[];
  145. * }} options
  146. */
  147. function buildOneAMD(type, options) {
  148. if (!options.amdDependencies) {
  149. options.amdDependencies = [];
  150. }
  151. options.amdDependencies.unshift('require');
  152. /** @type {import('esbuild').BuildOptions} */
  153. const opts = {
  154. entryPoints: [options.entryPoint],
  155. bundle: true,
  156. target: 'esnext',
  157. format: 'iife',
  158. define: {
  159. AMD: 'true'
  160. },
  161. globalName: 'moduleExports',
  162. banner: {
  163. js: `${bundledFileHeader}define("${options.amdModuleId}", [${(options.amdDependencies || [])
  164. .map((dep) => `"${dep}"`)
  165. .join(',')}],(require)=>{`
  166. },
  167. footer: {
  168. js: 'return moduleExports;\n});'
  169. },
  170. outbase: `src/${options.base}`,
  171. outdir: `out/release/${options.base}/${type}/`,
  172. plugins: [
  173. alias({
  174. 'vscode-nls': path.join(__dirname, '../build/fillers/vscode-nls.ts'),
  175. 'monaco-editor-core': path.join(__dirname, '../src/fillers/monaco-editor-core-amd.ts')
  176. })
  177. ],
  178. external: ['vs/editor/editor.api', ...(options.external || [])]
  179. };
  180. if (type === 'min') {
  181. opts.minify = true;
  182. }
  183. build(opts);
  184. }
  185. /**
  186. * @param {{
  187. * base: string;
  188. * entryPoint: string;
  189. * amdModuleId: string;
  190. * amdDependencies?: string[];
  191. * external?: string[];
  192. * }} options
  193. */
  194. function buildAMD(options) {
  195. buildOneAMD('dev', options);
  196. buildOneAMD('min', options);
  197. }
  198. exports.buildAMD = buildAMD;
  199. function getGitVersion() {
  200. const git = path.join(REPO_ROOT, '.git');
  201. const headPath = path.join(git, 'HEAD');
  202. let head;
  203. try {
  204. head = fs.readFileSync(headPath, 'utf8').trim();
  205. } catch (e) {
  206. return void 0;
  207. }
  208. if (/^[0-9a-f]{40}$/i.test(head)) {
  209. return head;
  210. }
  211. const refMatch = /^ref: (.*)$/.exec(head);
  212. if (!refMatch) {
  213. return void 0;
  214. }
  215. const ref = refMatch[1];
  216. const refPath = path.join(git, ref);
  217. try {
  218. return fs.readFileSync(refPath, 'utf8').trim();
  219. } catch (e) {
  220. // noop
  221. }
  222. const packedRefsPath = path.join(git, 'packed-refs');
  223. let refsRaw;
  224. try {
  225. refsRaw = fs.readFileSync(packedRefsPath, 'utf8').trim();
  226. } catch (e) {
  227. return void 0;
  228. }
  229. const refsRegex = /^([0-9a-f]{40})\s+(.+)$/gm;
  230. let refsMatch;
  231. const refs = {};
  232. while ((refsMatch = refsRegex.exec(refsRaw))) {
  233. refs[refsMatch[2]] = refsMatch[1];
  234. }
  235. return refs[ref];
  236. }
  237. const bundledFileHeader = (() => {
  238. const sha1 = getGitVersion();
  239. const semver = require('../package.json').version;
  240. const headerVersion = semver + '(' + sha1 + ')';
  241. const BUNDLED_FILE_HEADER = [
  242. '/*!-----------------------------------------------------------------------------',
  243. ' * Copyright (c) Microsoft Corporation. All rights reserved.',
  244. ' * Version: ' + headerVersion,
  245. ' * Released under the MIT license',
  246. ' * https://github.com/microsoft/monaco-editor/blob/main/LICENSE.txt',
  247. ' *-----------------------------------------------------------------------------*/',
  248. ''
  249. ].join('\n');
  250. return BUNDLED_FILE_HEADER;
  251. })();
  252. exports.bundledFileHeader = bundledFileHeader;
  253. /** @typedef {{ path:string; contents:Buffer;}} IFile */
  254. /**
  255. * @param {string} pattern
  256. * @param {{ base:string; ignore?:string[]; dot?:boolean; }} options
  257. * @returns {IFile[]}
  258. */
  259. function readFiles(pattern, options) {
  260. let files = glob.sync(pattern, { cwd: REPO_ROOT, ignore: options.ignore, dot: options.dot });
  261. // remove dirs
  262. files = files.filter((file) => {
  263. const fullPath = path.join(REPO_ROOT, file);
  264. const stats = fs.statSync(fullPath);
  265. return stats.isFile();
  266. });
  267. const base = options.base;
  268. const baseLength = base === '' ? 0 : base.endsWith('/') ? base.length : base.length + 1;
  269. return files.map((file) => {
  270. const fullPath = path.join(REPO_ROOT, file);
  271. const contents = fs.readFileSync(fullPath);
  272. const relativePath = file.substring(baseLength);
  273. return {
  274. path: relativePath,
  275. contents
  276. };
  277. });
  278. }
  279. exports.readFiles = readFiles;
  280. /**
  281. * @param {IFile[]} files
  282. * @param {string} dest
  283. */
  284. function writeFiles(files, dest) {
  285. for (const file of files) {
  286. const fullPath = path.join(REPO_ROOT, dest, file.path);
  287. ensureDir(path.dirname(fullPath));
  288. fs.writeFileSync(fullPath, file.contents);
  289. }
  290. }
  291. exports.writeFiles = writeFiles;