monaco-editor/build/utils.ts

292 lines
7.4 KiB
TypeScript
Raw Permalink Normal View History

/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
2022-02-03 21:56:52 +08:00
import * as fs from 'fs';
import * as path from 'path';
import * as cp from 'child_process';
import * as esbuild from 'esbuild';
import alias from 'esbuild-plugin-alias';
import * as glob from 'glob';
import { ensureDir } from './fs';
2021-11-12 18:22:26 +08:00
2022-02-03 21:56:52 +08:00
export const REPO_ROOT = path.join(__dirname, '../');
2021-11-12 05:13:12 +08:00
/**
* Launch the typescript compiler synchronously over a project.
*/
export function runTsc(_projectPath: string) {
2021-11-12 05:13:12 +08:00
const projectPath = path.join(REPO_ROOT, _projectPath);
2021-11-12 08:02:23 +08:00
console.log(`Launching compiler at ${_projectPath}...`);
const res = cp.spawnSync(
2021-11-12 17:55:50 +08:00
process.execPath,
[path.join(__dirname, '../node_modules/typescript/lib/tsc.js'), '-p', projectPath],
2021-11-12 18:22:26 +08:00
{ stdio: 'inherit' }
2021-11-12 17:55:50 +08:00
);
2021-11-12 05:13:12 +08:00
console.log(`Compiled ${_projectPath}`);
if (res.status !== 0) {
process.exit(res.status);
}
2021-11-12 05:13:12 +08:00
}
2021-11-12 05:19:08 +08:00
/**
* Launch prettier on a specific file.
*/
2022-02-03 21:56:52 +08:00
export function prettier(_filePath: string) {
2021-11-12 05:19:08 +08:00
const filePath = path.join(REPO_ROOT, _filePath);
2021-11-12 17:55:50 +08:00
cp.spawnSync(
process.execPath,
[path.join(__dirname, '../node_modules/prettier/bin-prettier.js'), '--write', filePath],
2021-11-12 18:22:26 +08:00
{ stdio: 'inherit' }
2021-11-12 17:55:50 +08:00
);
2021-11-12 05:19:08 +08:00
console.log(`Ran prettier over ${_filePath}`);
}
2021-11-12 05:13:12 +08:00
/**
* Transform an external .d.ts file to an internal .d.ts file
*/
export function massageAndCopyDts(source: string, destination: string, namespace: string) {
const absoluteSource = path.join(REPO_ROOT, source);
const absoluteDestination = path.join(REPO_ROOT, destination);
2021-11-12 05:13:12 +08:00
const lines = fs
.readFileSync(absoluteSource)
2021-11-12 05:13:12 +08:00
.toString()
.split(/\r\n|\r|\n/);
let result = [
`/*---------------------------------------------------------------------------------------------`,
` * Copyright (c) Microsoft Corporation. All rights reserved.`,
` * Licensed under the MIT License. See License.txt in the project root for license information.`,
` *--------------------------------------------------------------------------------------------*/`,
``,
`declare namespace ${namespace} {`
];
for (let line of lines) {
if (/^import/.test(line)) {
continue;
}
if (line === 'export {};') {
continue;
}
2021-11-12 05:13:12 +08:00
line = line.replace(/ /g, '\t');
line = line.replace(/declare /g, '');
if (line.length > 0) {
line = `\t${line}`;
result.push(line);
}
}
result.push(`}`);
result.push(``);
ensureDir(path.dirname(absoluteDestination));
fs.writeFileSync(absoluteDestination, result.join('\n'));
2021-11-12 05:19:08 +08:00
prettier(destination);
2021-11-12 05:13:12 +08:00
}
2021-11-12 05:45:32 +08:00
2022-02-03 21:56:52 +08:00
export function build(options: import('esbuild').BuildOptions) {
2021-11-12 18:10:04 +08:00
esbuild.build(options).then((result) => {
if (result.errors.length > 0) {
console.error(result.errors);
}
if (result.warnings.length > 0) {
console.error(result.warnings);
}
});
}
2022-02-03 21:56:52 +08:00
export function buildESM(options: { base: string; entryPoints: string[]; external: string[] }) {
2021-11-13 07:04:23 +08:00
build({
entryPoints: options.entryPoints,
bundle: true,
target: 'esnext',
format: 'esm',
drop: ['debugger'],
2021-11-13 07:04:23 +08:00
define: {
AMD: 'false'
},
banner: {
js: bundledFileHeader
},
external: options.external,
outbase: `src/${options.base}`,
outdir: `out/languages/bundled/esm/vs/${options.base}/`,
2021-11-13 07:04:23 +08:00
plugins: [
alias({
'vscode-nls': path.join(__dirname, 'fillers/vscode-nls.ts')
})
]
});
}
2022-02-03 21:56:52 +08:00
function buildOneAMD(
type: 'dev' | 'min',
options: {
base: string;
entryPoint: string;
amdModuleId: string;
amdDependencies?: string[];
external?: string[];
}
) {
if (!options.amdDependencies) {
options.amdDependencies = [];
}
options.amdDependencies.unshift('require');
2022-02-03 21:56:52 +08:00
const opts: esbuild.BuildOptions = {
2021-11-14 03:41:24 +08:00
entryPoints: [options.entryPoint],
2021-11-12 18:31:25 +08:00
bundle: true,
target: 'esnext',
format: 'iife',
drop: ['debugger'],
2021-11-12 18:31:25 +08:00
define: {
AMD: 'true'
},
globalName: 'moduleExports',
banner: {
js: `${bundledFileHeader}define("${options.amdModuleId}", [${(options.amdDependencies || [])
2021-11-14 02:40:20 +08:00
.map((dep) => `"${dep}"`)
.join(',')}],(require)=>{`
2021-11-12 18:31:25 +08:00
},
footer: {
js: 'return moduleExports;\n});'
},
2021-11-14 03:41:24 +08:00
outbase: `src/${options.base}`,
outdir: `out/languages/bundled/amd-${type}/vs/${options.base}/`,
2021-11-12 18:31:25 +08:00
plugins: [
alias({
'vscode-nls': path.join(__dirname, '../build/fillers/vscode-nls.ts'),
'monaco-editor-core': path.join(__dirname, '../src/fillers/monaco-editor-core-amd.ts')
2021-11-12 18:31:25 +08:00
})
],
external: ['vs/editor/editor.api', ...(options.external || [])]
2021-11-12 18:31:25 +08:00
};
if (type === 'min') {
opts.minify = true;
}
build(opts);
}
2022-02-03 21:56:52 +08:00
export function buildAMD(options: {
base: string;
entryPoint: string;
amdModuleId: string;
amdDependencies?: string[];
external?: string[];
}) {
2021-11-12 18:31:25 +08:00
buildOneAMD('dev', options);
buildOneAMD('min', options);
}
2021-11-12 05:45:32 +08:00
function getGitVersion() {
const git = path.join(REPO_ROOT, '.git');
const headPath = path.join(git, 'HEAD');
let head;
try {
head = fs.readFileSync(headPath, 'utf8').trim();
} catch (e) {
return void 0;
}
if (/^[0-9a-f]{40}$/i.test(head)) {
return head;
}
const refMatch = /^ref: (.*)$/.exec(head);
if (!refMatch) {
return void 0;
}
const ref = refMatch[1];
const refPath = path.join(git, ref);
try {
return fs.readFileSync(refPath, 'utf8').trim();
} catch (e) {
// noop
}
const packedRefsPath = path.join(git, 'packed-refs');
let refsRaw;
try {
refsRaw = fs.readFileSync(packedRefsPath, 'utf8').trim();
} catch (e) {
return void 0;
}
const refsRegex = /^([0-9a-f]{40})\s+(.+)$/gm;
let refsMatch;
const refs = {};
2021-11-12 17:55:50 +08:00
while ((refsMatch = refsRegex.exec(refsRaw))) {
2021-11-12 05:45:32 +08:00
refs[refsMatch[2]] = refsMatch[1];
}
return refs[ref];
}
2022-02-03 21:56:52 +08:00
export const bundledFileHeader = (() => {
2021-11-12 05:45:32 +08:00
const sha1 = getGitVersion();
const semver = require('../package.json').version;
const headerVersion = semver + '(' + sha1 + ')';
const BUNDLED_FILE_HEADER = [
'/*!-----------------------------------------------------------------------------',
' * Copyright (c) Microsoft Corporation. All rights reserved.',
' * Version: ' + headerVersion,
' * Released under the MIT license',
' * https://github.com/microsoft/monaco-editor/blob/main/LICENSE.txt',
' *-----------------------------------------------------------------------------*/',
''
].join('\n');
return BUNDLED_FILE_HEADER;
2021-11-12 21:31:18 +08:00
})();
2021-11-17 04:51:45 +08:00
2022-02-03 21:56:52 +08:00
export interface IFile {
path: string;
contents: Buffer;
}
2021-11-17 04:51:45 +08:00
2022-02-03 21:56:52 +08:00
export function readFiles(
pattern: string,
options: { base: string; ignore?: string[]; dot?: boolean }
): IFile[] {
2021-11-17 04:51:45 +08:00
let files = glob.sync(pattern, { cwd: REPO_ROOT, ignore: options.ignore, dot: options.dot });
// remove dirs
files = files.filter((file) => {
const fullPath = path.join(REPO_ROOT, file);
const stats = fs.statSync(fullPath);
return stats.isFile();
});
const base = options.base;
return files.map((file) => readFile(file, base));
}
export function readFile(file: string, base: string = '') {
2021-11-17 04:51:45 +08:00
const baseLength = base === '' ? 0 : base.endsWith('/') ? base.length : base.length + 1;
const fullPath = path.join(REPO_ROOT, file);
const contents = fs.readFileSync(fullPath);
const relativePath = file.substring(baseLength);
return {
path: relativePath,
contents
};
2021-11-17 04:51:45 +08:00
}
2022-02-03 21:56:52 +08:00
export function writeFiles(files: IFile[], dest: string) {
2021-11-17 04:51:45 +08:00
for (const file of files) {
const fullPath = path.join(REPO_ROOT, dest, file.path);
ensureDir(path.dirname(fullPath));
fs.writeFileSync(fullPath, file.contents);
}
}