Switch monaco to off of moduleResolution: classic

Fixes #270408

Trying to move some of the monaco related checks/tconfigs off of `moduleResolution: classic`. This legacy config is causing a lot of pain while trying to update the trusted-types typings, which is itself blocking picking up the latest dompurify

I initially tried a more scoped change but just could not get it working. So instead I ended up trying to rework our `LanguageServiceHost` to be more standard
This commit is contained in:
Matt Bierner
2025-10-10 16:02:03 -07:00
parent 1414a15c9a
commit 1eee7ae230
14 changed files with 177 additions and 352 deletions

View File

@@ -54,9 +54,6 @@ const extractEditorSrcTask = task.define('extract-editor-src', () => {
importIgnorePattern: /\.css$/,
destRoot: path.join(root, 'out-editor-src'),
tsOutDir: '../out-monaco-editor-core/esm/vs',
redirects: {
'@vscode/tree-sitter-wasm': '../node_modules/@vscode/tree-sitter-wasm/wasm/web-tree-sitter',
}
});
});

View File

@@ -336,7 +336,7 @@ function generateDeclarationFile(ts, recipe, sourceFileGetter) {
usage.push(`var b: any;`);
const generateUsageImport = (moduleId) => {
const importName = 'm' + (++usageCounter);
usageImports.push(`import * as ${importName} from './${moduleId.replace(/\.d\.ts$/, '')}';`);
usageImports.push(`import * as ${importName} from './${moduleId}';`);
return importName;
};
const enums = [];
@@ -538,6 +538,9 @@ class DeclarationResolver {
if (/\.d\.ts$/.test(moduleId)) {
return path_1.default.join(SRC, moduleId);
}
if (/\.js$/.test(moduleId)) {
return path_1.default.join(SRC, moduleId.replace(/\.js$/, '.ts'));
}
return path_1.default.join(SRC, `${moduleId}.ts`);
}
_getDeclarationSourceFile(moduleId) {
@@ -555,7 +558,7 @@ class DeclarationResolver {
const fileMap = new Map([
['file.ts', fileContents]
]);
const service = this.ts.createLanguageService(new typeScriptLanguageServiceHost_1.TypeScriptLanguageServiceHost(this.ts, new Map(), fileMap, {}, 'defaultLib:es5'));
const service = this.ts.createLanguageService(new typeScriptLanguageServiceHost_1.TypeScriptLanguageServiceHost(this.ts, fileMap, {}));
const text = service.getEmitOutput('file.ts', true, true).outputFiles[0].text;
return new CacheEntry(this.ts.createSourceFile(fileName, text, this.ts.ScriptTarget.ES5), mtime);
}

View File

@@ -406,7 +406,7 @@ function generateDeclarationFile(ts: Typescript, recipe: string, sourceFileGette
const generateUsageImport = (moduleId: string) => {
const importName = 'm' + (++usageCounter);
usageImports.push(`import * as ${importName} from './${moduleId.replace(/\.d\.ts$/, '')}';`);
usageImports.push(`import * as ${importName} from './${moduleId}';`);
return importName;
};
@@ -641,6 +641,9 @@ export class DeclarationResolver {
if (/\.d\.ts$/.test(moduleId)) {
return path.join(SRC, moduleId);
}
if (/\.js$/.test(moduleId)) {
return path.join(SRC, moduleId.replace(/\.js$/, '.ts'));
}
return path.join(SRC, `${moduleId}.ts`);
}
@@ -662,7 +665,7 @@ export class DeclarationResolver {
const fileMap: IFileMap = new Map([
['file.ts', fileContents]
]);
const service = this.ts.createLanguageService(new TypeScriptLanguageServiceHost(this.ts, new Map(), fileMap, {}, 'defaultLib:es5'));
const service = this.ts.createLanguageService(new TypeScriptLanguageServiceHost(this.ts, fileMap, {}));
const text = service.getEmitOutput('file.ts', true, true).outputFiles[0].text;
return new CacheEntry(
this.ts.createSourceFile(fileName, text, this.ts.ScriptTarget.ES5),

View File

@@ -44,8 +44,6 @@ exports.extractEditor = extractEditor;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const tss = __importStar(require("./treeshaking"));
const REPO_ROOT = path_1.default.join(__dirname, '../../');
const SRC_DIR = path_1.default.join(REPO_ROOT, 'src');
const dirCache = {};
function writeFile(filePath, contents) {
function ensureDirs(dirPath) {
@@ -84,21 +82,11 @@ function extractEditor(options) {
console.log(`Running tree shaker with shakeLevel ${tss.toStringShakeLevel(options.shakeLevel)}`);
// Take the extra included .d.ts files from `tsconfig.monaco.json`
options.typings = tsConfig.include.filter(includedFile => /\.d\.ts$/.test(includedFile));
// Add extra .d.ts files from `node_modules/@types/`
if (Array.isArray(options.compilerOptions?.types)) {
options.compilerOptions.types.forEach((type) => {
if (type === '@webgpu/types') {
options.typings.push(`../node_modules/${type}/dist/index.d.ts`);
}
else {
options.typings.push(`../node_modules/@types/${type}/index.d.ts`);
}
});
}
const result = tss.shake(options);
for (const fileName in result) {
if (result.hasOwnProperty(fileName)) {
writeFile(path_1.default.join(options.destRoot, fileName), result[fileName]);
const relativePath = path_1.default.relative(options.sourcesRoot, fileName);
writeFile(path_1.default.join(options.destRoot, relativePath), result[fileName]);
}
}
const copied = {};
@@ -107,12 +95,20 @@ function extractEditor(options) {
return;
}
copied[fileName] = true;
const srcPath = path_1.default.join(options.sourcesRoot, fileName);
const dstPath = path_1.default.join(options.destRoot, fileName);
writeFile(dstPath, fs_1.default.readFileSync(srcPath));
if (path_1.default.isAbsolute(fileName)) {
const relativePath = path_1.default.relative(options.sourcesRoot, fileName);
const dstPath = path_1.default.join(options.destRoot, relativePath);
writeFile(dstPath, fs_1.default.readFileSync(fileName));
}
else {
const srcPath = path_1.default.join(options.sourcesRoot, fileName);
const dstPath = path_1.default.join(options.destRoot, fileName);
writeFile(dstPath, fs_1.default.readFileSync(srcPath));
}
};
const writeOutputFile = (fileName, contents) => {
writeFile(path_1.default.join(options.destRoot, fileName), contents);
const relativePath = path_1.default.isAbsolute(fileName) ? path_1.default.relative(options.sourcesRoot, fileName) : fileName;
writeFile(path_1.default.join(options.destRoot, relativePath), contents);
};
for (const fileName in result) {
if (result.hasOwnProperty(fileName)) {
@@ -147,8 +143,7 @@ function transportCSS(module, enqueue, write) {
if (!/\.css/.test(module)) {
return false;
}
const filename = path_1.default.join(SRC_DIR, module);
const fileContents = fs_1.default.readFileSync(filename).toString();
const fileContents = fs_1.default.readFileSync(module).toString();
const inlineResources = 'base64'; // see https://github.com/microsoft/monaco-editor/issues/148
const newContents = _rewriteOrInlineUrls(fileContents, inlineResources === 'base64');
write(module, newContents);
@@ -163,7 +158,7 @@ function transportCSS(module, enqueue, write) {
return relativeFontPath;
}
const imagePath = path_1.default.join(path_1.default.dirname(module), url);
const fileContents = fs_1.default.readFileSync(path_1.default.join(SRC_DIR, imagePath));
const fileContents = fs_1.default.readFileSync(imagePath);
const MIME = /\.svg$/.test(url) ? 'image/svg+xml' : 'image/png';
let DATA = ';base64,' + fileContents.toString('base64');
if (!forceBase64 && /\.svg$/.test(url)) {

View File

@@ -7,9 +7,6 @@ import fs from 'fs';
import path from 'path';
import * as tss from './treeshaking';
const REPO_ROOT = path.join(__dirname, '../../');
const SRC_DIR = path.join(REPO_ROOT, 'src');
const dirCache: { [dir: string]: boolean } = {};
function writeFile(filePath: string, contents: Buffer | string): void {
@@ -57,21 +54,11 @@ export function extractEditor(options: tss.ITreeShakingOptions & { destRoot: str
// Take the extra included .d.ts files from `tsconfig.monaco.json`
options.typings = (<string[]>tsConfig.include).filter(includedFile => /\.d\.ts$/.test(includedFile));
// Add extra .d.ts files from `node_modules/@types/`
if (Array.isArray(options.compilerOptions?.types)) {
options.compilerOptions.types.forEach((type: string) => {
if (type === '@webgpu/types') {
options.typings.push(`../node_modules/${type}/dist/index.d.ts`);
} else {
options.typings.push(`../node_modules/@types/${type}/index.d.ts`);
}
});
}
const result = tss.shake(options);
for (const fileName in result) {
if (result.hasOwnProperty(fileName)) {
writeFile(path.join(options.destRoot, fileName), result[fileName]);
const relativePath = path.relative(options.sourcesRoot, fileName);
writeFile(path.join(options.destRoot, relativePath), result[fileName]);
}
}
const copied: { [fileName: string]: boolean } = {};
@@ -80,12 +67,20 @@ export function extractEditor(options: tss.ITreeShakingOptions & { destRoot: str
return;
}
copied[fileName] = true;
const srcPath = path.join(options.sourcesRoot, fileName);
const dstPath = path.join(options.destRoot, fileName);
writeFile(dstPath, fs.readFileSync(srcPath));
if (path.isAbsolute(fileName)) {
const relativePath = path.relative(options.sourcesRoot, fileName);
const dstPath = path.join(options.destRoot, relativePath);
writeFile(dstPath, fs.readFileSync(fileName));
} else {
const srcPath = path.join(options.sourcesRoot, fileName);
const dstPath = path.join(options.destRoot, fileName);
writeFile(dstPath, fs.readFileSync(srcPath));
}
};
const writeOutputFile = (fileName: string, contents: string | Buffer) => {
writeFile(path.join(options.destRoot, fileName), contents);
const relativePath = path.isAbsolute(fileName) ? path.relative(options.sourcesRoot, fileName) : fileName;
writeFile(path.join(options.destRoot, relativePath), contents);
};
for (const fileName in result) {
if (result.hasOwnProperty(fileName)) {
@@ -127,8 +122,7 @@ function transportCSS(module: string, enqueue: (module: string) => void, write:
return false;
}
const filename = path.join(SRC_DIR, module);
const fileContents = fs.readFileSync(filename).toString();
const fileContents = fs.readFileSync(module).toString();
const inlineResources = 'base64'; // see https://github.com/microsoft/monaco-editor/issues/148
const newContents = _rewriteOrInlineUrls(fileContents, inlineResources === 'base64');
@@ -146,7 +140,7 @@ function transportCSS(module: string, enqueue: (module: string) => void, write:
}
const imagePath = path.join(path.dirname(module), url);
const fileContents = fs.readFileSync(path.join(SRC_DIR, imagePath));
const fileContents = fs.readFileSync(imagePath);
const MIME = /\.svg$/.test(url) ? 'image/svg+xml' : 'image/png';
let DATA = ';base64,' + fileContents.toString('base64');

View File

@@ -12,7 +12,6 @@ exports.shake = shake;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const typeScriptLanguageServiceHost_1 = require("./typeScriptLanguageServiceHost");
const TYPESCRIPT_LIB_FOLDER = path_1.default.dirname(require.resolve('typescript/lib/lib.d.ts'));
var ShakeLevel;
(function (ShakeLevel) {
ShakeLevel[ShakeLevel["Files"] = 0] = "Files";
@@ -68,101 +67,26 @@ function shake(options) {
//#region Discovery, LanguageService & Setup
function createTypeScriptLanguageService(ts, options) {
// Discover referenced files
const FILES = discoverAndReadFiles(ts, options);
const FILES = new Map();
// Add entrypoints
options.entryPoints.forEach(entryPoint => {
const filePath = path_1.default.join(options.sourcesRoot, `${entryPoint}.ts`);
FILES.set(filePath, fs_1.default.readFileSync(filePath).toString());
});
// Add fake usage files
options.inlineEntryPoints.forEach((inlineEntryPoint, index) => {
FILES.set(`inlineEntryPoint.${index}.ts`, inlineEntryPoint);
FILES.set(path_1.default.join(options.sourcesRoot, `inlineEntryPoint.${index}.ts`), inlineEntryPoint);
});
// Add additional typings
options.typings.forEach((typing) => {
const filePath = path_1.default.join(options.sourcesRoot, typing);
FILES.set(typing, fs_1.default.readFileSync(filePath).toString());
FILES.set(filePath, fs_1.default.readFileSync(filePath).toString());
});
// Resolve libs
const RESOLVED_LIBS = processLibFiles(ts, options);
const compilerOptions = ts.convertCompilerOptionsFromJson(options.compilerOptions, options.sourcesRoot).options;
const host = new typeScriptLanguageServiceHost_1.TypeScriptLanguageServiceHost(ts, RESOLVED_LIBS, FILES, compilerOptions, 'defaultLib:lib.d.ts');
const basePath = path_1.default.join(options.sourcesRoot, '..');
const compilerOptions = ts.convertCompilerOptionsFromJson(options.compilerOptions, basePath).options;
const host = new typeScriptLanguageServiceHost_1.TypeScriptLanguageServiceHost(ts, FILES, compilerOptions);
return ts.createLanguageService(host);
}
/**
* Read imports and follow them until all files have been handled
*/
function discoverAndReadFiles(ts, options) {
const FILES = new Map();
const in_queue = Object.create(null);
const queue = [];
const enqueue = (moduleId) => {
// To make the treeshaker work on windows...
moduleId = moduleId.replace(/\\/g, '/');
if (in_queue[moduleId]) {
return;
}
in_queue[moduleId] = true;
queue.push(moduleId);
};
options.entryPoints.forEach((entryPoint) => enqueue(entryPoint));
while (queue.length > 0) {
const moduleId = queue.shift();
let redirectedModuleId = moduleId;
if (options.redirects[moduleId]) {
redirectedModuleId = options.redirects[moduleId];
}
const dts_filename = path_1.default.join(options.sourcesRoot, redirectedModuleId + '.d.ts');
if (fs_1.default.existsSync(dts_filename)) {
const dts_filecontents = fs_1.default.readFileSync(dts_filename).toString();
FILES.set(`${moduleId}.d.ts`, dts_filecontents);
continue;
}
const js_filename = path_1.default.join(options.sourcesRoot, redirectedModuleId + '.js');
if (fs_1.default.existsSync(js_filename)) {
// This is an import for a .js file, so ignore it...
continue;
}
const ts_filename = path_1.default.join(options.sourcesRoot, redirectedModuleId + '.ts');
const ts_filecontents = fs_1.default.readFileSync(ts_filename).toString();
const info = ts.preProcessFile(ts_filecontents);
for (let i = info.importedFiles.length - 1; i >= 0; i--) {
const importedFileName = info.importedFiles[i].fileName;
if (options.importIgnorePattern.test(importedFileName)) {
// Ignore *.css imports
continue;
}
let importedModuleId = importedFileName;
if (/(^\.\/)|(^\.\.\/)/.test(importedModuleId)) {
importedModuleId = path_1.default.join(path_1.default.dirname(moduleId), importedModuleId);
if (importedModuleId.endsWith('.js')) { // ESM: code imports require to be relative and have a '.js' file extension
importedModuleId = importedModuleId.substr(0, importedModuleId.length - 3);
}
}
enqueue(importedModuleId);
}
FILES.set(`${moduleId}.ts`, ts_filecontents);
}
return FILES;
}
/**
* Read lib files and follow lib references
*/
function processLibFiles(ts, options) {
const stack = [...options.compilerOptions.lib];
const result = new Map();
while (stack.length > 0) {
const filename = `lib.${stack.shift().toLowerCase()}.d.ts`;
const key = `defaultLib:${filename}`;
if (!result.has(key)) {
// add this file
const filepath = path_1.default.join(TYPESCRIPT_LIB_FOLDER, filename);
const sourceText = fs_1.default.readFileSync(filepath).toString();
result.set(key, sourceText);
// precess dependencies and "recurse"
const info = ts.preProcessFile(sourceText);
for (const ref of info.libReferenceDirectives) {
stack.push(ref.fileName);
}
}
}
return result;
}
//#endregion
//#region Tree Shaking
var NodeColor;
@@ -410,9 +334,9 @@ function markNodes(ts, languageService, options) {
}
enqueueFile(fullPath);
}
options.entryPoints.forEach(moduleId => enqueueFile(moduleId + '.ts'));
options.entryPoints.forEach(moduleId => enqueueFile(path_1.default.join(options.sourcesRoot, moduleId + '.ts')));
// Add fake usage files
options.inlineEntryPoints.forEach((_, index) => enqueueFile(`inlineEntryPoint.${index}.ts`));
options.inlineEntryPoints.forEach((_, index) => enqueueFile(path_1.default.join(options.sourcesRoot, `inlineEntryPoint.${index}.ts`)));
let step = 0;
const checker = program.getTypeChecker();
while (black_queue.length > 0 || gray_queue.length > 0) {

View File

@@ -6,9 +6,7 @@
import fs from 'fs';
import path from 'path';
import type * as ts from 'typescript';
import { IFileMap, ILibMap, TypeScriptLanguageServiceHost } from './typeScriptLanguageServiceHost';
const TYPESCRIPT_LIB_FOLDER = path.dirname(require.resolve('typescript/lib/lib.d.ts'));
import { IFileMap, TypeScriptLanguageServiceHost } from './typeScriptLanguageServiceHost';
enum ShakeLevel {
Files = 0,
@@ -58,7 +56,7 @@ export interface ITreeShakingOptions {
*/
importIgnorePattern: RegExp;
redirects: { [module: string]: string };
// redirects: { [module: string]: string };
}
export interface ITreeShakingResult {
@@ -111,126 +109,31 @@ export function shake(options: ITreeShakingOptions): ITreeShakingResult {
//#region Discovery, LanguageService & Setup
function createTypeScriptLanguageService(ts: typeof import('typescript'), options: ITreeShakingOptions): ts.LanguageService {
// Discover referenced files
const FILES = discoverAndReadFiles(ts, options);
const FILES: IFileMap = new Map();
// Add entrypoints
options.entryPoints.forEach(entryPoint => {
const filePath = path.join(options.sourcesRoot, `${entryPoint}.ts`);
FILES.set(filePath, fs.readFileSync(filePath).toString());
});
// Add fake usage files
options.inlineEntryPoints.forEach((inlineEntryPoint, index) => {
FILES.set(`inlineEntryPoint.${index}.ts`, inlineEntryPoint);
FILES.set(path.join(options.sourcesRoot, `inlineEntryPoint.${index}.ts`), inlineEntryPoint);
});
// Add additional typings
options.typings.forEach((typing) => {
const filePath = path.join(options.sourcesRoot, typing);
FILES.set(typing, fs.readFileSync(filePath).toString());
FILES.set(filePath, fs.readFileSync(filePath).toString());
});
// Resolve libs
const RESOLVED_LIBS = processLibFiles(ts, options);
const compilerOptions = ts.convertCompilerOptionsFromJson(options.compilerOptions, options.sourcesRoot).options;
const host = new TypeScriptLanguageServiceHost(ts, RESOLVED_LIBS, FILES, compilerOptions, 'defaultLib:lib.d.ts');
const basePath = path.join(options.sourcesRoot, '..');
const compilerOptions = ts.convertCompilerOptionsFromJson(options.compilerOptions, basePath).options;
const host = new TypeScriptLanguageServiceHost(ts, FILES, compilerOptions);
return ts.createLanguageService(host);
}
/**
* Read imports and follow them until all files have been handled
*/
function discoverAndReadFiles(ts: typeof import('typescript'), options: ITreeShakingOptions): IFileMap {
const FILES: IFileMap = new Map();
const in_queue: { [module: string]: boolean } = Object.create(null);
const queue: string[] = [];
const enqueue = (moduleId: string) => {
// To make the treeshaker work on windows...
moduleId = moduleId.replace(/\\/g, '/');
if (in_queue[moduleId]) {
return;
}
in_queue[moduleId] = true;
queue.push(moduleId);
};
options.entryPoints.forEach((entryPoint) => enqueue(entryPoint));
while (queue.length > 0) {
const moduleId = queue.shift()!;
let redirectedModuleId: string = moduleId;
if (options.redirects[moduleId]) {
redirectedModuleId = options.redirects[moduleId];
}
const dts_filename = path.join(options.sourcesRoot, redirectedModuleId + '.d.ts');
if (fs.existsSync(dts_filename)) {
const dts_filecontents = fs.readFileSync(dts_filename).toString();
FILES.set(`${moduleId}.d.ts`, dts_filecontents);
continue;
}
const js_filename = path.join(options.sourcesRoot, redirectedModuleId + '.js');
if (fs.existsSync(js_filename)) {
// This is an import for a .js file, so ignore it...
continue;
}
const ts_filename = path.join(options.sourcesRoot, redirectedModuleId + '.ts');
const ts_filecontents = fs.readFileSync(ts_filename).toString();
const info = ts.preProcessFile(ts_filecontents);
for (let i = info.importedFiles.length - 1; i >= 0; i--) {
const importedFileName = info.importedFiles[i].fileName;
if (options.importIgnorePattern.test(importedFileName)) {
// Ignore *.css imports
continue;
}
let importedModuleId = importedFileName;
if (/(^\.\/)|(^\.\.\/)/.test(importedModuleId)) {
importedModuleId = path.join(path.dirname(moduleId), importedModuleId);
if (importedModuleId.endsWith('.js')) { // ESM: code imports require to be relative and have a '.js' file extension
importedModuleId = importedModuleId.substr(0, importedModuleId.length - 3);
}
}
enqueue(importedModuleId);
}
FILES.set(`${moduleId}.ts`, ts_filecontents);
}
return FILES;
}
/**
* Read lib files and follow lib references
*/
function processLibFiles(ts: typeof import('typescript'), options: ITreeShakingOptions): ILibMap {
const stack: string[] = [...options.compilerOptions.lib];
const result: ILibMap = new Map();
while (stack.length > 0) {
const filename = `lib.${stack.shift()!.toLowerCase()}.d.ts`;
const key = `defaultLib:${filename}`;
if (!result.has(key)) {
// add this file
const filepath = path.join(TYPESCRIPT_LIB_FOLDER, filename);
const sourceText = fs.readFileSync(filepath).toString();
result.set(key, sourceText);
// precess dependencies and "recurse"
const info = ts.preProcessFile(sourceText);
for (const ref of info.libReferenceDirectives) {
stack.push(ref.fileName);
}
}
}
return result;
}
//#endregion
//#region Tree Shaking
@@ -529,9 +432,9 @@ function markNodes(ts: typeof import('typescript'), languageService: ts.Language
enqueueFile(fullPath);
}
options.entryPoints.forEach(moduleId => enqueueFile(moduleId + '.ts'));
options.entryPoints.forEach(moduleId => enqueueFile(path.join(options.sourcesRoot, moduleId + '.ts')));
// Add fake usage files
options.inlineEntryPoints.forEach((_, index) => enqueueFile(`inlineEntryPoint.${index}.ts`));
options.inlineEntryPoints.forEach((_, index) => enqueueFile(path.join(options.sourcesRoot, `inlineEntryPoint.${index}.ts`)));
let step = 0;

View File

@@ -1,21 +1,26 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TypeScriptLanguageServiceHost = void 0;
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const typescript_1 = __importDefault(require("typescript"));
const node_fs_1 = __importDefault(require("node:fs"));
/**
* A TypeScript language service host
*/
class TypeScriptLanguageServiceHost {
ts;
libs;
files;
topLevelFiles;
compilerOptions;
defaultLibName;
constructor(ts, libs, files, compilerOptions, defaultLibName) {
constructor(ts, topLevelFiles, compilerOptions) {
this.ts = ts;
this.libs = libs;
this.files = files;
this.topLevelFiles = topLevelFiles;
this.compilerOptions = compilerOptions;
this.defaultLibName = defaultLibName;
}
// --- language service host ---------------
getCompilationSettings() {
@@ -23,8 +28,8 @@ class TypeScriptLanguageServiceHost {
}
getScriptFileNames() {
return [
...this.libs.keys(),
...this.files.keys(),
...this.topLevelFiles.keys(),
this.ts.getDefaultLibFilePath(this.compilerOptions)
];
}
getScriptVersion(_fileName) {
@@ -34,14 +39,11 @@ class TypeScriptLanguageServiceHost {
return '1';
}
getScriptSnapshot(fileName) {
if (this.files.has(fileName)) {
return this.ts.ScriptSnapshot.fromString(this.files.get(fileName));
}
else if (this.libs.has(fileName)) {
return this.ts.ScriptSnapshot.fromString(this.libs.get(fileName));
if (this.topLevelFiles.has(fileName)) {
return this.ts.ScriptSnapshot.fromString(this.topLevelFiles.get(fileName));
}
else {
return this.ts.ScriptSnapshot.fromString('');
return typescript_1.default.ScriptSnapshot.fromString(node_fs_1.default.readFileSync(fileName).toString());
}
}
getScriptKind(_fileName) {
@@ -51,16 +53,19 @@ class TypeScriptLanguageServiceHost {
return '';
}
getDefaultLibFileName(_options) {
return this.defaultLibName;
}
isDefaultLibFileName(fileName) {
return fileName === this.getDefaultLibFileName(this.compilerOptions);
return this.ts.getDefaultLibFilePath(_options);
}
readFile(path, _encoding) {
return this.files.get(path) || this.libs.get(path);
if (this.topLevelFiles.get(path)) {
return this.topLevelFiles.get(path);
}
return typescript_1.default.sys.readFile(path, _encoding);
}
fileExists(path) {
return this.files.has(path) || this.libs.has(path);
if (this.topLevelFiles.has(path)) {
return true;
}
return typescript_1.default.sys.fileExists(path);
}
}
exports.TypeScriptLanguageServiceHost = TypeScriptLanguageServiceHost;

View File

@@ -4,8 +4,9 @@
*--------------------------------------------------------------------------------------------*/
import ts from 'typescript';
import fs from 'node:fs';
// import path from 'node:path';
export type ILibMap = Map</*libName*/ string, string>;
export type IFileMap = Map</*fileName*/ string, string>;
/**
@@ -15,10 +16,8 @@ export class TypeScriptLanguageServiceHost implements ts.LanguageServiceHost {
constructor(
private readonly ts: typeof import('typescript'),
private readonly libs: ILibMap,
private readonly files: IFileMap,
private readonly topLevelFiles: IFileMap,
private readonly compilerOptions: ts.CompilerOptions,
private readonly defaultLibName: string,
) { }
// --- language service host ---------------
@@ -27,8 +26,8 @@ export class TypeScriptLanguageServiceHost implements ts.LanguageServiceHost {
}
getScriptFileNames(): string[] {
return [
...this.libs.keys(),
...this.files.keys(),
...this.topLevelFiles.keys(),
this.ts.getDefaultLibFilePath(this.compilerOptions)
];
}
getScriptVersion(_fileName: string): string {
@@ -38,12 +37,10 @@ export class TypeScriptLanguageServiceHost implements ts.LanguageServiceHost {
return '1';
}
getScriptSnapshot(fileName: string): ts.IScriptSnapshot {
if (this.files.has(fileName)) {
return this.ts.ScriptSnapshot.fromString(this.files.get(fileName)!);
} else if (this.libs.has(fileName)) {
return this.ts.ScriptSnapshot.fromString(this.libs.get(fileName)!);
if (this.topLevelFiles.has(fileName)) {
return this.ts.ScriptSnapshot.fromString(this.topLevelFiles.get(fileName)!);
} else {
return this.ts.ScriptSnapshot.fromString('');
return ts.ScriptSnapshot.fromString(fs.readFileSync(fileName).toString());
}
}
getScriptKind(_fileName: string): ts.ScriptKind {
@@ -53,15 +50,18 @@ export class TypeScriptLanguageServiceHost implements ts.LanguageServiceHost {
return '';
}
getDefaultLibFileName(_options: ts.CompilerOptions): string {
return this.defaultLibName;
}
isDefaultLibFileName(fileName: string): boolean {
return fileName === this.getDefaultLibFileName(this.compilerOptions);
return this.ts.getDefaultLibFilePath(_options);
}
readFile(path: string, _encoding?: string): string | undefined {
return this.files.get(path) || this.libs.get(path);
if (this.topLevelFiles.get(path)) {
return this.topLevelFiles.get(path);
}
return ts.sys.readFile(path, _encoding);
}
fileExists(path: string): boolean {
return this.files.has(path) || this.libs.has(path);
if (this.topLevelFiles.has(path)) {
return true;
}
return ts.sys.fileExists(path);
}
}

View File

@@ -70,27 +70,27 @@ declare namespace monaco {
dispose(): void;
}
#include(vs/platform/markers/common/markers): MarkerTag, MarkerSeverity
#include(vs/base/common/cancellation): CancellationTokenSource, CancellationToken
#include(vs/base/common/uri): URI, UriComponents
#include(vs/base/common/keyCodes): KeyCode
#include(vs/editor/common/services/editorBaseApi): KeyMod
#include(vs/base/common/htmlContent): IMarkdownString, MarkdownStringTrustedOptions
#include(vs/base/browser/keyboardEvent): IKeyboardEvent
#include(vs/base/browser/mouseEvent): IMouseEvent
#include(vs/editor/common/editorCommon): IScrollEvent
#include(vs/editor/common/core/position): IPosition, Position
#include(vs/editor/common/core/range): IRange, Range
#include(vs/editor/common/core/selection): ISelection, Selection, SelectionDirection
#include(vs/editor/common/languages): Token
#include(vs/platform/markers/common/markers.js): MarkerTag, MarkerSeverity
#include(vs/base/common/cancellation.js): CancellationTokenSource, CancellationToken
#include(vs/base/common/uri.js): URI, UriComponents
#include(vs/base/common/keyCodes.js): KeyCode
#include(vs/editor/common/services/editorBaseApi.js): KeyMod
#include(vs/base/common/htmlContent.js): IMarkdownString, MarkdownStringTrustedOptions
#include(vs/base/browser/keyboardEvent.js): IKeyboardEvent
#include(vs/base/browser/mouseEvent.js): IMouseEvent
#include(vs/editor/common/editorCommon.js): IScrollEvent
#include(vs/editor/common/core/position.js): IPosition, Position
#include(vs/editor/common/core/range.js): IRange, Range
#include(vs/editor/common/core/selection.js): ISelection, Selection, SelectionDirection
#include(vs/editor/common/languages.js): Token
}
declare namespace monaco.editor {
#includeAll(vs/editor/standalone/browser/standaloneEditor;languages.Token=>Token):
#include(vs/editor/standalone/common/standaloneTheme): BuiltinTheme, IStandaloneThemeData, IColors
#include(vs/editor/common/languages/supports/tokenization): ITokenThemeRule
#include(vs/editor/standalone/browser/standaloneWebWorker): MonacoWebWorker, IInternalWebWorkerOptions
#include(vs/editor/standalone/browser/standaloneCodeEditor): IActionDescriptor, IGlobalEditorOptions, IStandaloneEditorConstructionOptions, IStandaloneDiffEditorConstructionOptions, IStandaloneCodeEditor, IStandaloneDiffEditor
#includeAll(vs/editor/standalone/browser/standaloneEditor.js;languages.Token=>Token):
#include(vs/editor/standalone/common/standaloneTheme.js): BuiltinTheme, IStandaloneThemeData, IColors
#include(vs/editor/common/languages/supports/tokenization.js): ITokenThemeRule
#include(vs/editor/standalone/browser/standaloneWebWorker.js): MonacoWebWorker, IInternalWebWorkerOptions
#include(vs/editor/standalone/browser/standaloneCodeEditor.js): IActionDescriptor, IGlobalEditorOptions, IStandaloneEditorConstructionOptions, IStandaloneDiffEditorConstructionOptions, IStandaloneCodeEditor, IStandaloneDiffEditor
export interface ICommandHandler {
(...args: any[]): void;
}
@@ -101,27 +101,27 @@ export interface ILocalizedString {
export interface ICommandMetadata {
readonly description: ILocalizedString | string;
}
#include(vs/platform/contextkey/common/contextkey): IContextKey, ContextKeyValue
#include(vs/editor/standalone/browser/standaloneServices): IEditorOverrideServices
#include(vs/platform/markers/common/markers): IMarker, IMarkerData, IRelatedInformation
#include(vs/editor/standalone/browser/colorizer): IColorizerOptions, IColorizerElementOptions
#include(vs/base/common/scrollable): ScrollbarVisibility
#include(vs/base/common/themables): ThemeColor, ThemeIcon
#include(vs/editor/common/core/editOperation): ISingleEditOperation
#include(vs/editor/common/core/wordHelper): IWordAtPosition
#includeAll(vs/editor/common/model): IScrollEvent
#include(vs/editor/common/diff/legacyLinesDiffComputer): IChange, ICharChange, ILineChange
#include(vs/editor/common/core/2d/dimension): IDimension
#includeAll(vs/editor/common/editorCommon): IScrollEvent
#includeAll(vs/editor/common/textModelEvents):
#include(vs/editor/common/model/mirrorTextModel): IModelContentChange
#includeAll(vs/editor/common/cursorEvents):
#include(vs/platform/accessibility/common/accessibility): AccessibilitySupport
#includeAll(vs/editor/common/config/editorOptions):
#include(vs/editor/browser/config/editorConfiguration): IEditorConstructionOptions
#includeAll(vs/editor/browser/editorBrowser;editorCommon.=>):
#include(vs/editor/common/config/fontInfo): FontInfo, BareFontInfo
#include(vs/editor/common/config/editorZoom): EditorZoom, IEditorZoom
#include(vs/platform/contextkey/common/contextkey.js): IContextKey, ContextKeyValue
#include(vs/editor/standalone/browser/standaloneServices.js): IEditorOverrideServices
#include(vs/platform/markers/common/markers.js): IMarker, IMarkerData, IRelatedInformation
#include(vs/editor/standalone/browser/colorizer.js): IColorizerOptions, IColorizerElementOptions
#include(vs/base/common/scrollable.js): ScrollbarVisibility
#include(vs/base/common/themables.js): ThemeColor, ThemeIcon
#include(vs/editor/common/core/editOperation.js): ISingleEditOperation
#include(vs/editor/common/core/wordHelper.js): IWordAtPosition
#includeAll(vs/editor/common/model.js): IScrollEvent
#include(vs/editor/common/diff/legacyLinesDiffComputer.js): IChange, ICharChange, ILineChange
#include(vs/editor/common/core/2d/dimension.js): IDimension
#includeAll(vs/editor/common/editorCommon.js): IScrollEvent
#includeAll(vs/editor/common/textModelEvents.js):
#include(vs/editor/common/model/mirrorTextModel.js): IModelContentChange
#includeAll(vs/editor/common/cursorEvents.js):
#include(vs/platform/accessibility/common/accessibility.js): AccessibilitySupport
#includeAll(vs/editor/common/config/editorOptions.js):
#include(vs/editor/browser/config/editorConfiguration.js): IEditorConstructionOptions
#includeAll(vs/editor/browser/editorBrowser.js;editorCommon.=>):
#include(vs/editor/common/config/fontInfo.js): FontInfo, BareFontInfo
#include(vs/editor/common/config/editorZoom.js): EditorZoom, IEditorZoom
//compatibility:
export type IReadOnlyModel = ITextModel;
@@ -130,21 +130,21 @@ export type IModel = ITextModel;
declare namespace monaco.languages {
#include(vs/editor/common/textModelEditSource): EditDeltaInfo
#include(vs/base/common/glob): IRelativePattern
#include(vs/editor/common/languageSelector): LanguageSelector, LanguageFilter
#includeAll(vs/editor/standalone/browser/standaloneLanguages;languages.=>;editorCommon.=>editor.;model.=>editor.;IMarkerData=>editor.IMarkerData):
#includeAll(vs/editor/common/languages/languageConfiguration):
#includeAll(vs/editor/common/languages;IMarkerData=>editor.IMarkerData;ISingleEditOperation=>editor.ISingleEditOperation;model.=>editor.;ThemeIcon=>editor.ThemeIcon): Token
#include(vs/editor/common/languages/language): ILanguageExtensionPoint
#includeAll(vs/editor/standalone/common/monarch/monarchTypes):
#include(vs/editor/common/textModelEditSource.js): EditDeltaInfo
#include(vs/base/common/glob.js): IRelativePattern
#include(vs/editor/common/languageSelector.js): LanguageSelector, LanguageFilter
#includeAll(vs/editor/standalone/browser/standaloneLanguages.js;languages.=>;editorCommon.=>editor.;model.=>editor.;IMarkerData=>editor.IMarkerData):
#includeAll(vs/editor/common/languages/languageConfiguration.js):
#includeAll(vs/editor/common/languages.js;IMarkerData=>editor.IMarkerData;ISingleEditOperation=>editor.ISingleEditOperation;model.=>editor.;ThemeIcon=>editor.ThemeIcon): Token
#include(vs/editor/common/languages/language.js): ILanguageExtensionPoint
#includeAll(vs/editor/standalone/common/monarch/monarchTypes.js):
}
declare namespace monaco.worker {
#include(vs/editor/common/model/mirrorTextModel): IMirrorTextModel
#includeAll(vs/editor/common/services/editorWebWorker;):
#include(vs/editor/common/model/mirrorTextModel.js): IMirrorTextModel
#includeAll(vs/editor/common/services/editorWebWorker.js;):
}

View File

@@ -1,12 +1,12 @@
// This file is adding references to various symbols which should not be removed via tree shaking
import { IObservable } from './vs/base/common/observable';
import { IObservable } from './vs/base/common/observable.js';
import { ServiceIdentifier } from './vs/platform/instantiation/common/instantiation';
import { start } from './vs/editor/editor.worker.start';
import { SyncDescriptor0 } from './vs/platform/instantiation/common/descriptors';
import * as editorAPI from './vs/editor/editor.api';
import { ServiceIdentifier } from './vs/platform/instantiation/common/instantiation.js';
import { start } from './vs/editor/editor.worker.start.js';
import { SyncDescriptor0 } from './vs/platform/instantiation/common/descriptors.js';
import * as editorAPI from './vs/editor/editor.api.js';
(function () {
var a: any;

11
package-lock.json generated
View File

@@ -74,7 +74,7 @@
"@types/trusted-types": "^1.0.6",
"@types/vscode-notebook-renderer": "^1.72.0",
"@types/webpack": "^5.28.5",
"@types/wicg-file-system-access": "^2020.9.6",
"@types/wicg-file-system-access": "^2023.10.7",
"@types/windows-foreground-love": "^0.3.0",
"@types/winreg": "^1.2.30",
"@types/yauzl": "^2.10.0",
@@ -2197,10 +2197,11 @@
}
},
"node_modules/@types/wicg-file-system-access": {
"version": "2020.9.6",
"resolved": "https://registry.npmjs.org/@types/wicg-file-system-access/-/wicg-file-system-access-2020.9.6.tgz",
"integrity": "sha512-6hogE75Hl2Ov/jgp8ZhDaGmIF/q3J07GtXf8nCJCwKTHq7971po5+DId7grft09zG7plBwpF6ZU0yx9Du4/e1A==",
"dev": true
"version": "2023.10.7",
"resolved": "https://registry.npmjs.org/@types/wicg-file-system-access/-/wicg-file-system-access-2023.10.7.tgz",
"integrity": "sha512-g49ijasEJvCd7ifmAY2D0wdEtt1xRjBbA33PJTiv8mKBr7DoMsPeISoJ8oQOTopSRi+FBWPpPW5ouDj2QPKtGA==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/windows-foreground-love": {
"version": "0.3.0",

View File

@@ -135,7 +135,7 @@
"@types/trusted-types": "^1.0.6",
"@types/vscode-notebook-renderer": "^1.72.0",
"@types/webpack": "^5.28.5",
"@types/wicg-file-system-access": "^2020.9.6",
"@types/wicg-file-system-access": "^2023.10.7",
"@types/windows-foreground-love": "^0.3.0",
"@types/winreg": "^1.2.30",
"@types/yauzl": "^2.10.0",
@@ -239,4 +239,4 @@
"optionalDependencies": {
"windows-foreground-love": "0.5.0"
}
}
}

View File

@@ -9,7 +9,7 @@
],
"paths": {},
"module": "esnext",
"moduleResolution": "classic",
"moduleResolution": "nodenext",
"removeComments": false,
"preserveConstEnums": true,
"target": "ES2022",