### Complete Example Structure Source: https://github.com/luke-hagar-sp/volar.js/blob/master/docs/CONTRIBUTING_DOCS.md Defines the structure for complete and runnable code examples, including setup, implementation, usage, and explanation. ```markdown ### Example: Feature Name Brief description of what the example demonstrates. ```typescript // Step 1: Setup import { ... } from '...'; // Step 2: Implementation const instance = createInstance(...); // Step 3: Usage const result = instance.doSomething(); ``` **Explanation:** - Step 1 does X - Step 2 does Y - Step 3 produces Z ``` -------------------------------- ### Basic Test Setup Example Source: https://github.com/luke-hagar-sp/volar.js/blob/master/packages/test-utils/README.md Sets up a language server, initializes it, opens a document, and sends a completion request. Ensure to shut down the server after tests. ```typescript import { startLanguageServer } from "@volar/test-utils"; import { describe, it, expect, afterEach } from "vitest"; describe("Language Server Tests", () => { const serverHandle = startLanguageServer("./dist/server.js"); afterEach(async () => { await serverHandle.shutdown(); }); it("should provide completions", async () => { await serverHandle.initialize("file:///workspace", {}); const document = await serverHandle.openTextDocument( "./test.ts", "typescript" ); const completions = await serverHandle.sendCompletionRequest(document.uri, { line: 0, character: 10, }); expect(completions).toBeDefined(); expect(completions?.items.length).toBeGreaterThan(0); }); }); ``` -------------------------------- ### Setup and Teardown Pattern Source: https://github.com/luke-hagar-sp/volar.js/blob/master/packages/test-utils/README.md A common testing pattern using `beforeEach` to start and initialize the server, and `afterEach` to shut it down. ```typescript describe("Language Server", () => { let serverHandle: LanguageServerHandle; beforeEach(async () => { serverHandle = startLanguageServer("./dist/server.js"); await serverHandle.initialize("file:///workspace", {}); }); afterEach(async () => { await serverHandle.shutdown(); }); // Tests... }); ``` -------------------------------- ### Volar.js Monorepo Setup and Build Source: https://github.com/luke-hagar-sp/volar.js/blob/master/README.md Commands to clone the Volar.js repository, install dependencies using pnpm, build all packages, and run tests. This is the initial setup for contributing to or using the monorepo. ```bash # Clone the repository git clone https://github.com/volarjs/volar.js.git cd volar.js # Install dependencies pnpm install # Build all packages pnpm run build # Run tests pnpm run test ``` -------------------------------- ### Verify Setup with Tests Source: https://github.com/luke-hagar-sp/volar.js/blob/master/docs/CONTRIBUTING.md Run all project tests to verify the development environment setup. ```bash pnpm run test ``` -------------------------------- ### Quick Start: Create Language and Language Service Source: https://github.com/luke-hagar-sp/volar.js/blob/master/README.md This snippet demonstrates the basic setup for creating a language instance and a language service using Volar.js core packages. It shows how to initialize with plugins and use the service for features like code completion. ```typescript import { createLanguage } from "@volar/language-core"; import { createLanguageService } from "@volar/language-service"; import { URI } from "vscode-uri"; // Create a language instance with plugins const language = createLanguage( [ /* your language plugins */ ], new Map(), (id) => { /* sync function */ } ); // Create a language service const languageService = createLanguageService( language, [ /* your service plugins */ ], { workspaceFolders: [URI.parse("file:///")] }, {} ); // Use the language service const completions = await languageService.getCompletionItems( URI.parse("file:///example.ts"), { line: 0, character: 10 } ); ``` -------------------------------- ### Create Language Instance Example Source: https://github.com/luke-hagar-sp/volar.js/blob/master/packages/language-core/README.md Example demonstrating how to create a Language instance using `createLanguage` and register a script. ```typescript import { createLanguage } from "@volar/language-core"; import { URI } from "vscode-uri"; const scriptRegistry = new Map>(); const language = createLanguage( [myLanguagePlugin], scriptRegistry, (uri, includeFsFiles, shouldRegister) => { // Load file from file system const content = fs.readFileSync(uri.fsPath, "utf-8"); const snapshot = createSnapshot(content); language.scripts.set(uri, snapshot, "typescript"); } ); ``` -------------------------------- ### Install Dependencies Source: https://github.com/luke-hagar-sp/volar.js/blob/master/docs/CONTRIBUTING.md Install all project dependencies using pnpm. ```bash pnpm install ``` -------------------------------- ### Install @volar/language-server Source: https://github.com/luke-hagar-sp/volar.js/blob/master/packages/language-server/README.md Install the language server package using npm. ```bash npm install @volar/language-server ``` -------------------------------- ### Install @volar/kit Source: https://github.com/luke-hagar-sp/volar.js/blob/master/packages/kit/README.md Install the @volar/kit package using npm. ```bash npm install @volar/kit ``` -------------------------------- ### Install @volar/language-core Source: https://github.com/luke-hagar-sp/volar.js/blob/master/packages/language-core/README.md Install the @volar/language-core package using npm. ```bash npm install @volar/language-core ``` -------------------------------- ### Install @volar/test-utils Source: https://github.com/luke-hagar-sp/volar.js/blob/master/packages/test-utils/README.md Install the test utilities package using npm. ```bash npm install @volar/test-utils ``` -------------------------------- ### Create and Use a Language Service Source: https://github.com/luke-hagar-sp/volar.js/blob/master/docs/llm/EXAMPLES.md Set up a complete Volar.js language service by creating a language instance and then a language service instance. This example demonstrates the basic structure for integrating custom plugins and using the service for operations like getting hover information and completions. ```typescript import { createLanguage } from "@volar/language-core"; import { createLanguageService } from "@volar/language-service"; import { URI } from "vscode-uri"; // Create script registry const scriptRegistry = new Map>(); // Create language instance const language = createLanguage( [myLanguagePlugin], scriptRegistry, (uri, includeFsFiles, shouldRegister) => { // Sync function - loads files from file system if (includeFsFiles && fs.existsSync(uri.fsPath)) { const content = fs.readFileSync(uri.fsPath, "utf-8"); const snapshot = createSnapshot(content); language.scripts.set(uri, snapshot); } } ); // Create language service const languageService = createLanguageService( language, [myServicePlugin], { workspaceFolders: [URI.parse("file:///")] }, {} ); // Use language service const hover = await languageService.getHover(uri, { line: 10, character: 5 }); const completions = await languageService.getCompletionItems(uri, { line: 10, character: 5 }); ``` -------------------------------- ### Install @volar/language-service Source: https://github.com/luke-hagar-sp/volar.js/blob/master/packages/language-service/README.md Install the @volar/language-service package using npm. ```bash npm install @volar/language-service ``` -------------------------------- ### Install @volar/jsdelivr Source: https://github.com/luke-hagar-sp/volar.js/blob/master/packages/jsdelivr/README.md Install the jsDelivr package using npm. ```bash npm install @volar/jsdelivr ``` -------------------------------- ### Basic VS Code Extension Setup Source: https://github.com/luke-hagar-sp/volar.js/blob/master/packages/vscode/README.md This snippet shows the fundamental setup for a VS Code extension that integrates with a language server. It initializes the language client and registers it with the extension context. ```typescript import * as vscode from "vscode"; import { LanguageClient, ServerOptions, TransportKind, } from "vscode-languageclient/node"; import { middleware, activateAutoInsertion } from "@volar/vscode"; export function activate(context: vscode.ExtensionContext) { // Server options const serverModule = context.asAbsolutePath("server.js"); const serverOptions: ServerOptions = { run: { module: serverModule, transport: TransportKind.ipc }, debug: { module: serverModule, transport: TransportKind.ipc }, }; // Client options const clientOptions = { documentSelector: [{ scheme: "file", language: "typescript" }], middleware, }; // Create client const client = new LanguageClient( "myLanguageServer", "My Language Server", serverOptions, clientOptions ); // Start client client.start(); // Activate features context.subscriptions.push( activateAutoInsertion(client, clientOptions.documentSelector) ); context.subscriptions.push(client); } ``` -------------------------------- ### getText Method Example Source: https://github.com/luke-hagar-sp/volar.js/blob/master/docs/guides/script-snapshot-guide.md Demonstrates how to retrieve portions of the script snapshot's content using a half-open interval [start, end). ```typescript const snapshot: IScriptSnapshot = { getText: (start, end) => content.substring(start, end), // ... }; // Get full content const full = snapshot.getText(0, snapshot.getLength()); // Get first 10 characters const first10 = snapshot.getText(0, 10); // Get characters 5-15 const middle = snapshot.getText(5, 15); ``` -------------------------------- ### Install @volar/eslint Source: https://github.com/luke-hagar-sp/volar.js/blob/master/packages/eslint/README.md Install the @volar/eslint package using npm. ```bash npm install @volar/eslint ``` -------------------------------- ### Basic Volar Language Server Setup Source: https://github.com/luke-hagar-sp/volar.js/blob/master/packages/language-server/README.md Sets up a basic Volar language server using `createServerBase` and `createSimpleProject`. This is suitable for non-TypeScript projects or simple setups. ```typescript import { createServerBase, createSimpleProject } from "@volar/language-server"; import { createConnection } from "vscode-languageserver/node"; import { URI } from "vscode-uri"; // Create LSP connection const connection = createConnection(); // Create server const server = createServerBase(connection, { // Environment configuration }); // Create project const project = createSimpleProject([ // Your language plugins ]); // Initialize connection.onInitialize((params) => { return server.initialize(params, project, [ // Your language service plugins ]); }); connection.onInitialized(() => { server.initialized(); }); // Listen connection.listen(); ``` -------------------------------- ### Start Language Server Source: https://github.com/luke-hagar-sp/volar.js/blob/master/packages/test-utils/README.md Starts a language server process. Provide the path to the server module and optionally the current working directory. ```typescript import { startLanguageServer } from "@volar/test-utils"; const serverHandle = startLanguageServer("./dist/server.js", process.cwd()); ``` -------------------------------- ### Install @volar/typescript Source: https://github.com/luke-hagar-sp/volar.js/blob/master/packages/typescript/README.md Install the @volar/typescript package using npm. ```bash npm install @volar/typescript ``` -------------------------------- ### TypeScript Code Example with Imports and Comments Source: https://github.com/luke-hagar-sp/volar.js/blob/master/docs/CONTRIBUTING_DOCS.md Demonstrates how to include necessary imports, use descriptive variable names, and add comments for clarity in TypeScript code examples. ```typescript import { createLanguage } from "@volar/language-core"; import { URI } from "vscode-uri"; // Use descriptive variable names const language = createLanguage(plugins, registry, sync); // Include comments for clarity const sourceScript = language.scripts.get(uri); // Get source script ``` -------------------------------- ### LanguageServicePlugin Example Source: https://github.com/luke-hagar-sp/volar.js/blob/master/docs/llm/TYPES.md A basic example of a LanguageServicePlugin that enables hover provider capabilities. ```typescript const plugin: LanguageServicePlugin = { capabilities: { hoverProvider: true }, create(context) { return { provide: { ... } }; } }; ``` -------------------------------- ### SourceScript Creation Example Source: https://github.com/luke-hagar-sp/volar.js/blob/master/docs/DATA_FLOW.md Demonstrates the creation of a SourceScript object from a file URI, snapshot, and language ID. ```typescript // File: example.vue const uri = URI.parse('file:///example.vue'); const snapshot = createSnapshot(fileContent); // Create SourceScript language.scripts.set(uri, snapshot, 'vue'); // SourceScript created: { id: uri, languageId: 'vue', snapshot: snapshot, generated: undefined } ``` -------------------------------- ### Start Language Server for Testing Source: https://github.com/luke-hagar-sp/volar.js/blob/master/docs/API.md Starts a language server process, typically used for testing purposes. Specify the server module path and optionally the current working directory. ```typescript function startLanguageServer( serverModule: string, cwd?: string | URL ): LanguageServerHandle; ``` -------------------------------- ### Basic VirtualCode Creation Source: https://github.com/luke-hagar-sp/volar.js/blob/master/docs/guides/virtualcode-complete-reference.md A fundamental example demonstrating the creation of a VirtualCode object, including snapshot and mapping generation. ```typescript createVirtualCode( uri: URI, languageId: string, snapshot: IScriptSnapshot, ctx: CodegenContext ): VirtualCode | undefined { // Step 1: Get source code const sourceCode = snapshot.getText(0, snapshot.getLength()); // Step 2: Transform to TypeScript const generatedCode = transformToTypeScript(sourceCode); // Step 3: Create snapshot const virtualSnapshot: IScriptSnapshot = { getText: (start, end) => generatedCode.substring(start, end), getLength: () => generatedCode.length, getChangeRange: () => undefined, }; // Step 4: Create mappings const mappings: CodeMapping[] = [ { sourceOffsets: [0], generatedOffsets: [0], lengths: [sourceCode.length], data: { verification: true, navigation: true, completion: true, semantic: true, structure: true, format: true, }, }, ]; // Step 5: Return VirtualCode return { id: 'main', languageId: 'typescript', snapshot: virtualSnapshot, mappings, }; } ``` -------------------------------- ### Complete Example: All Features Enabled/Disabled Source: https://github.com/luke-hagar-sp/volar.js/blob/master/docs/guides/mapping-system-guide.md Demonstrates a complete mapping configuration with various features enabled or disabled across different regions. ```typescript const mappings: CodeMapping[] = [ // Region 1: Full features { sourceOffsets: [0], generatedOffsets: [0], lengths: [100], data: { verification: true, // Diagnostics and code actions completion: true, // Code completion semantic: true, // Hover, semantic tokens navigation: true, // Go-to-definition, references structure: true, // Outline, folding format: true, // Formatting }, }, // Region 2: Read-only (no editing features) { sourceOffsets: [100], generatedOffsets: [100], lengths: [50], data: { verification: false, // No diagnostics completion: false, // No completion semantic: true, // Hover enabled navigation: true, // Navigation enabled structure: true, // Structure enabled format: false, // No formatting }, }, ]; ``` -------------------------------- ### Install Volar.js Individual Packages Source: https://github.com/luke-hagar-sp/volar.js/blob/master/README.md Instructions for installing specific Volar.js packages using npm. This is useful when you only need certain functionalities in your project. ```bash npm install @volar/language-core npm install @volar/language-service npm install @volar/language-server # ... etc ``` -------------------------------- ### Volar.js Completion Feature Example Source: https://github.com/luke-hagar-sp/volar.js/blob/master/docs/guides/integration-guide.md Example demonstrating how to implement the completion feature, including mapping source positions to virtual positions, retrieving completion items, and mapping completion ranges back to source. ```typescript provideCompletionItems(document, position, context, token) { const sourceScript = context.language.scripts.get(document.uri); const virtualCode = sourceScript.generated.root; const mapper = context.language.maps.get(virtualCode, sourceScript); const sourceOffset = document.offsetAt(position); const completions = []; // Map to virtual position and filter by completion for (const [virtualOffset, mapping] of mapper.toGeneratedLocation( sourceOffset, (data) => data.completion === true )) { // Get completions from virtual code const virtualDocument = getVirtualDocument(virtualCode); const virtualCompletions = getCompletionsFromTypeScript( virtualDocument, virtualOffset ); // Map completion ranges back to source for (const item of virtualCompletions.items) { if (item.textEdit) { for (const [sourceStart, sourceEnd] of mapper.toSourceRange( item.textEdit.range.start, item.textEdit.range.end, false, (data) => data.completion === true )) { completions.push({ ...item, textEdit: { ...item.textEdit, range: { start: document.positionAt(sourceStart), end: document.positionAt(sourceEnd), }, }, }); } } else { completions.push(item); } } } return { items: completions, isIncomplete: false }; } ``` -------------------------------- ### Install @volar/vscode Package Source: https://github.com/luke-hagar-sp/volar.js/blob/master/packages/vscode/README.md Install the @volar/vscode package using npm. This is the initial step to integrate Volar's language server capabilities into your VS Code extension. ```bash npm install @volar/vscode ``` -------------------------------- ### Complete Language Plugin Example Source: https://github.com/luke-hagar-sp/volar.js/blob/master/docs/examples/basic-language-plugin.md A comprehensive example of a Volar `LanguagePlugin` that identifies custom file types, transforms their content into TypeScript virtual code, and defines mappings for navigation and diagnostics. ```typescript import type { LanguagePlugin, VirtualCode, IScriptSnapshot, CodeMapping, } from "@volar/language-core"; import { URI } from "vscode-uri"; const myLanguagePlugin: LanguagePlugin = { getLanguageId(uri: URI): string | undefined { if (uri.fsPath.endsWith(".myext")) { return "my-lang"; } }, createVirtualCode( uri: URI, languageId: string, snapshot: IScriptSnapshot, ctx: CodegenContext ): VirtualCode | undefined { if (languageId !== "my-lang") return; const sourceCode = snapshot.getText(0, snapshot.getLength()); const generatedCode = `export function main() { ${sourceCode} }`; return { id: "main", languageId: "typescript", snapshot: { getText: (start, end) => generatedCode.substring(start, end), getLength: () => generatedCode.length, getChangeRange: () => undefined, }, mappings: [ { sourceOffsets: [0], generatedOffsets: [0], lengths: [sourceCode.length], data: { verification: true, navigation: true, completion: true, semantic: true, structure: true, format: true, }, }, ], }; }, }; ``` -------------------------------- ### Basic LanguageServicePlugin Example Source: https://github.com/luke-hagar-sp/volar.js/blob/master/docs/PLUGINS.md Demonstrates the basic structure of a LanguageServicePlugin, including capability declaration and providing hover and completion services. ```typescript import type { LanguageServicePlugin, LanguageServicePluginInstance, } from "@volar/language-service"; const myServicePlugin: LanguageServicePlugin = { name: "my-plugin", capabilities: { hoverProvider: true, completionProvider: { triggerCharacters: ["early."], }, }, create(context) { return { provide: { provideHover(document, position, token) { // Provide hover information return { contents: { kind: "markdown", value: "Hover information", }, }; }, provideCompletionItems(document, position, context, token) { // Provide completions return { isIncomplete: false, items: [ { label: "myCompletion", kind: 1, insertText: "myCompletion", }, ], }; }, }, }; }, }; ``` -------------------------------- ### Volar.js Hover Feature Example Source: https://github.com/luke-hagar-sp/volar.js/blob/master/docs/guides/integration-guide.md Step-by-step example of implementing the hover feature, including mapping source positions to virtual positions, retrieving hover information, and mapping results back to source ranges. ```typescript // 1. User hovers over symbol in file.vue const hover = await languageService.getHover( URI.file('file.vue'), { line: 10, character: 5 } ); // 2. LanguageServicePlugin receives request provideHover(document, position, token) { // 3. Get source script const sourceScript = context.language.scripts.get(document.uri); const virtualCode = sourceScript.generated.root; const mapper = context.language.maps.get(virtualCode, sourceScript); // 4. Map source position to virtual position const sourceOffset = document.offsetAt(position); for (const [virtualOffset, mapping] of mapper.toGeneratedLocation( sourceOffset, (data) => data.semantic === true // Filter by CodeInformation )) { // 5. Get hover info from virtual code const virtualDocument = getVirtualDocument(virtualCode); const hoverInfo = getHoverFromTypeScript(virtualDocument, virtualOffset); // 6. Map result range back to source if (hoverInfo.range) { for (const [sourceStart, sourceEnd] of mapper.toSourceRange( hoverInfo.range.start, hoverInfo.range.end, false, (data) => data.semantic === true )) { return { contents: hoverInfo.contents, range: { start: document.positionAt(sourceStart), end: document.positionAt(sourceEnd), }, }; } } return { contents: hoverInfo.contents }; } } ``` -------------------------------- ### dispose Method Example for Resource Cleanup Source: https://github.com/luke-hagar-sp/volar.js/blob/master/docs/guides/script-snapshot-guide.md Provides an example of implementing the optional dispose method to release resources held by the script snapshot, such as parser instances or event listeners. ```typescript const snapshot: IScriptSnapshot = { getText: (start, end) => content.substring(start, end), getLength: () => content.length, getChangeRange: () => undefined, dispose: () => { // Clean up resources parserCache.delete(fileId); eventListeners.forEach(listener => removeEventListener(listener)); }, }; ``` -------------------------------- ### Complete Custom Language Service Plugin Example Source: https://github.com/luke-hagar-sp/volar.js/blob/master/docs/examples/custom-language-service.md A comprehensive example of a Volar LanguageServicePlugin, integrating structure, capabilities, and feature providers for hover, completion, and diagnostics. Includes a helper function for word extraction. ```typescript import type { LanguageServicePlugin, LanguageServicePluginInstance, LanguageServiceContext, } from "@volar/language-service"; import type * as vscode from "vscode-languageserver-protocol"; const myServicePlugin: LanguageServicePlugin = { name: "my-language-service", capabilities: { hoverProvider: true, completionProvider: { triggerCharacters: [".", "("], }, diagnosticProvider: { interFileDependencies: false, workspaceDiagnostics: false, }, }, create(context: LanguageServiceContext): LanguageServicePluginInstance { return { provide: { provideHover(document, position, token) { const text = document.getText(); const word = getWordAtPosition(text, document.offsetAt(position)); if (word) { return { contents: { kind: "markdown", value: `**${word}**\n\nHover information for ${word}`, }, }; } }, provideCompletionItems(document, position, context, token) { const items: vscode.CompletionItem[] = [ { label: "myFunction", kind: 2, // Method insertText: "myFunction($1)", insertTextFormat: 2, // SnippetFormat documentation: "My custom function", }, ]; return { isIncomplete: false, items, }; }, provideDiagnostics(document, token) { const diagnostics: vscode.Diagnostic[] = []; const text = document.getText(); const lines = text.split("\n"); lines.forEach((line, index) => { if (line.includes("TODO")) { diagnostics.push({ range: { start: { line: index, character: 0 }, end: { line: index, character: line.length }, }, severity: 2, // Warning message: "TODO comment found", source: "my-plugin", }); } }); return diagnostics; }, }, }; }, }; function getWordAtPosition(text: string, offset: number): string | undefined { // Simple word extraction const start = text.lastIndexOf(" ", offset) + 1; const end = text.indexOf(" ", offset); if (end === -1) return text.substring(start); return text.substring(start, end); } ``` -------------------------------- ### VirtualCode Generation Example Source: https://github.com/luke-hagar-sp/volar.js/blob/master/docs/DATA_FLOW.md Illustrates the generation of a VirtualCode object from a SourceScript and its subsequent attachment. ```typescript // SourceScript for example.vue const sourceScript = language.scripts.get(uri); // LanguagePlugin creates VirtualCode const virtualCode = vuePlugin.createVirtualCode( uri, 'vue', sourceScript.snapshot, ctx ); // VirtualCode created: { id: 'script', languageId: 'typescript', snapshot: createSnapshot(generatedTypeScript), mappings: [ { sourceOffsets: [0, 100, 200], generatedOffsets: [0, 150, 300], lengths: [100, 100, 50], data: { verification: true, navigation: true } } ], embeddedCodes: [ { id: 'template', languageId: 'html', ... }, { id: 'style', languageId: 'css', ... } ] } // Attached to SourceScript sourceScript.generated = { root: virtualCode, languagePlugin: vuePlugin, embeddedCodes: new Map() }; ``` -------------------------------- ### Testing Multiple Documents Example Source: https://github.com/luke-hagar-sp/volar.js/blob/master/packages/test-utils/README.md Demonstrates handling multiple documents by opening two files and sending completion requests to each. ```typescript it("should handle multiple documents", async () => { await serverHandle.initialize("file:///workspace", {}); const doc1 = await serverHandle.openTextDocument("./file1.ts", "typescript"); const doc2 = await serverHandle.openTextDocument("./file2.ts", "typescript"); const completions1 = await serverHandle.sendCompletionRequest(doc1.uri, { line: 0, character: 0, }); const completions2 = await serverHandle.sendCompletionRequest(doc2.uri, { line: 0, character: 0, }); expect(completions1).toBeDefined(); expect(completions2).toBeDefined(); }); ``` -------------------------------- ### Interface Documentation Structure Source: https://github.com/luke-hagar-sp/volar.js/blob/master/docs/CONTRIBUTING_DOCS.md Outlines the structure for documenting interfaces, including a description, properties, and an example. ```markdown ### InterfaceName Description of the interface. **Properties:** - `property1: Type` - Description - `property2?: Type` - Description of optional property **Example:** ```typescript const obj: InterfaceName = { property1: value1 }; ``` ``` -------------------------------- ### Overlapping Mappings with Fallback Source: https://github.com/luke-hagar-sp/volar.js/blob/master/packages/source-map/README.md Demonstrates how to handle overlapping mappings using `fallbackToAnyMatch`. The first example shows strict matching where start and end must map to the same source range. The second example shows flexible matching where start and end can come from different mappings. ```typescript // Without fallback (strict matching) for (const [start, end] of sourceMap.toSourceRange(100, 200, false)) { // Both start and end must map to same source range } ``` ```typescript // With fallback (flexible matching) for (const [start, end] of sourceMap.toSourceRange(100, 200, true)) { // Start and end can come from different mappings } ``` -------------------------------- ### getLength Method Example Source: https://github.com/luke-hagar-sp/volar.js/blob/master/docs/guides/script-snapshot-guide.md Shows how to get the total character length of the script snapshot's content. This operation should ideally be O(1). ```typescript const snapshot: IScriptSnapshot = { getLength: () => content.length, // ... }; const length = snapshot.getLength(); ``` -------------------------------- ### Build Individual Package Source: https://github.com/luke-hagar-sp/volar.js/blob/master/docs/CONTRIBUTING.md Navigate to a specific package directory and build it. ```bash cd packages/language-core pnpm run build ``` -------------------------------- ### Get Inlay Hints Source: https://github.com/luke-hagar-sp/volar.js/blob/master/packages/language-service/README.md Provides inlay hints, such as type annotations and parameter names. Requires the `inlayHintProvider` capability. ```typescript getInlayHints( uri: URI, range: Range, token?: CancellationToken ): Promise ``` -------------------------------- ### Step 1: Get Source Script in Volar.js Source: https://github.com/luke-hagar-sp/volar.js/blob/master/docs/guides/integration-guide.md Demonstrates how to retrieve a source script using its URI in Volar.js. ```typescript // User opens file.vue const uri = URI.file('/path/to/file.vue'); // Language system requests script const sourceScript = language.scripts.get(uri); ``` -------------------------------- ### Creating a Basic LSP Server Source: https://github.com/luke-hagar-sp/volar.js/blob/master/docs/llm/EXAMPLES.md Illustrates the setup for creating a language server using Volar.js, including project creation and connection handling. ```typescript import { createServerBase, createSimpleProject } from "@volar/language-server"; import { createConnection } from "vscode-languageserver/node"; const connection = createConnection(); const server = createServerBase(connection, {}); const project = createSimpleProject([myLanguagePlugin]); connection.onInitialize((params) => { return server.initialize(params, project, [myServicePlugin]); }); connection.onInitialized(() => { server.initialized(); }); connection.listen(); ``` -------------------------------- ### server.initialize Source: https://github.com/luke-hagar-sp/volar.js/blob/master/packages/language-server/README.md Initializes the language server with provided parameters, project, and plugins. ```APIDOC ## server.initialize ### Description Initializes the language server with LSP initialize parameters, a project instance, and an array of language service plugins. This method prepares the server for operation. ### Signature ```typescript server.initialize( params: InitializeParams, project: LanguageServerProject, languageServicePlugins: LanguageServicePlugin[] ): InitializeResult; ``` ### Parameters - **params** (InitializeParams) - The LSP initialize parameters received from the client. - **project** (LanguageServerProject) - The project instance (TypeScript or Simple) to be used by the server. - **languageServicePlugins** (Array) - An array of language service plugins to extend server capabilities. ### Returns - InitializeResult - The result of the initialization, containing capabilities of the language server. ### Example ```typescript connection.onInitialize((params) => { return server.initialize(params, project, [myServicePlugin]); }); connection.onInitialized(() => { server.initialized(); }); ``` ``` -------------------------------- ### Example Vitest Test Structure Source: https://github.com/luke-hagar-sp/volar.js/blob/master/docs/CONTRIBUTING.md Illustrates a basic test structure using Vitest, including describe, it, and expect for assertions. ```typescript import { describe, it, expect } from "vitest"; describe("MyFunction", () => { it("should handle normal case", () => { const result = myFunction(input); expect(result).toBe(expected); }); it("should handle edge case", () => { const result = myFunction(edgeCaseInput); expect(result).toBe(expected); }); }); ``` -------------------------------- ### Step 2: Create VirtualCode with LanguagePlugin Source: https://github.com/luke-hagar-sp/volar.js/blob/master/docs/guides/integration-guide.md Shows how a LanguagePlugin creates VirtualCode from a source file snapshot and context. ```typescript // LanguagePlugin.createVirtualCode() is called const virtualCode = vuePlugin.createVirtualCode( uri, 'vue', snapshot, ctx ); // Returns VirtualCode return { id: 'root', languageId: 'typescript', snapshot: scriptSnapshot, mappings: [/* mappings */], embeddedCodes: [/* template, style */], }; ``` -------------------------------- ### Instantiate a Language Service Source: https://github.com/luke-hagar-sp/volar.js/blob/master/docs/examples/custom-language-service.md Shows how to create a basic language service instance. Ensure you have the necessary language and plugin definitions before use. ```typescript import { createLanguageService } from "@volar/language-service"; const languageService = createLanguageService( language, [myServicePlugin], { workspaceFolders: [URI.parse("file:///")], }, {} ); // Use the service const hover = await languageService.getHover(uri, position); const completions = await languageService.getCompletionItems(uri, position); const diagnostics = await languageService.getDiagnostics(uri); ``` -------------------------------- ### Get Rename Range Source: https://github.com/luke-hagar-sp/volar.js/blob/master/packages/language-service/README.md Gets the range that can be renamed at a specific position. Requires the `renameProvider.prepareProvider` capability. ```typescript getRenameRange( uri: URI, position: Position, token?: CancellationToken ): Promise ``` -------------------------------- ### startLanguageServer Source: https://github.com/luke-hagar-sp/volar.js/blob/master/packages/test-utils/README.md Starts a language server process and returns a handle for interaction. This is the entry point for setting up a test environment for a language server. ```APIDOC ## startLanguageServer ### Description Starts a language server process and returns a handle for interaction. ### Signature ```typescript function startLanguageServer( serverModule: string, cwd?: string | URL ): LanguageServerHandle; ``` ### Parameters #### Path Parameters - **serverModule** (string) - Required - Path to server module file - **cwd** (string | URL) - Optional - Current working directory ### Returns Server handle with methods for interaction ``` -------------------------------- ### Get Position Mapper Source: https://github.com/luke-hagar-sp/volar.js/blob/master/docs/llm/API_REFERENCE.md Gets a mapper for translating positions between virtual code and a source script. ```typescript get(virtualCode: VirtualCode, sourceScript: SourceScript): Mapper ``` -------------------------------- ### LanguagePlugin Example Source: https://github.com/luke-hagar-sp/volar.js/blob/master/docs/llm/TYPES.md An example of a LanguagePlugin implementation that identifies Vue files and creates a basic virtual code structure. ```typescript const plugin: LanguagePlugin = { getLanguageId(uri) { return uri.fsPath.endsWith('.vue') ? 'vue' : undefined; }, createVirtualCode(uri, languageId, snapshot, ctx) { // Transform source to virtual code return { id: 'main', languageId: 'typescript', snapshot, mappings: [] }; } }; ``` -------------------------------- ### Create Language Service Instance Source: https://github.com/luke-hagar-sp/volar.js/blob/master/packages/language-service/README.md Demonstrates how to create a language service instance using `createLanguageService` from @volar/language-service, along with necessary dependencies from @volar/language-core. ```typescript import { createLanguageService } from "@volar/language-service"; import { createLanguage } from "@volar/language-core"; import { URI } from "vscode-uri"; const language = createLanguage(plugins, registry, sync); const languageService = createLanguageService( language, [myServicePlugin], { workspaceFolders: [URI.parse("file:///")], }, {} ); ``` -------------------------------- ### Create Base Server Instance Source: https://github.com/luke-hagar-sp/volar.js/blob/master/packages/language-server/README.md Creates a base LSP server instance using the provided connection and environment configuration. This is a foundational step for setting up the language server. ```typescript import { createServerBase } from "@volar/language-server"; import { createConnection } from "vscode-languageserver/node"; const connection = createConnection(); const server = createServerBase(connection, { // Environment configuration }); ``` -------------------------------- ### Setup Volar Worker with Basic Language Service Source: https://github.com/luke-hagar-sp/volar.js/blob/master/packages/monaco/README.md Initializes a basic worker language service for Volar.js in Monaco Editor. This is a foundational setup for custom language support. ```typescript // my-lang.worker.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, env, languagePlugins: [ // ... ], languageServicePlugins: [ // ... ], }); }); }; ``` -------------------------------- ### Offset System: Half-Open Intervals Source: https://github.com/luke-hagar-sp/volar.js/blob/master/docs/guides/mapping-system-guide.md Explains the zero-based, half-open interval [start, end) system used for offsets in the mapping system. The start is inclusive, and the end is exclusive. ```typescript // Source code: "Hello World" // Offset 0 = 'H' // Offset 5 = ' ' // Offset 11 = end of string // Mapping "Hello" (offsets 0-5) { sourceOffsets: [0], generatedOffsets: [0], lengths: [5], // Length is 5, covers [0-5) data: { /* ... */ } } ``` -------------------------------- ### Best Practice: Always Initialize Server Source: https://github.com/luke-hagar-sp/volar.js/blob/master/packages/test-utils/README.md Demonstrates the best practice of calling `initialize()` before making any requests to the language server. This ensures the server is ready to process requests. ```typescript await serverHandle.initialize("file:///workspace", {}); // Now safe to make requests ``` -------------------------------- ### Using Dependency Injection Source: https://github.com/luke-hagar-sp/volar.js/blob/master/packages/language-service/README.md Illustrates how plugins can inject dependencies from other services using the `context.inject` method. ```APIDOC ### Using Dependency Injection Plugins can inject dependencies to other plugins: ```typescript const myPlugin: LanguageServicePlugin = { name: "my-plugin", capabilities: { /* ... */ }, create(context) { // Inject a dependency const otherService = context.inject("myService", arg1, arg2); return { provide: { // Use the injected service provideHover(document, position, token) { return otherService?.getHover(document, position); }, }, }; }, }; ``` ``` -------------------------------- ### Create jsDelivr File System Source: https://github.com/luke-hagar-sp/volar.js/blob/master/packages/jsdelivr/README.md Create a file system that fetches NPM packages from jsDelivr CDN. This example shows basic configuration with custom path and version resolution, and a fetch callback. ```typescript import { createNpmFileSystem } from "@volar/jsdelivr"; import { URI } from "vscode-uri"; const fs = createNpmFileSystem( (uri) => { // Convert URI to CDN path if (uri.path.startsWith("/node_modules/")) { return uri.path.slice("/node_modules/".length); } }, (pkgName) => { // Get package version (e.g., from package.json) return "latest"; }, (path, content) => { console.log(`Fetched ${path}`); } ); ``` -------------------------------- ### createNpmFileSystem Source: https://github.com/luke-hagar-sp/volar.js/blob/master/docs/API.md Creates a file system that fetches NPM packages from the jsDelivr CDN. ```APIDOC ## createNpmFileSystem ### Description Creates a file system that fetches NPM packages from jsDelivr CDN. ### Parameters - `getCdnPath` (function) - Optional. A function to get the CDN path for a URI. - `getPackageVersion` (function) - Optional. A function to get the version of a package. - `onFetch` (function) - Optional. A callback function executed when a file is fetched. ``` -------------------------------- ### Basic Volar.js Setup with jsDelivr File System Source: https://github.com/luke-hagar-sp/volar.js/blob/master/packages/jsdelivr/README.md Integrate the jsDelivr file system into the Volar.js language service for browser-based development. ```typescript import { createNpmFileSystem } from "@volar/jsdelivr"; import { createLanguageService } from "@volar/language-service"; import { URI } from "vscode-uri"; const fs = createNpmFileSystem(); const languageService = createLanguageService( language, plugins, { workspaceFolders: [URI.parse("file:///")], fs, // Use jsDelivr file system }, {} ); ``` -------------------------------- ### Get Document Links Source: https://github.com/luke-hagar-sp/volar.js/blob/master/packages/language-service/README.md Provides document links. Requires the `documentLinkProvider` capability. ```typescript getDocumentLinks( uri: URI, token?: CancellationToken ): Promise ``` -------------------------------- ### Language.maps.get Source: https://github.com/luke-hagar-sp/volar.js/blob/master/docs/llm/API_REFERENCE.md Gets a mapper for translating positions between virtual code and a source script. ```APIDOC ## Language.maps.get ### Description Gets a mapper for translating positions between virtual code and source script. ### Parameters - **virtualCode** (VirtualCode) - Required - The virtual code. - **sourceScript** (SourceScript) - Required - The source script. ### Returns - `Mapper` - The mapper instance. ``` -------------------------------- ### Registering Language Plugins Source: https://github.com/luke-hagar-sp/volar.js/blob/master/docs/PLUGINS.md Demonstrates how to register multiple LanguagePlugins when creating a language core instance. Plugins are tried in order, and the first one to return a result wins. ```typescript import { createLanguage } from "@volar/language-core"; const language = createLanguage( [myLanguagePlugin, anotherLanguagePlugin], // Plugins array scriptRegistry, syncFunction ); ``` -------------------------------- ### Multi-File Plugin with Embedded Codes Example Source: https://github.com/luke-hagar-sp/volar.js/blob/master/docs/guides/language-plugin-complete-guide.md This example shows a multi-file plugin capable of extracting and managing different code sections (script, template, style) from a single source file, each as a separate virtual code block. Use this pattern when a file contains distinct, independently processable code segments. ```typescript const multiFilePlugin: LanguagePlugin = { createVirtualCode(uri, languageId, snapshot, ctx) { const source = snapshot.getText(0, snapshot.getLength()); // Extract different parts const script = extractScript(source); const template = extractTemplate(source); const style = extractStyle(source); return { id: 'root', languageId: 'typescript', snapshot: createSnapshot(script), mappings: createScriptMappings(source, script), embeddedCodes: [ { id: 'template', languageId: 'html', snapshot: createSnapshot(template), mappings: createTemplateMappings(source, template), }, { id: 'style', languageId: 'css', snapshot: createSnapshot(style), mappings: createStyleMappings(source, style), }, ], }; }, }; ``` -------------------------------- ### Create Simple Project Source: https://github.com/luke-hagar-sp/volar.js/blob/master/docs/llm/API_REFERENCE.md Creates a simple project instance without TypeScript integration, using only the provided language plugins. ```typescript function createSimpleProject( languagePlugins: LanguagePlugin[] ): LanguageServerProject; ``` -------------------------------- ### Get Moniker Information Source: https://github.com/luke-hagar-sp/volar.js/blob/master/packages/language-service/README.md Provides moniker information for symbols. Requires the `monikerProvider` capability. ```typescript getMoniker( uri: URI, position: Position, token?: CancellationToken ): Promise ``` -------------------------------- ### Build All Packages Source: https://github.com/luke-hagar-sp/volar.js/blob/master/docs/CONTRIBUTING.md Build all packages within the Volar.js monorepo. ```bash pnpm run build ``` -------------------------------- ### createServerBase Source: https://github.com/luke-hagar-sp/volar.js/blob/master/docs/llm/API_REFERENCE.md Creates a base instance for a language server, requiring a connection and environment configuration. ```APIDOC ## createServerBase ### Description Creates a base server instance. ### Parameters - **connection** (Connection) - Required - The server connection. - **env** (LanguageServerEnvironment) - Required - The environment configuration. ### Returns - `LanguageServerBase` instance ``` -------------------------------- ### Monaco Editor Worker Setup Source: https://github.com/luke-hagar-sp/volar.js/blob/master/docs/llm/EXAMPLES.md Configures the worker script for Monaco Editor integration with Volar.js. ```typescript // worker.ts import { createSimpleWorkerLanguageService } from "@volar/monaco/worker"; import { URI } from "vscode-uri"; self.onmessage = () => { worker.initialize((ctx) => { return createSimpleWorkerLanguageService({ workerContext: ctx, env: { workspaceFolders: [URI.parse("file:///")] }, languagePlugins: [myLanguagePlugin], languageServicePlugins: [myServicePlugin], }); }); }; ``` -------------------------------- ### Initialize Server Source: https://github.com/luke-hagar-sp/volar.js/blob/master/packages/language-server/README.md Initializes the language server with LSP parameters, a project instance, and language service plugins. Also includes the handler for the 'initialized' notification. ```typescript connection.onInitialize((params) => { return server.initialize(params, project, [myServicePlugin]); }); connection.onInitialized(() => { server.initialized(); }); ``` -------------------------------- ### Get Call Hierarchy Items Source: https://github.com/luke-hagar-sp/volar.js/blob/master/packages/language-service/README.md Provides call hierarchy items. Requires the `callHierarchyProvider` capability. ```typescript getCallHierarchyItems( uri: URI, position: Position, token?: CancellationToken ): Promise ``` -------------------------------- ### Create Simple Project Source: https://github.com/luke-hagar-sp/volar.js/blob/master/packages/language-server/README.md Initializes a simple project manager for projects without a TypeScript configuration. It requires an array of language plugins. ```typescript import { createSimpleProject } from "@volar/language-server"; const project = createSimpleProject([ // Your language plugins ]); ``` -------------------------------- ### Get Document Colors Source: https://github.com/luke-hagar-sp/volar.js/blob/master/packages/language-service/README.md Provides color information within a document. Requires the `colorProvider` capability. ```typescript getDocumentColors( uri: URI, token?: CancellationToken ): Promise ``` -------------------------------- ### Get Selection Ranges Source: https://github.com/luke-hagar-sp/volar.js/blob/master/packages/language-service/README.md Provides selection ranges for smart selection. Requires the `selectionRangeProvider` capability. ```typescript getSelectionRanges( uri: URI, positions: Position[], token?: CancellationToken ): Promise ``` -------------------------------- ### Get Folding Ranges Source: https://github.com/luke-hagar-sp/volar.js/blob/master/packages/language-service/README.md Provides folding ranges for a given URI. Requires the `foldingRangeProvider` capability. ```typescript getFoldingRanges( uri: URI, token?: CancellationToken ): Promise ``` -------------------------------- ### Basic ESLint Setup with Volar Processor Source: https://github.com/luke-hagar-sp/volar.js/blob/master/packages/eslint/README.md Set up ESLint with a Volar processor for .vue and .svelte files, enabling linting of virtual code. ```typescript import { createProcessor } from "@volar/eslint"; import { ESLint } from "eslint"; import { myLanguagePlugin } from "./my-plugin"; const processor = createProcessor([myLanguagePlugin], false); const eslint = new ESLint({ useEslintrc: true, processor: { ".vue": processor, ".svelte": processor, }, }); // Lint files const results = await eslint.lintFiles(["**/*.vue"]); ``` -------------------------------- ### Get File Rename Edits Source: https://github.com/luke-hagar-sp/volar.js/blob/master/packages/language-service/README.md Provides edits for renaming a file. Requires the `fileRenameEditsProvider` capability. ```typescript getFileRenameEdits( oldUri: URI, newUri: URI, token?: CancellationToken ): Promise ``` -------------------------------- ### Using the Plugin with createLanguage Source: https://github.com/luke-hagar-sp/volar.js/blob/master/docs/examples/basic-language-plugin.md Demonstrates how to integrate the custom `LanguagePlugin` into Volar's core language system. It shows the setup of a script registry and the creation of a language instance. ```typescript import { createLanguage } from "@volar/language-core"; const scriptRegistry = new Map>(); const language = createLanguage([myLanguagePlugin], scriptRegistry, (uri) => { // Sync function - load file content const content = fs.readFileSync(uri.fsPath, "utf-8"); const snapshot = createSnapshot(content); language.scripts.set(uri, snapshot, "my-lang"); }); ``` -------------------------------- ### Get Workspace Diagnostics Source: https://github.com/luke-hagar-sp/volar.js/blob/master/packages/language-service/README.md Provides diagnostics for all documents within the workspace. Requires the `diagnosticProvider.workspaceDiagnostics` capability. ```typescript getWorkspaceDiagnostics( token?: CancellationToken ): Promise ``` -------------------------------- ### External Link Conventions Source: https://github.com/luke-hagar-sp/volar.js/blob/master/docs/CONTRIBUTING_DOCS.md Demonstrates how to format external links with descriptive text and full URLs. ```markdown [Language Server Protocol](https://microsoft.github.io/language-server-protocol/) ``` -------------------------------- ### Creating an IScriptSnapshot Instance Source: https://github.com/luke-hagar-sp/volar.js/blob/master/docs/guides/virtualcode-complete-reference.md Demonstrates how to create an instance of IScriptSnapshot by providing implementations for its methods. This example shows a basic implementation for a generated code string. ```typescript const generatedCode = 'export function main() { return 42; }'; const snapshot: IScriptSnapshot = { getText: (start, end) => generatedCode.substring(start, end), getLength: () => generatedCode.length, getChangeRange: (oldSnapshot) => { // Calculate change range for incremental updates // Return undefined if not available return undefined; }, dispose: () => { // Clean up resources if needed }, }; ``` -------------------------------- ### Get Workspace Symbols Source: https://github.com/luke-hagar-sp/volar.js/blob/master/packages/language-service/README.md Searches for symbols across the entire workspace. Requires the `workspaceSymbolProvider` capability. ```typescript getWorkspaceSymbols( query: string, token?: CancellationToken ): Promise ``` -------------------------------- ### Get Document Diagnostics Source: https://github.com/luke-hagar-sp/volar.js/blob/master/docs/llm/API_REFERENCE.md Provides diagnostics for a given document URI. Supports cancellation tokens. ```typescript getDiagnostics( uri: URI, token?: CancellationToken ): Promise ``` -------------------------------- ### Mock Configuration Initialization Source: https://github.com/luke-hagar-sp/volar.js/blob/master/packages/test-utils/README.md Initializes the language server handle with specific configuration options, including the TypeScript SDK path. This is crucial for testing features that depend on external tools or configurations. ```typescript // Set configuration in initialization options await serverHandle.initialize("file:///workspace", { typescript: { tsdk: "/path/to/typescript", }, }); ```