utils.js 7.5 KB

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