utils.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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. * }} options
  145. */
  146. function buildOneAMD(type, options) {
  147. /** @type {import('esbuild').BuildOptions} */
  148. const opts = {
  149. entryPoints: [options.entryPoint],
  150. bundle: true,
  151. target: 'esnext',
  152. format: 'iife',
  153. define: {
  154. AMD: 'true'
  155. },
  156. globalName: 'moduleExports',
  157. banner: {
  158. js: `${bundledFileHeader}define("${options.amdModuleId}",[${(options.amdDependencies || [])
  159. .map((dep) => `"${dep}"`)
  160. .join(',')}],()=>{`
  161. },
  162. footer: {
  163. js: 'return moduleExports;\n});'
  164. },
  165. outbase: `src/${options.base}`,
  166. outdir: `out/release/${options.base}/${type}/`,
  167. plugins: [
  168. alias({
  169. 'vscode-nls': path.join(__dirname, '../build/fillers/vscode-nls.ts'),
  170. 'monaco-editor-core': path.join(__dirname, '../build/fillers/monaco-editor-core-amd.ts')
  171. })
  172. ]
  173. };
  174. if (type === 'min') {
  175. opts.minify = true;
  176. }
  177. build(opts);
  178. }
  179. /**
  180. * @param {{
  181. * base: string;
  182. * entryPoint: string;
  183. * amdModuleId: string;
  184. * amdDependencies?: string[];
  185. * }} options
  186. */
  187. function buildAMD(options) {
  188. buildOneAMD('dev', options);
  189. buildOneAMD('min', options);
  190. }
  191. exports.buildAMD = buildAMD;
  192. function getGitVersion() {
  193. const git = path.join(REPO_ROOT, '.git');
  194. const headPath = path.join(git, 'HEAD');
  195. let head;
  196. try {
  197. head = fs.readFileSync(headPath, 'utf8').trim();
  198. } catch (e) {
  199. return void 0;
  200. }
  201. if (/^[0-9a-f]{40}$/i.test(head)) {
  202. return head;
  203. }
  204. const refMatch = /^ref: (.*)$/.exec(head);
  205. if (!refMatch) {
  206. return void 0;
  207. }
  208. const ref = refMatch[1];
  209. const refPath = path.join(git, ref);
  210. try {
  211. return fs.readFileSync(refPath, 'utf8').trim();
  212. } catch (e) {
  213. // noop
  214. }
  215. const packedRefsPath = path.join(git, 'packed-refs');
  216. let refsRaw;
  217. try {
  218. refsRaw = fs.readFileSync(packedRefsPath, 'utf8').trim();
  219. } catch (e) {
  220. return void 0;
  221. }
  222. const refsRegex = /^([0-9a-f]{40})\s+(.+)$/gm;
  223. let refsMatch;
  224. const refs = {};
  225. while ((refsMatch = refsRegex.exec(refsRaw))) {
  226. refs[refsMatch[2]] = refsMatch[1];
  227. }
  228. return refs[ref];
  229. }
  230. const bundledFileHeader = (() => {
  231. const sha1 = getGitVersion();
  232. const semver = require('../package.json').version;
  233. const headerVersion = semver + '(' + sha1 + ')';
  234. const BUNDLED_FILE_HEADER = [
  235. '/*!-----------------------------------------------------------------------------',
  236. ' * Copyright (c) Microsoft Corporation. All rights reserved.',
  237. ' * Version: ' + headerVersion,
  238. ' * Released under the MIT license',
  239. ' * https://github.com/microsoft/monaco-editor/blob/main/LICENSE.txt',
  240. ' *-----------------------------------------------------------------------------*/',
  241. ''
  242. ].join('\n');
  243. return BUNDLED_FILE_HEADER;
  244. })();
  245. exports.bundledFileHeader = bundledFileHeader;
  246. /** @typedef {{ path:string; contents:Buffer;}} IFile */
  247. /**
  248. * @param {string} pattern
  249. * @param {{ base:string; ignore?:string[]; dot?:boolean; }} options
  250. * @returns {IFile[]}
  251. */
  252. function readFiles(pattern, options) {
  253. let files = glob.sync(pattern, { cwd: REPO_ROOT, ignore: options.ignore, dot: options.dot });
  254. // remove dirs
  255. files = files.filter((file) => {
  256. const fullPath = path.join(REPO_ROOT, file);
  257. const stats = fs.statSync(fullPath);
  258. return stats.isFile();
  259. });
  260. const base = options.base;
  261. const baseLength = base === '' ? 0 : base.endsWith('/') ? base.length : base.length + 1;
  262. return files.map((file) => {
  263. const fullPath = path.join(REPO_ROOT, file);
  264. const contents = fs.readFileSync(fullPath);
  265. const relativePath = file.substring(baseLength);
  266. return {
  267. path: relativePath,
  268. contents
  269. };
  270. });
  271. }
  272. exports.readFiles = readFiles;
  273. /**
  274. * @param {IFile[]} files
  275. * @param {string} dest
  276. */
  277. function writeFiles(files, dest) {
  278. for (const file of files) {
  279. const fullPath = path.join(REPO_ROOT, dest, file.path);
  280. ensureDir(path.dirname(fullPath));
  281. fs.writeFileSync(fullPath, file.contents);
  282. }
  283. }
  284. exports.writeFiles = writeFiles;