1
0

utils.ts 7.2 KB

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