### Initialize Server and Send Completion Request Example Source: https://github.com/volarjs/volar.js/blob/master/packages/test-utils/README.md Illustrates a common workflow: initializing the language server, opening a text document, and then sending a completion request to retrieve code completions for a specific position within the document. ```typescript await serverHandle.initialize('file:///path/to/workspace', {}); const document = await serverHandle.openTextDocument('path/to/file', 'typescript'); const completions = await serverHandle.sendCompletionRequest(document.uri, { line: 0, character: 0 }); ``` -------------------------------- ### Import and Start Volar Language Server Source: https://github.com/volarjs/volar.js/blob/master/packages/test-utils/README.md Demonstrates how to import `startLanguageServer` from `@volar/test-utils` and initialize a language server by providing the path to its module. The function optionally accepts a current working directory. ```typescript import { startLanguageServer } from '@volar/test-utils'; const serverHandle = startLanguageServer('path/to/server/module'); ``` -------------------------------- ### TypeScript Mapping Data Structure Example Source: https://github.com/volarjs/volar.js/blob/master/packages/source-map/README.md An example demonstrating the structure of a `Mapping` tuple, showing how source, generated offsets, lengths, and custom data are represented within the source map context. ```TypeScript let mapping: Mapping = { source: '.../sourceFile.ts', sourceOffsets: [10], generatedOffsets: [30], lengths: [10], data: myData, }; ``` -------------------------------- ### Monitor file changes and lint with Volar.js Kit FileWatcher Source: https://github.com/volarjs/volar.js/blob/master/packages/kit/README.md This example demonstrates how to set up a file watcher using `chokidar` to monitor TypeScript, JavaScript, and custom 'foo' files. It integrates with `@volar/kit` to update the project's file state (created, deleted, updated) and trigger a linter check on changes. The `update` function includes debouncing and console clearing for a responsive linter output. ```ts import * as fs from 'fs'; import * as path from 'path'; import { watch } from 'chokidar'; import * as kit from '@volar/kit'; const tsconfig = getTsconfig(); const project = kit.createProject(tsconfig, [{ extension: 'foo', isMixedContent: true, scriptKind: 7 }]); const config: kit.Config = { languages: { // ... }, services: { // ... }, }; const linter = kit.createLinter(config, project.languageServiceHost); let req = 0; update(); createWatcher(path.dirname(tsconfig), ['ts', 'js', 'foo']) .on('add', (fileName) => { project.fileCreated(fileName); update(); }) .on('unlink', (fileName) => { project.fileDeleted(fileName); update(); }) .on('change', (fileName) => { project.fileUpdated(fileName); update(); }); function createWatcher(rootPath: string, extension: string[]) { return watch(`${rootPath}/**/*.{${extension.join(',')}}`, { ignored: (path) => path.includes('node_modules'), ignoreInitial: true }); } async function update() { const currentReq = ++req; const isCanceled = () => currentReq !== req; await new Promise(resolve => setTimeout(resolve, 100)); if (isCanceled()) return; process.stdout.write('\x1Bc'); // clear console let hasError = false; for (const fileName of project.languageServiceHost.getScriptFileNames()) { const errors = await linter.check(fileName); if (isCanceled()) return; if (errors.length) { linter.logErrors(fileName, errors); hasError = true; } } if (!hasError) { console.log('No errors'); } } function getTsconfig() { let tsconfig = path.resolve(process.cwd(), './tsconfig.json'); const tsconfigIndex = process.argv.indexOf('--tsconfig'); if (tsconfigIndex >= 0) { tsconfig = path.resolve(process.cwd(), process.argv[tsconfigIndex + 1]); } if (!fs.existsSync(tsconfig)) { throw `tsconfig.json not found: ${tsconfig}`; } return tsconfig; } ``` -------------------------------- ### Volar Language Server Handle API Reference Source: https://github.com/volarjs/volar.js/blob/master/packages/test-utils/README.md Documents the methods available on the `serverHandle` object returned by `startLanguageServer`, detailing how to interact with the language server for initialization, document management, and sending various language-related requests. ```APIDOC serverHandle: - initialize(rootUri: string, initializationOptions: InitializationOptions) Description: Initializes the language server. Parameters: - rootUri: string - The root URI of the workspace. - initializationOptions: InitializationOptions - Options for initializing the language server. - openTextDocument(fileName: string, languageId: string) Description: Opens a text document. Parameters: - fileName: string - The path to the document to open. - languageId: string - The language ID of the document (e.g., 'typescript'). - openUntitledDocument(languageId: string, content: string) Description: Opens an untitled text document. Parameters: - languageId: string - The language ID of the untitled document. - content: string - The initial content of the untitled document. - closeTextDocument(uri: string) Description: Closes a text document. Parameters: - uri: string - The URI of the document to close. - send*Request methods Description: Send various language-related requests to the server. ``` -------------------------------- ### SourceMap Class API Reference Source: https://github.com/volarjs/volar.js/blob/master/packages/source-map/README.md Detailed documentation for the `SourceMap` class, including its constructor parameters and methods for converting between source and generated code offsets. ```APIDOC SourceMap Class: Description: Provides functionality related to source maps. Constructor Parameters: fallbackToAnyMatch (boolean, default: false): Allow the start and end offsets to come from different mappings. filter? (function, default: undefined): (data: Data) => boolean - According to mapping: Mapping.data, filter out offsets that do not meet the custom conditions. Methods: toSourceRange(generatedStart: number, generatedEnd: number, fallbackToAnyMatch: boolean, filter?: (data: Data) => boolean): Returns all source start and end offsets for the given generated start and end offsets. toGeneratedRange(sourceStart: number, sourceEnd: number, fallbackToAnyMatch: boolean, filter?: (data: Data) => boolean): Returns all generated start and end offsets for the given source start and end offsets. toSourceLocation(generatedOffset: number, filter?: (data: Data) => boolean): Returns all source offsets for a given generated offset. toGeneratedLocation(sourceOffset: number, filter?: (data: Data) => boolean): Returns all generated offsets for a given source offset. ``` -------------------------------- ### Volar.js Package Dependency Tree Source: https://github.com/volarjs/volar.js/blob/master/README.md This diagram illustrates the hierarchical structure and dependencies among the core packages within the Volar.js project. It shows how @volar/language-core forms the foundational layer, supporting @volar/language-service, which in turn enables @volar/language-server and other editor integrations like @volar/vscode and @volar/monaco, as well as Node.js utility via @volar/kit. ```text @volar/language-core | |--- @volar/language-service | |--- @volar/language-server | | | |--- @volar/vscode (as a client to the language server) | |--- @volar/kit (encapsulates @volar/language-service for Node.js applications) | |--- @volar/monaco (integrates @volar/language-service into Monaco Editor) ``` -------------------------------- ### Create an inferred Volar.js Kit project without tsconfig.json Source: https://github.com/volarjs/volar.js/blob/master/packages/kit/README.md This snippet illustrates how to initialize a Volar.js project using `kit.createInferredProject`. This method is useful when a `tsconfig.json` file is not available or desired, allowing the project to be defined directly by a root path and a list of source file names. ```ts const rootPath = process.cwd(); const fileNames = [ path.resolve(rootPath, './src/a.ts'), path.resolve(rootPath, './src/b.js'), path.resolve(rootPath, './src/c.foo'), ]; const project = kit.createInferredProject(rootPath, fileNames); ``` -------------------------------- ### Initialize Volar.js Language Service Worker Source: https://github.com/volarjs/volar.js/blob/master/packages/monaco/README.md This TypeScript code sets up a web worker for a custom language service using `@volar/monaco`. It initializes the Monaco editor worker context and creates a simple worker language service, defining the workspace folders for the environment. ```ts import * as worker from 'monaco-editor-core/esm/vs/editor/editor.worker'; import type * as monaco from 'monaco-editor-core'; import type { LanguageServiceEnvironment } from '@volar/language-service'; import { createSimpleWorkerLanguageService } from '@volar/monaco/worker'; import { URI } from 'vscode-uri'; self.onmessage = () => { worker.initialize((ctx: monaco.worker.IWorkerContext) => { const env: LanguageServiceEnvironment = { workspaceFolders: [ URI.parse('file:///'), ], }; return createSimpleWorkerLanguageService({ workerContext: ctx, ev, languagePlugins: [ // ... ], languageServicePlugins: [ // ... ], }); }); }; ``` -------------------------------- ### Enable Automatic Type Acquisition (ATA) for TypeScript in Volar.js Worker Source: https://github.com/volarjs/volar.js/blob/master/packages/monaco/README.md This diff demonstrates how to add Automatic Type Acquisition (ATA) support to the TypeScript language service worker. It integrates `@volar/jsdelivr`'s `createNpmFileSystem` into the environment's `fs` property, allowing the worker to fetch missing package types automatically. ```ts import * as worker from 'monaco-editor-core/esm/vs/editor/editor.worker'; import type * as monaco from 'monaco-editor-core'; import type { LanguageServiceEnvironment } from '@volar/language-service'; import { createTypeScriptWorkerLanguageService } from '@volar/monaco/worker'; import { URI } from 'vscode-uri'; +import { createNpmFileSystem } from '@volar/jsdelivr'; import { create as createTypeScriptServicePlugin } from 'volar-service-typescript'; import ts from 'typescript'; self.onmessage = () => { worker.initialize((ctx: monaco.worker.IWorkerContext) => { const env: LanguageServiceEnvironment = { workspaceFolders: [ URI.parse('file:///'), ], }; + env.fs = createNpmFileSystem(); return createTypeScriptWorkerLanguageService({ typescript: ts, compilerOptions: { // ... }, uriConverter: { asFileName: uri => uri.fsPath, asUri: fileName => URI.file(fileName), }, workerContext: ctx, ev, languagePlugins: [ // ... ], languageServicePlugins: [ // ... createTypeScriptServicePlugin(ts), ], }); }); }; ``` -------------------------------- ### Integrate TypeScript Language Service into Volar.js Worker Source: https://github.com/volarjs/volar.js/blob/master/packages/monaco/README.md This diff shows how to modify the language service worker to support TypeScript. It replaces `createSimpleWorkerLanguageService` with `createTypeScriptWorkerLanguageService` and adds TypeScript-specific configurations like the `typescript` instance, `compilerOptions`, and a `uriConverter` for file path handling. ```ts import * as worker from 'monaco-editor-core/esm/vs/editor/editor.worker'; import type * as monaco from 'monaco-editor-core'; import type { LanguageServiceEnvironment } from '@volar/language-service'; -import { createSimpleWorkerLanguageService }n from '@volar/monaco/worker'; +import { createTypeScriptWorkerLanguageService } from '@volar/monaco/worker'; import { URI } from 'vscode-uri'; +import { create as createTypeScriptServicePlugin } from 'volar-service-typescript'; +import ts from 'typescript'; self.onmessage = () => { worker.initialize((ctx: monaco.worker.IWorkerContext) => { const env: LanguageServiceEnvironment = { workspaceFolders: [ URI.parse('file:///'), ], }; - return createSimpleWorkerLanguageService({ + return createTypeScriptWorkerLanguageService({ + typescript: ts, + compilerOptions: { + // ... + }, + uriConverter: { + asFileName: uri => uri.fsPath, + asUri: fileName => URI.file(fileName), + }, workerContext: ctx, ev, languagePlugins: [ // ... ], languageServicePlugins: [ // ... + ...createTypeScriptServicePlugin(ts), ], }); }); }; ``` -------------------------------- ### Configure Monaco Editor Worker Loader Source: https://github.com/volarjs/volar.js/blob/master/packages/monaco/README.md This TypeScript code configures the Monaco Editor's global environment to load custom language workers. It defines `MonacoEnvironment.getWorker` to return the appropriate worker instance based on the language label, distinguishing between a custom language worker and the default editor worker. ```ts import editorWorker from 'monaco-editor-core/esm/vs/editor/editor.worker?worker'; import myWorker from './my-lang.worker?worker'; (self as any).MonacoEnvironment = { getWorker(_: any, label: string) { if (label === 'my-lang') { return new myWorker(); } return new editorWorker(); } } ``` -------------------------------- ### Register Volar.js Language Features in Monaco Editor Source: https://github.com/volarjs/volar.js/blob/master/packages/monaco/README.md This TypeScript code registers a custom language (`my-lang`) with Monaco Editor and activates various Volar.js-based language features. It creates a web worker for the language service and then registers markers (diagnostics), auto-insertion, and other language providers for the custom language, linking them to specific files. ```ts import type { WorkerLanguageService } from '@volar/monaco/worker'; import { editor, languages, Uri } from 'monaco-editor-core'; import { activateMarkers, activateAutoInsertion, registerProviders } from '@volar/monaco'; languages.register({ id: 'my-lang', extensions: ['.my-lang'] }); languages.onLanguage('my-lang', () => { const worker = editor.createWebWorker({ moduleId: 'vs/language/my-lang/myLangWorker', label: 'my-lang', }); activateMarkers( worker, ['my-lang'], 'my-lang-markers-owner', // sync files () => [Uri.file('/Foo.my-lang'), Uri.file('/Bar.my-lang')], editor ); // auto close tags activateAutoInsertion( worker, ['my-lang'], // sync files () => [Uri.file('/Foo.my-lang'), Uri.file('/Bar.my-lang')], editor ); registerProviders( worker, ['my-lang'], // sync files () => [Uri.file('/Foo.my-lang'), Uri.file('/Bar.my-lang')], languages ) }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.