@tsrx/language-server 0.6.3 → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -2064,8 +2064,6 @@ function extract_regions(code, regex, tag_name_length, id_prefix) {
|
|
|
2064
2064
|
const require$2 = (0, module$1.createRequire)(require("url").pathToFileURL(__filename).href);
|
|
2065
2065
|
const root_dirname = path.default.dirname((0, url.fileURLToPath)(require("url").pathToFileURL(__filename).href));
|
|
2066
2066
|
const { log: log$9, logWarning, logError: logError$4 } = createLogging("[TSRX Language]");
|
|
2067
|
-
/** @type {Set<string>} */
|
|
2068
|
-
const loggedCompilationFailures = /* @__PURE__ */ new Set();
|
|
2069
2067
|
const TSRX_EXTENSIONS$1 = [".tsrx"];
|
|
2070
2068
|
/**
|
|
2071
2069
|
* `[package name, package directory parts, supported extensions, package hints, entry candidates?]`.
|
|
@@ -2397,6 +2395,12 @@ var TSRXVirtualCode = class {
|
|
|
2397
2395
|
originalCode = "";
|
|
2398
2396
|
/** @type {AST.Program | null} */
|
|
2399
2397
|
sourceAst = null;
|
|
2398
|
+
/**
|
|
2399
|
+
* The `<script>` bodies of code (not data blocks) the transform appends to the
|
|
2400
|
+
* generated TSX as blocks; empty while the file has a fatal compile error.
|
|
2401
|
+
* @type {EmbeddedRegion[]}
|
|
2402
|
+
*/
|
|
2403
|
+
scriptRegions = [];
|
|
2400
2404
|
/** @type {boolean} */
|
|
2401
2405
|
isDotCompletionMode = false;
|
|
2402
2406
|
/** @type {unknown[]} */
|
|
@@ -2439,6 +2443,7 @@ var TSRXVirtualCode = class {
|
|
|
2439
2443
|
this.fatalErrors = [];
|
|
2440
2444
|
this.usageErrors = [];
|
|
2441
2445
|
this.sourceAst = null;
|
|
2446
|
+
this.scriptRegions = [];
|
|
2442
2447
|
this.isDotCompletionMode = false;
|
|
2443
2448
|
let isDotTyped = false;
|
|
2444
2449
|
let dotPosition = -1;
|
|
@@ -2497,7 +2502,6 @@ var TSRXVirtualCode = class {
|
|
|
2497
2502
|
}
|
|
2498
2503
|
if (result.fatalError) {
|
|
2499
2504
|
logError$4("TSRX compilation failed for", this.fileName, ":", result.fatalError);
|
|
2500
|
-
if (process.env.TSRX_TSC === "true") logTSRXErrors(this.fileName, [result.fatalError]);
|
|
2501
2505
|
this.fatalErrors.push(result.fatalError);
|
|
2502
2506
|
files_with_fatal_compile_error.add(normalize_file_name_key(this.fileName));
|
|
2503
2507
|
} else {
|
|
@@ -2506,11 +2510,11 @@ var TSRXVirtualCode = class {
|
|
|
2506
2510
|
}
|
|
2507
2511
|
this.originalCode = newCode;
|
|
2508
2512
|
if (!result.fatalError && result.text) {
|
|
2509
|
-
this.generatedCode = result.text;
|
|
2513
|
+
this.generatedCode = hashbang_as_comment(result.text);
|
|
2510
2514
|
this.mappings = result.mappings;
|
|
2511
2515
|
this.usageErrors = result.errors;
|
|
2512
2516
|
this.sourceAst = result.sourceAst;
|
|
2513
|
-
|
|
2517
|
+
this.scriptRegions = result.scriptRegions;
|
|
2514
2518
|
if (result.cssRegions.length > 0) log$9("Creating", result.cssRegions.length, "CSS embedded codes");
|
|
2515
2519
|
this.embeddedCodes = result.cssRegions.map((region) => create_embedded_code_from_region(region, "css"));
|
|
2516
2520
|
if (DEBUG) {
|
|
@@ -2529,7 +2533,7 @@ var TSRXVirtualCode = class {
|
|
|
2529
2533
|
}
|
|
2530
2534
|
} else {
|
|
2531
2535
|
log$9("Compilation failed, only display where the compilation error occurred.");
|
|
2532
|
-
this.generatedCode = newCode;
|
|
2536
|
+
this.generatedCode = hashbang_as_comment(newCode);
|
|
2533
2537
|
this.mappings = [{
|
|
2534
2538
|
sourceOffsets: [0],
|
|
2535
2539
|
generatedOffsets: [0],
|
|
@@ -2628,6 +2632,19 @@ var TSRXVirtualCode = class {
|
|
|
2628
2632
|
}
|
|
2629
2633
|
};
|
|
2630
2634
|
/**
|
|
2635
|
+
* Volar puts the generated code after blank lines as long as the source in the
|
|
2636
|
+
* file TypeScript reads (in tsserver and `tsrx-tsc`), so a `#!` line there is no
|
|
2637
|
+
* longer at the start of the file and TypeScript reads it as code: two
|
|
2638
|
+
* expression statements without `;`. They count when TypeScript infers the
|
|
2639
|
+
* semicolon style of an edit, so an import added to a file whose own statements
|
|
2640
|
+
* have no `;` lost its `;`. A line comment of the same length keeps every offset.
|
|
2641
|
+
* @param {string} code
|
|
2642
|
+
* @returns {string}
|
|
2643
|
+
*/
|
|
2644
|
+
function hashbang_as_comment(code) {
|
|
2645
|
+
return code.startsWith("#!") ? `//${code.slice(2)}` : code;
|
|
2646
|
+
}
|
|
2647
|
+
/**
|
|
2631
2648
|
* Clamp an intra-token offset into `[0, length]`.
|
|
2632
2649
|
* @param {number} offset
|
|
2633
2650
|
* @param {number} length
|
|
@@ -2637,22 +2654,6 @@ function clamp_offset(offset, length) {
|
|
|
2637
2654
|
return Math.min(Math.max(offset, 0), length);
|
|
2638
2655
|
}
|
|
2639
2656
|
/**
|
|
2640
|
-
* @param {string} file_name
|
|
2641
|
-
* @param {ReadonlyArray<unknown>} errors
|
|
2642
|
-
*/
|
|
2643
|
-
function logTSRXErrors(file_name, errors) {
|
|
2644
|
-
for (const error of errors) {
|
|
2645
|
-
const message = error && typeof error === "object" && "message" in error ? String(
|
|
2646
|
-
/** @type {{ message: unknown }} */
|
|
2647
|
-
error.message
|
|
2648
|
-
) : String(error);
|
|
2649
|
-
const key = `${file_name}\0${message}`;
|
|
2650
|
-
if (loggedCompilationFailures.has(key)) continue;
|
|
2651
|
-
loggedCompilationFailures.add(key);
|
|
2652
|
-
console.error(`[tsrx-tsc] ${file_name}: ${message}`);
|
|
2653
|
-
}
|
|
2654
|
-
}
|
|
2655
|
-
/**
|
|
2656
2657
|
* Build an embedded virtual code from a `<style>` / `<script>` region produced
|
|
2657
2658
|
* by the transform. The embedded document text is the region's content;
|
|
2658
2659
|
* `languageId` selects which Volar service handles it (`css` or `typescript`).
|
|
@@ -3051,7 +3052,6 @@ function invalidateCompilerResolutionCaches() {
|
|
|
3051
3052
|
path2TsrxCompilerPathMap.clear();
|
|
3052
3053
|
pathToPackageManifestCache.clear();
|
|
3053
3054
|
reset_consumer_compiler_resolution_caches();
|
|
3054
|
-
loggedCompilationFailures.clear();
|
|
3055
3055
|
}
|
|
3056
3056
|
/**
|
|
3057
3057
|
* Drop cached definition-file content and matches. A path invalidates only one
|
|
@@ -6418,7 +6418,7 @@ var main_exports$1 = /* @__PURE__ */ __exportAll({
|
|
|
6418
6418
|
TextDocumentIdentifier: () => TextDocumentIdentifier,
|
|
6419
6419
|
TextDocumentItem: () => TextDocumentItem,
|
|
6420
6420
|
TextEdit: () => TextEdit,
|
|
6421
|
-
URI: () => URI$
|
|
6421
|
+
URI: () => URI$5,
|
|
6422
6422
|
VersionedTextDocumentIdentifier: () => VersionedTextDocumentIdentifier,
|
|
6423
6423
|
WorkspaceChange: () => WorkspaceChange,
|
|
6424
6424
|
WorkspaceEdit: () => WorkspaceEdit,
|
|
@@ -6427,7 +6427,7 @@ var main_exports$1 = /* @__PURE__ */ __exportAll({
|
|
|
6427
6427
|
integer: () => integer,
|
|
6428
6428
|
uinteger: () => uinteger
|
|
6429
6429
|
});
|
|
6430
|
-
var DocumentUri, URI$
|
|
6430
|
+
var DocumentUri, URI$5, integer, uinteger, Position, Range, Location, LocationLink, Color, ColorInformation, ColorPresentation, FoldingRangeKind, FoldingRange, DiagnosticRelatedInformation, DiagnosticSeverity$1, DiagnosticTag, CodeDescription, Diagnostic, Command, TextEdit, ChangeAnnotation, ChangeAnnotationIdentifier, AnnotatedTextEdit, TextDocumentEdit, CreateFile, RenameFile, DeleteFile, WorkspaceEdit, TextEditChangeImpl, SnippetTextEdit, ChangeAnnotations, WorkspaceChange, TextDocumentIdentifier, VersionedTextDocumentIdentifier, OptionalVersionedTextDocumentIdentifier, LanguageKind, TextDocumentItem, MarkupKind, MarkupContent, CompletionItemKind$1, InsertTextFormat$1, CompletionItemTag, InsertReplaceEdit, InsertTextMode, ApplyKind, CompletionItemLabelDetails, CompletionItem, CompletionList, MarkedString, Hover, ParameterInformation, SignatureInformation, DocumentHighlightKind, DocumentHighlight, SymbolKind$1, SymbolTag, SymbolInformation, WorkspaceSymbol, DocumentSymbol, CodeActionKind, CodeActionTriggerKind, CodeActionContext, CodeActionTag, CodeAction, CodeLens, FormattingOptions, DocumentLink, SelectionRange, SemanticTokenTypes, SemanticTokenModifiers, SemanticTokens, InlineValueText, InlineValueVariableLookup, InlineValueEvaluatableExpression, InlineValueContext, InlayHintKind, InlayHintLabelPart, InlayHint, StringValue, InlineCompletionItem, InlineCompletionList, InlineCompletionTriggerKind, SelectedCompletionInfo, InlineCompletionContext, WorkspaceFolder, EOL, TextDocument$1, FullTextDocument$1, Is;
|
|
6431
6431
|
var init_main$1 = __esmMin((() => {
|
|
6432
6432
|
;
|
|
6433
6433
|
(function(DocumentUri) {
|
|
@@ -6442,7 +6442,7 @@ var init_main$1 = __esmMin((() => {
|
|
|
6442
6442
|
return typeof value === "string";
|
|
6443
6443
|
}
|
|
6444
6444
|
URI.is = is;
|
|
6445
|
-
})(URI$
|
|
6445
|
+
})(URI$5 || (URI$5 = {}));
|
|
6446
6446
|
;
|
|
6447
6447
|
(function(integer) {
|
|
6448
6448
|
integer.MIN_VALUE = -2147483648;
|
|
@@ -8277,7 +8277,7 @@ var init_main$1 = __esmMin((() => {
|
|
|
8277
8277
|
(function(WorkspaceFolder) {
|
|
8278
8278
|
function is(value) {
|
|
8279
8279
|
const candidate = value;
|
|
8280
|
-
return Is.objectLiteral(candidate) && URI$
|
|
8280
|
+
return Is.objectLiteral(candidate) && URI$5.is(candidate.uri) && Is.string(candidate.name);
|
|
8281
8281
|
}
|
|
8282
8282
|
WorkspaceFolder.is = is;
|
|
8283
8283
|
})(WorkspaceFolder || (WorkspaceFolder = {}));
|
|
@@ -22683,6 +22683,83 @@ function typescript_notice(found, workspace_dirs) {
|
|
|
22683
22683
|
].join(" ");
|
|
22684
22684
|
}
|
|
22685
22685
|
|
|
22686
|
+
//#endregion
|
|
22687
|
+
//#region ../typescript-plugin/src/unclosed-element.js
|
|
22688
|
+
/** @import * as AST from 'estree' */
|
|
22689
|
+
/**
|
|
22690
|
+
* Elements whose body is raw text, each with a pattern for its opening tag. The
|
|
22691
|
+
* body ends at the next `</style>` or `<\/script>`, wherever it is later in the
|
|
22692
|
+
* file, so that closing tag can belong to a later element (see `isUnclosed`).
|
|
22693
|
+
*/
|
|
22694
|
+
const RAW_TEXT_OPENING_TAGS = /* @__PURE__ */ new Map([["style", /<style[\s/>]/], ["script", /<script[\s/>]/]]);
|
|
22695
|
+
/**
|
|
22696
|
+
* An element of the parsed source and, when the element is one of its children,
|
|
22697
|
+
* the element that holds it.
|
|
22698
|
+
* @typedef {{ element: AST.TSRXJSXElement; parent: ElementPath | null }} ElementPath
|
|
22699
|
+
*/
|
|
22700
|
+
/**
|
|
22701
|
+
* Find the element whose opening tag ends at `end` in the parsed source.
|
|
22702
|
+
* @param {unknown} node
|
|
22703
|
+
* @param {number} end - The offset right after the opening tag's `>`
|
|
22704
|
+
* @param {ElementPath | null} [parent] - The element whose `children` hold `node`
|
|
22705
|
+
* @returns {ElementPath | null}
|
|
22706
|
+
*/
|
|
22707
|
+
function findElement(node, end, parent = null) {
|
|
22708
|
+
if (Array.isArray(node)) {
|
|
22709
|
+
for (const child of node) {
|
|
22710
|
+
const found = findElement(child, end, parent);
|
|
22711
|
+
if (found) return found;
|
|
22712
|
+
}
|
|
22713
|
+
return null;
|
|
22714
|
+
}
|
|
22715
|
+
if (!node || typeof node !== "object") return null;
|
|
22716
|
+
const element = node;
|
|
22717
|
+
const path = element.openingElement ? {
|
|
22718
|
+
element,
|
|
22719
|
+
parent
|
|
22720
|
+
} : null;
|
|
22721
|
+
if (path?.element.openingElement.end === end) return path;
|
|
22722
|
+
for (const [key, value] of Object.entries(node)) {
|
|
22723
|
+
if (key === "loc" || key === "metadata") continue;
|
|
22724
|
+
const found = findElement(value, end, key === "children" ? path : null);
|
|
22725
|
+
if (found) return found;
|
|
22726
|
+
}
|
|
22727
|
+
return null;
|
|
22728
|
+
}
|
|
22729
|
+
/**
|
|
22730
|
+
* Whether the element still needs its closing tag, decided like TypeScript's
|
|
22731
|
+
* `isUnclosedTag`: the element is unclosed, or it took the closing tag of a parent
|
|
22732
|
+
* with the same name (`<div>` typed as the first child of a `<div>`), which is then
|
|
22733
|
+
* the unclosed one. Loose-mode recovery marks an element without its closing tag
|
|
22734
|
+
* `unclosed`.
|
|
22735
|
+
*
|
|
22736
|
+
* A `<style>` or `<script>` body ends at the next closing tag with its name, which
|
|
22737
|
+
* can belong to a later element: a new `<style>` typed in one component takes the
|
|
22738
|
+
* `</style>` of the style block in the next component. That element's opening tag
|
|
22739
|
+
* is then in the body, so the new element still needs its own closing tag.
|
|
22740
|
+
* @param {ElementPath} path
|
|
22741
|
+
* @param {string} sourceCode
|
|
22742
|
+
* @returns {boolean}
|
|
22743
|
+
*/
|
|
22744
|
+
function isUnclosed(path, sourceCode) {
|
|
22745
|
+
/** @param {AST.TSRXJSXElement} element */
|
|
22746
|
+
const name = (element) => {
|
|
22747
|
+
const { start, end } = element.openingElement.name;
|
|
22748
|
+
return sourceCode.slice(start, end);
|
|
22749
|
+
};
|
|
22750
|
+
const { element } = path;
|
|
22751
|
+
const rawTextOpeningTag = RAW_TEXT_OPENING_TAGS.get(name(element));
|
|
22752
|
+
if (rawTextOpeningTag) {
|
|
22753
|
+
if (element.unclosed || !element.closingElement) return true;
|
|
22754
|
+
const bodyEnd = element.closingElement.start;
|
|
22755
|
+
return rawTextOpeningTag.test(sourceCode.slice(element.openingElement.end, bodyEnd));
|
|
22756
|
+
}
|
|
22757
|
+
for (let current = path;; current = current.parent) {
|
|
22758
|
+
if (current.element.unclosed) return true;
|
|
22759
|
+
if (!current.parent || name(current.parent.element) !== name(current.element)) return false;
|
|
22760
|
+
}
|
|
22761
|
+
}
|
|
22762
|
+
|
|
22686
22763
|
//#endregion
|
|
22687
22764
|
//#region src/autoInsertPlugin.js
|
|
22688
22765
|
/** @import * as AST from 'estree' */
|
|
@@ -22711,12 +22788,6 @@ const VOID_ELEMENTS = /* @__PURE__ */ new Set([
|
|
|
22711
22788
|
"wbr"
|
|
22712
22789
|
]);
|
|
22713
22790
|
/**
|
|
22714
|
-
* Elements whose body is raw text, each with a pattern for its opening tag. The
|
|
22715
|
-
* body ends at the next `</style>` or `<\/script>`, wherever it is later in the
|
|
22716
|
-
* file, so that closing tag can belong to a later element (see `isUnclosed`).
|
|
22717
|
-
*/
|
|
22718
|
-
const RAW_TEXT_OPENING_TAGS = /* @__PURE__ */ new Map([["style", /<style[\s/>]/], ["script", /<script[\s/>]/]]);
|
|
22719
|
-
/**
|
|
22720
22791
|
* Auto-insert plugin for TSRX.
|
|
22721
22792
|
* Handles auto-closing tags when typing '>' after a tag name. The VS Code extension
|
|
22722
22793
|
* asks for them with Volar's `volar/client/autoInsert` request; other editors get
|
|
@@ -22805,73 +22876,6 @@ async provideAutoInsertSnippet(document, position, lastChange, _token) {
|
|
|
22805
22876
|
};
|
|
22806
22877
|
}
|
|
22807
22878
|
/**
|
|
22808
|
-
* An element of the parsed source and, when the element is one of its children,
|
|
22809
|
-
* the element that holds it.
|
|
22810
|
-
* @typedef {{ element: AST.TSRXJSXElement; parent: ElementPath | null }} ElementPath
|
|
22811
|
-
*/
|
|
22812
|
-
/**
|
|
22813
|
-
* Find the element whose opening tag ends at `end` in the parsed source.
|
|
22814
|
-
* @param {unknown} node
|
|
22815
|
-
* @param {number} end - The offset right after the opening tag's `>`
|
|
22816
|
-
* @param {ElementPath | null} [parent] - The element whose `children` hold `node`
|
|
22817
|
-
* @returns {ElementPath | null}
|
|
22818
|
-
*/
|
|
22819
|
-
function findElement(node, end, parent = null) {
|
|
22820
|
-
if (Array.isArray(node)) {
|
|
22821
|
-
for (const child of node) {
|
|
22822
|
-
const found = findElement(child, end, parent);
|
|
22823
|
-
if (found) return found;
|
|
22824
|
-
}
|
|
22825
|
-
return null;
|
|
22826
|
-
}
|
|
22827
|
-
if (!node || typeof node !== "object") return null;
|
|
22828
|
-
const element = node;
|
|
22829
|
-
const path = element.openingElement ? {
|
|
22830
|
-
element,
|
|
22831
|
-
parent
|
|
22832
|
-
} : null;
|
|
22833
|
-
if (path?.element.openingElement.end === end) return path;
|
|
22834
|
-
for (const [key, value] of Object.entries(node)) {
|
|
22835
|
-
if (key === "loc" || key === "metadata") continue;
|
|
22836
|
-
const found = findElement(value, end, key === "children" ? path : null);
|
|
22837
|
-
if (found) return found;
|
|
22838
|
-
}
|
|
22839
|
-
return null;
|
|
22840
|
-
}
|
|
22841
|
-
/**
|
|
22842
|
-
* Whether the element still needs its closing tag, decided like TypeScript's
|
|
22843
|
-
* `isUnclosedTag`: the element is unclosed, or it took the closing tag of a parent
|
|
22844
|
-
* with the same name (`<div>` typed as the first child of a `<div>`), which is then
|
|
22845
|
-
* the unclosed one. Loose-mode recovery marks an element without its closing tag
|
|
22846
|
-
* `unclosed`.
|
|
22847
|
-
*
|
|
22848
|
-
* A `<style>` or `<script>` body ends at the next closing tag with its name, which
|
|
22849
|
-
* can belong to a later element: a new `<style>` typed in one component takes the
|
|
22850
|
-
* `</style>` of the style block in the next component. That element's opening tag
|
|
22851
|
-
* is then in the body, so the new element still needs its own closing tag.
|
|
22852
|
-
* @param {ElementPath} path
|
|
22853
|
-
* @param {string} sourceCode
|
|
22854
|
-
* @returns {boolean}
|
|
22855
|
-
*/
|
|
22856
|
-
function isUnclosed(path, sourceCode) {
|
|
22857
|
-
/** @param {AST.TSRXJSXElement} element */
|
|
22858
|
-
const name = (element) => {
|
|
22859
|
-
const { start, end } = element.openingElement.name;
|
|
22860
|
-
return sourceCode.slice(start, end);
|
|
22861
|
-
};
|
|
22862
|
-
const { element } = path;
|
|
22863
|
-
const rawTextOpeningTag = RAW_TEXT_OPENING_TAGS.get(name(element));
|
|
22864
|
-
if (rawTextOpeningTag) {
|
|
22865
|
-
if (element.unclosed || !element.closingElement) return true;
|
|
22866
|
-
const bodyEnd = element.closingElement.start;
|
|
22867
|
-
return rawTextOpeningTag.test(sourceCode.slice(element.openingElement.end, bodyEnd));
|
|
22868
|
-
}
|
|
22869
|
-
for (let current = path;; current = current.parent) {
|
|
22870
|
-
if (current.element.unclosed) return true;
|
|
22871
|
-
if (!current.parent || name(current.parent.element) !== name(current.element)) return false;
|
|
22872
|
-
}
|
|
22873
|
-
}
|
|
22874
|
-
/**
|
|
22875
22879
|
* Escape `text` so that a snippet inserts it as written. `\`, `$` and `}` are snippet
|
|
22876
22880
|
* syntax: unescaped, the `$Foo` in `</$Foo>` is a variable, which VS Code replaces
|
|
22877
22881
|
* with nothing.
|
|
@@ -23055,7 +23059,7 @@ function parseCompilationErrorWithDocument(error, virtualCode, sourceMap, docume
|
|
|
23055
23059
|
let start = null;
|
|
23056
23060
|
/** @type {Position | null} */
|
|
23057
23061
|
let end = null;
|
|
23058
|
-
if (error.pos) {
|
|
23062
|
+
if (error.pos !== void 0) {
|
|
23059
23063
|
const start_offset = get_start_offset_from_error(error);
|
|
23060
23064
|
const end_offset = get_end_offset_from_error(error, start_offset);
|
|
23061
23065
|
const mapping = virtualCode.findMappingBySourceRange(start_offset, end_offset);
|
|
@@ -23076,6 +23080,13 @@ function parseCompilationErrorWithDocument(error, virtualCode, sourceMap, docume
|
|
|
23076
23080
|
}
|
|
23077
23081
|
}
|
|
23078
23082
|
}
|
|
23083
|
+
if (!start || !end) {
|
|
23084
|
+
const nearest = nearest_reported_range(virtualCode, start_offset, error.raisedAt);
|
|
23085
|
+
if (nearest) {
|
|
23086
|
+
start = document.positionAt(nearest[0]);
|
|
23087
|
+
end = document.positionAt(nearest[1]);
|
|
23088
|
+
}
|
|
23089
|
+
}
|
|
23079
23090
|
}
|
|
23080
23091
|
if (!start || !end) {
|
|
23081
23092
|
start = {
|
|
@@ -23088,7 +23099,7 @@ function parseCompilationErrorWithDocument(error, virtualCode, sourceMap, docume
|
|
|
23088
23099
|
};
|
|
23089
23100
|
}
|
|
23090
23101
|
return {
|
|
23091
|
-
severity: import_language_server.DiagnosticSeverity.Error,
|
|
23102
|
+
severity: error.severity === "warning" ? import_language_server.DiagnosticSeverity.Warning : import_language_server.DiagnosticSeverity.Error,
|
|
23092
23103
|
range: {
|
|
23093
23104
|
start,
|
|
23094
23105
|
end
|
|
@@ -23099,6 +23110,56 @@ function parseCompilationErrorWithDocument(error, virtualCode, sourceMap, docume
|
|
|
23099
23110
|
};
|
|
23100
23111
|
}
|
|
23101
23112
|
/**
|
|
23113
|
+
* The generated range of the source token that reports diagnostics and starts
|
|
23114
|
+
* nearest after `offset`, when it starts before `reach`. Otherwise the one that
|
|
23115
|
+
* ends nearest before `offset`, or starts nearest after it when none ends
|
|
23116
|
+
* before it. Of tokens the same distance away, the shortest. A mapping over
|
|
23117
|
+
* whitespace only, such as the indentation before a template's output, is not
|
|
23118
|
+
* code to show the error on.
|
|
23119
|
+
* @param {TSRXVirtualCodeInstance} virtualCode
|
|
23120
|
+
* @param {number} offset
|
|
23121
|
+
* @param {number} [reach] Where the error's parser stopped, such as the token that ended a template
|
|
23122
|
+
* @returns {[number, number] | null}
|
|
23123
|
+
*/
|
|
23124
|
+
function nearest_reported_range(virtualCode, offset, reach = offset) {
|
|
23125
|
+
/** @type {{ range: [number, number], distance: number, length: number } | null} */
|
|
23126
|
+
let before = null;
|
|
23127
|
+
/** @type {{ range: [number, number], distance: number, length: number, start: number } | null} */
|
|
23128
|
+
let after = null;
|
|
23129
|
+
for (const mapping of virtualCode.mappings ?? []) {
|
|
23130
|
+
if (!mapping.data?.verification) continue;
|
|
23131
|
+
for (let i = 0; i < mapping.sourceOffsets.length; i++) {
|
|
23132
|
+
const source_start = mapping.sourceOffsets[i];
|
|
23133
|
+
const length = mapping.lengths[i];
|
|
23134
|
+
const generated_length = mapping.generatedLengths?.[i] ?? length;
|
|
23135
|
+
if (length === 0 || generated_length <= 0) continue;
|
|
23136
|
+
if (!/\S/.test(virtualCode.originalCode.slice(source_start, source_start + length))) continue;
|
|
23137
|
+
const generated_start = mapping.generatedOffsets[i];
|
|
23138
|
+
const ends_before = source_start + length <= offset;
|
|
23139
|
+
if (!ends_before && source_start < offset) continue;
|
|
23140
|
+
const candidate = {
|
|
23141
|
+
/** @type {[number, number]} */
|
|
23142
|
+
range: [generated_start, generated_start + generated_length],
|
|
23143
|
+
distance: ends_before ? offset - (source_start + length) : source_start - offset,
|
|
23144
|
+
length,
|
|
23145
|
+
start: source_start
|
|
23146
|
+
};
|
|
23147
|
+
if (ends_before) {
|
|
23148
|
+
if (is_nearer(candidate, before)) before = candidate;
|
|
23149
|
+
} else if (is_nearer(candidate, after)) after = candidate;
|
|
23150
|
+
}
|
|
23151
|
+
}
|
|
23152
|
+
if (after && after.start < reach) return after.range;
|
|
23153
|
+
return (before ?? after)?.range ?? null;
|
|
23154
|
+
}
|
|
23155
|
+
/**
|
|
23156
|
+
* @param {{ distance: number, length: number }} candidate
|
|
23157
|
+
* @param {{ distance: number, length: number } | null} best
|
|
23158
|
+
*/
|
|
23159
|
+
function is_nearer(candidate, best) {
|
|
23160
|
+
return !best || candidate.distance < best.distance || candidate.distance === best.distance && candidate.length < best.length;
|
|
23161
|
+
}
|
|
23162
|
+
/**
|
|
23102
23163
|
* @param {CompileError} error
|
|
23103
23164
|
* @param {TextDocument} document
|
|
23104
23165
|
* @returns {Range}
|
|
@@ -23999,6 +24060,14 @@ init_main();
|
|
|
23999
24060
|
* }} NodeWithId;
|
|
24000
24061
|
*/
|
|
24001
24062
|
/**
|
|
24063
|
+
* A raw-text `<script>` element, its body verbatim in `content`.
|
|
24064
|
+
* @typedef {{
|
|
24065
|
+
* openingElement: { name: { start: number, end: number }, end: number },
|
|
24066
|
+
* closingElement: { name: { end: number } } | null,
|
|
24067
|
+
* content: string,
|
|
24068
|
+
* }} ScriptElement;
|
|
24069
|
+
*/
|
|
24070
|
+
/**
|
|
24002
24071
|
* @typedef {[
|
|
24003
24072
|
* Omit<DocumentSymbol, 'children'> & { children: SymbolInfo[] }, {
|
|
24004
24073
|
* rangeNode: AST.Node;
|
|
@@ -24031,7 +24100,7 @@ function createDocumentSymbolPlugin() {
|
|
|
24031
24100
|
if (virtualCode?.fatalErrors?.length || virtualCode?.isDotCompletionMode) return collectFallbackDocumentSymbols(document, fallbackFileName) ?? cachedSymbols;
|
|
24032
24101
|
if (!sourceMap || !sourceAst) return collectFallbackDocumentSymbols(document, fallbackFileName) ?? [];
|
|
24033
24102
|
const sourceDocument = TextDocument.create(sourceUri.toString(), "tsrx", 0, originalCode);
|
|
24034
|
-
const symbols = mapDocumentSymbolsToGenerated(collectDocumentSymbols(sourceAst, sourceDocument), virtualCode, sourceDocument, document, sourceMap);
|
|
24103
|
+
const symbols = mapDocumentSymbolsToGenerated(collectDocumentSymbols(sourceAst, sourceDocument, virtualCode.scriptRegions), virtualCode, sourceDocument, document, sourceMap);
|
|
24035
24104
|
documentSymbolCache.set(cacheKey, symbols);
|
|
24036
24105
|
return symbols;
|
|
24037
24106
|
} };
|
|
@@ -24172,10 +24241,70 @@ function isSymbolMapping(data) {
|
|
|
24172
24241
|
/**
|
|
24173
24242
|
* @param {AST.Program} ast
|
|
24174
24243
|
* @param {TextDocument} document
|
|
24244
|
+
* @param {Array<{ start: number, content: string }>} [scriptRegions] The `<script>` bodies of
|
|
24245
|
+
* code, from the compiler's script mappings.
|
|
24175
24246
|
* @returns {SymbolInfo[]}
|
|
24176
24247
|
*/
|
|
24177
|
-
function collectDocumentSymbols(ast, document) {
|
|
24178
|
-
|
|
24248
|
+
function collectDocumentSymbols(ast, document, scriptRegions = []) {
|
|
24249
|
+
const symbols = collectSymbolsFromStatements(Array.isArray(ast.body) ? ast.body : [], document);
|
|
24250
|
+
if (scriptRegions.length > 0) {
|
|
24251
|
+
const elements = findScriptElements(ast);
|
|
24252
|
+
for (const region of scriptRegions) {
|
|
24253
|
+
const element = elements.get(region.start);
|
|
24254
|
+
if (element) symbols.push(createScriptSymbol(element, region, document));
|
|
24255
|
+
}
|
|
24256
|
+
}
|
|
24257
|
+
return symbols.sort(([, a], [, b]) => a.rangeNode.start - b.rangeNode.start);
|
|
24258
|
+
}
|
|
24259
|
+
/**
|
|
24260
|
+
* The `<script>` elements of a source AST, by the offset where their body starts (the end of
|
|
24261
|
+
* the opening tag), which is where the compiler's script regions start.
|
|
24262
|
+
* @param {AST.Node} ast
|
|
24263
|
+
* @returns {Map<number, ScriptElement>}
|
|
24264
|
+
*/
|
|
24265
|
+
function findScriptElements(ast) {
|
|
24266
|
+
/** @type {Map<number, ScriptElement>} */
|
|
24267
|
+
const elements = /* @__PURE__ */ new Map();
|
|
24268
|
+
/** @param {any} node */
|
|
24269
|
+
const visit = (node) => {
|
|
24270
|
+
if (node.type === "JSXElement" && node.openingElement?.name?.type === "JSXIdentifier" && node.openingElement.name.name === "script" && typeof node.content === "string") elements.set(node.openingElement.end, node);
|
|
24271
|
+
for (const key in node) {
|
|
24272
|
+
if (key === "loc" || key === "metadata" || key === "css") continue;
|
|
24273
|
+
const value = node[key];
|
|
24274
|
+
for (const child of Array.isArray(value) ? value : [value]) if (child && typeof child === "object" && typeof child.type === "string") visit(child);
|
|
24275
|
+
}
|
|
24276
|
+
};
|
|
24277
|
+
visit(ast);
|
|
24278
|
+
return elements;
|
|
24279
|
+
}
|
|
24280
|
+
/**
|
|
24281
|
+
* A `<script>` symbol spanning the element from its tag name to its closing tag name (the
|
|
24282
|
+
* parts of it that map to the generated TSX), selected by the opening tag's name, with the
|
|
24283
|
+
* top-level declarations of its body as children. The transform appends each body to the
|
|
24284
|
+
* generated TSX as a bare block, which TypeScript's navigation tree skips, so the body is
|
|
24285
|
+
* parsed here, where it stands in the source: the rest of the file is blanked, which keeps
|
|
24286
|
+
* every offset a source offset.
|
|
24287
|
+
* @param {ScriptElement} element
|
|
24288
|
+
* @param {{ start: number, content: string }} region
|
|
24289
|
+
* @param {TextDocument} document
|
|
24290
|
+
* @returns {SymbolInfo}
|
|
24291
|
+
*/
|
|
24292
|
+
function createScriptSymbol(element, region, document) {
|
|
24293
|
+
/** @type {AST.Node[]} */
|
|
24294
|
+
let statements = [];
|
|
24295
|
+
try {
|
|
24296
|
+
const blanked = document.getText().slice(0, region.start).replace(/[^\r\n]/g, " ") + region.content;
|
|
24297
|
+
statements = (0, _tsrx_core.parseModule)(blanked, document.uri, { loose: true }).body;
|
|
24298
|
+
} catch (error) {
|
|
24299
|
+
logError$3(`Unable to read a <script> body: ${/** @type {Error} */ error.message}`);
|
|
24300
|
+
}
|
|
24301
|
+
const name = element.openingElement.name;
|
|
24302
|
+
const range = {
|
|
24303
|
+
type: "JSXElement",
|
|
24304
|
+
start: name.start,
|
|
24305
|
+
end: element.closingElement?.name.end ?? region.start + region.content.length
|
|
24306
|
+
};
|
|
24307
|
+
return createNamedNodeSymbol("<script>", import_language_server.SymbolKind.Module, range, name, document, collectSymbolsFromStatements(statements, document));
|
|
24179
24308
|
}
|
|
24180
24309
|
/**
|
|
24181
24310
|
* @param {AST.Node[]} statements
|
|
@@ -24233,6 +24362,9 @@ function createSymbolForDeclaration(node, document, fallbackName) {
|
|
|
24233
24362
|
case "TSTypeAliasDeclaration":
|
|
24234
24363
|
if (!id || !name) return [];
|
|
24235
24364
|
return [createNamedNodeSymbol(name, import_language_server.SymbolKind.TypeParameter, node, id, document)];
|
|
24365
|
+
case "TSEnumDeclaration":
|
|
24366
|
+
if (!id || !name) return [];
|
|
24367
|
+
return [createNamedNodeSymbol(name, import_language_server.SymbolKind.Enum, node, id, document)];
|
|
24236
24368
|
default: return [];
|
|
24237
24369
|
}
|
|
24238
24370
|
}
|
|
@@ -24629,6 +24761,74 @@ function createTypeScriptDiagnosticFilterPlugin() {
|
|
|
24629
24761
|
};
|
|
24630
24762
|
}
|
|
24631
24763
|
|
|
24764
|
+
//#endregion
|
|
24765
|
+
//#region ../typescript-plugin/src/module-format.js
|
|
24766
|
+
/**
|
|
24767
|
+
* The module format (`impliedNodeFormat`) of `.tsrx` files. TypeScript derives a
|
|
24768
|
+
* file's format from its extension, and knows none for `.tsrx`, so under
|
|
24769
|
+
* `node16`/`nodenext` it treats every `.tsrx` file as CommonJS: `import.meta`
|
|
24770
|
+
* reports TS1470 even in a `"type": "module"` package. Volar's
|
|
24771
|
+
* `fixupImpliedNodeFormatForFile` sets the format only while it resolves the
|
|
24772
|
+
* file's imports, and resets it afterwards.
|
|
24773
|
+
*
|
|
24774
|
+
* A `.tsrx` file takes the format a `.ts` file at the same path would have:
|
|
24775
|
+
* from the `type` of the nearest `package.json` under `node16`/`nodenext` (or in
|
|
24776
|
+
* `node_modules`), and none otherwise. TSRX has no `.mtsrx`/`.ctsrx`
|
|
24777
|
+
* counterparts of `.mts`/`.cts`. The format goes into the options TypeScript
|
|
24778
|
+
* creates the source file with, so the source file's external-module status, the
|
|
24779
|
+
* document registry's key and the `package.json` TypeScript watches all match it.
|
|
24780
|
+
*/
|
|
24781
|
+
/**
|
|
24782
|
+
* Fill in the module format of a `.tsrx` file in the options TypeScript is about
|
|
24783
|
+
* to create its source file with, as TypeScript fills it in for a `.ts` file.
|
|
24784
|
+
* Options that already carry a format, and other files, are left alone.
|
|
24785
|
+
* @param {typeof import('typescript')} ts
|
|
24786
|
+
* @param {string} file_name
|
|
24787
|
+
* @param {unknown} source_file_options The `languageVersionOrOptions` of `getSourceFile`.
|
|
24788
|
+
* @param {import('typescript').PackageJsonInfoCache | undefined} package_json_info_cache
|
|
24789
|
+
* @param {import('typescript').ModuleResolutionHost} host
|
|
24790
|
+
* @param {import('typescript').CompilerOptions} compiler_options
|
|
24791
|
+
*/
|
|
24792
|
+
function fill_tsrx_module_format(ts, file_name, source_file_options, package_json_info_cache, host, compiler_options) {
|
|
24793
|
+
if (typeof source_file_options !== "object" || source_file_options === null || source_file_options.impliedNodeFormat !== void 0 || !is_tsrx_file(file_name)) return;
|
|
24794
|
+
const worker = ts.getImpliedNodeFormatForFileWorker;
|
|
24795
|
+
const format = worker ? worker(`${file_name}.ts`, package_json_info_cache, host, compiler_options) : ts.getImpliedNodeFormatForFile?.(`${file_name}.ts`, package_json_info_cache, host, compiler_options);
|
|
24796
|
+
if (typeof format === "object" && format !== null) Object.assign(source_file_options, format);
|
|
24797
|
+
else if (format !== void 0)
|
|
24798
|
+
/** @type {import('typescript').CreateSourceFileOptions} */ source_file_options.impliedNodeFormat = format;
|
|
24799
|
+
}
|
|
24800
|
+
/** @type {WeakSet<object>} */
|
|
24801
|
+
const patched = /* @__PURE__ */ new WeakSet();
|
|
24802
|
+
/**
|
|
24803
|
+
* Language services (tsserver, the language server): fill in the module format
|
|
24804
|
+
* of each `.tsrx` document the registry creates or updates. The language
|
|
24805
|
+
* service passes the options the program computed, and the registry keys its
|
|
24806
|
+
* entries by their format, so it has to be set before the registry sees them.
|
|
24807
|
+
* @param {typeof import('typescript')} ts
|
|
24808
|
+
* @param {import('typescript').DocumentRegistry} registry
|
|
24809
|
+
* @returns {import('typescript').DocumentRegistry}
|
|
24810
|
+
*/
|
|
24811
|
+
function with_tsrx_module_format_in_registry(ts, registry) {
|
|
24812
|
+
if (patched.has(registry)) return registry;
|
|
24813
|
+
patched.add(registry);
|
|
24814
|
+
for (const method of ["acquireDocumentWithKey", "updateDocumentWithKey"]) {
|
|
24815
|
+
const original = registry[method];
|
|
24816
|
+
/** @type {any} */ registry[method] = (file_name, path, host, key, snapshot, version, script_kind, source_file_options) => {
|
|
24817
|
+
fill_tsrx_module_format(
|
|
24818
|
+
ts,
|
|
24819
|
+
file_name,
|
|
24820
|
+
source_file_options,
|
|
24821
|
+
/** @type {any} */
|
|
24822
|
+
host.getModuleResolutionCache?.()?.getPackageJsonInfoCache(),
|
|
24823
|
+
host,
|
|
24824
|
+
host.getCompilationSettings()
|
|
24825
|
+
);
|
|
24826
|
+
return original.call(registry, file_name, path, host, key, snapshot, version, script_kind, source_file_options);
|
|
24827
|
+
};
|
|
24828
|
+
}
|
|
24829
|
+
return registry;
|
|
24830
|
+
}
|
|
24831
|
+
|
|
24632
24832
|
//#endregion
|
|
24633
24833
|
//#region src/typescriptService.js
|
|
24634
24834
|
/**
|
|
@@ -24670,7 +24870,19 @@ function load_typescript_service() {
|
|
|
24670
24870
|
* @returns {ReturnType<typeof import('volar-service-typescript').create>}
|
|
24671
24871
|
*/
|
|
24672
24872
|
function createTypeScriptServices(ts) {
|
|
24673
|
-
return load_typescript_service().create(ts);
|
|
24873
|
+
return load_typescript_service().create(with_tsrx_document_registries(ts));
|
|
24874
|
+
}
|
|
24875
|
+
/**
|
|
24876
|
+
* `ts` for `volar-service-typescript`, whose language services get each `.tsrx`
|
|
24877
|
+
* document's module format from their document registry
|
|
24878
|
+
* (`with_tsrx_module_format_in_registry`). The service creates the registries
|
|
24879
|
+
* itself, and the module's exports are read-only getters, so the override sits
|
|
24880
|
+
* on an object that inherits everything else from `ts`.
|
|
24881
|
+
* @param {typeof import('typescript')} ts
|
|
24882
|
+
* @returns {typeof import('typescript')}
|
|
24883
|
+
*/
|
|
24884
|
+
function with_tsrx_document_registries(ts) {
|
|
24885
|
+
return Object.create(ts, { createDocumentRegistry: { value: (...args) => with_tsrx_module_format_in_registry(ts, ts.createDocumentRegistry(...args)) } });
|
|
24674
24886
|
}
|
|
24675
24887
|
|
|
24676
24888
|
//#endregion
|
|
@@ -24708,6 +24920,26 @@ function stripFormatting(plugin) {
|
|
|
24708
24920
|
};
|
|
24709
24921
|
}
|
|
24710
24922
|
/**
|
|
24923
|
+
* Strip the folding capability from a Volar service plugin.
|
|
24924
|
+
*
|
|
24925
|
+
* Volar runs service plugins on the generated TS and CSS, and keeps the folds whose ends
|
|
24926
|
+
* map back to the `.tsrx` source: the CSS service's folds in `<style>` blocks do, but none
|
|
24927
|
+
* of TypeScript's. The server folds `.tsrx` sources itself (`foldingRangeHandler.js`) and
|
|
24928
|
+
* adds the folds Volar maps back: a plugin that offered folding ranges would make Volar
|
|
24929
|
+
* register its own `textDocument/foldingRange` handler, which would replace that one.
|
|
24930
|
+
*
|
|
24931
|
+
* @template {{ capabilities?: Record<string, unknown> }} T
|
|
24932
|
+
* @param {T} plugin
|
|
24933
|
+
* @returns {T}
|
|
24934
|
+
*/
|
|
24935
|
+
function stripFoldingRanges(plugin) {
|
|
24936
|
+
const { foldingRangeProvider: _folding, ...capabilities } = plugin.capabilities ?? {};
|
|
24937
|
+
return {
|
|
24938
|
+
...plugin,
|
|
24939
|
+
capabilities
|
|
24940
|
+
};
|
|
24941
|
+
}
|
|
24942
|
+
/**
|
|
24711
24943
|
* The Volar service plugins for a backend, in registration order.
|
|
24712
24944
|
*
|
|
24713
24945
|
* Classic: the TypeScript services run in this process and the TSRX
|
|
@@ -24733,7 +24965,7 @@ function createServicePlugins(backend, ts) {
|
|
|
24733
24965
|
const shared_last = [
|
|
24734
24966
|
createDefinitionPlugin(),
|
|
24735
24967
|
createDocumentSymbolPlugin(),
|
|
24736
|
-
stripFormatting((0, volar_service_css.create)())
|
|
24968
|
+
stripFoldingRanges(stripFormatting((0, volar_service_css.create)()))
|
|
24737
24969
|
];
|
|
24738
24970
|
if (backend === "native" || backend === "plugin") return [
|
|
24739
24971
|
...shared_first,
|
|
@@ -24747,7 +24979,7 @@ function createServicePlugins(backend, ts) {
|
|
|
24747
24979
|
...shared_first,
|
|
24748
24980
|
createCompileErrorDiagnosticPlugin(),
|
|
24749
24981
|
...shared_last,
|
|
24750
|
-
...createTypeScriptServices(ts).map(stripFormatting),
|
|
24982
|
+
...createTypeScriptServices(ts).map((plugin) => stripFoldingRanges(stripFormatting(plugin))),
|
|
24751
24983
|
createTypeScriptDiagnosticFilterPlugin(),
|
|
24752
24984
|
createHoverPlugin({ typescriptBackend: backend }),
|
|
24753
24985
|
createDocumentHighlightPlugin({ typescriptBackend: backend })
|
|
@@ -25111,8 +25343,429 @@ async function closing_tags_enabled(connection, uri) {
|
|
|
25111
25343
|
}
|
|
25112
25344
|
}
|
|
25113
25345
|
|
|
25346
|
+
//#endregion
|
|
25347
|
+
//#region src/foldingRangeHandler.js
|
|
25348
|
+
/** @import * as AST from 'estree' */
|
|
25349
|
+
/** @import { Connection, FoldingRange, LanguageServer } from '@volar/language-server' */
|
|
25350
|
+
/**
|
|
25351
|
+
* A fold that ends on one of these keeps the line holding it visible: the closing `}`,
|
|
25352
|
+
* `</div>`, `)` or `` ` ``, as VS Code's TypeScript folds TSX.
|
|
25353
|
+
*/
|
|
25354
|
+
const CLOSING_CHARACTERS = /* @__PURE__ */ new Set([
|
|
25355
|
+
"}",
|
|
25356
|
+
"]",
|
|
25357
|
+
")",
|
|
25358
|
+
"`",
|
|
25359
|
+
">"
|
|
25360
|
+
]);
|
|
25361
|
+
/** TypeScript's region markers: `// #region name` and `// #endregion`. */
|
|
25362
|
+
const REGION_MARKER = /^#(end)?region/;
|
|
25363
|
+
/** Keys that hold no child nodes, or nodes whose offsets are not source offsets. */
|
|
25364
|
+
const SKIPPED_KEYS = /* @__PURE__ */ new Set([
|
|
25365
|
+
"loc",
|
|
25366
|
+
"metadata",
|
|
25367
|
+
"css",
|
|
25368
|
+
"leadingComments",
|
|
25369
|
+
"trailingComments",
|
|
25370
|
+
"innerComments"
|
|
25371
|
+
]);
|
|
25372
|
+
/** Statements whose body block folds from the end of the line that opens it. */
|
|
25373
|
+
const ATTACHED_BLOCK_PARENTS = /* @__PURE__ */ new Set([
|
|
25374
|
+
"IfStatement",
|
|
25375
|
+
"ForStatement",
|
|
25376
|
+
"ForInStatement",
|
|
25377
|
+
"ForOfStatement",
|
|
25378
|
+
"WhileStatement",
|
|
25379
|
+
"DoWhileStatement",
|
|
25380
|
+
"WithStatement",
|
|
25381
|
+
"TryStatement",
|
|
25382
|
+
"CatchClause",
|
|
25383
|
+
"SwitchCase",
|
|
25384
|
+
"JSXIfExpression",
|
|
25385
|
+
"JSXForExpression",
|
|
25386
|
+
"JSXTryExpression"
|
|
25387
|
+
]);
|
|
25388
|
+
const FUNCTION_TYPES = /* @__PURE__ */ new Set([
|
|
25389
|
+
"FunctionDeclaration",
|
|
25390
|
+
"FunctionExpression",
|
|
25391
|
+
"ArrowFunctionExpression"
|
|
25392
|
+
]);
|
|
25393
|
+
/**
|
|
25394
|
+
* Answer `textDocument/foldingRange` for `.tsrx` files with folds computed from the TSRX
|
|
25395
|
+
* source, merged with the folds Volar's service plugins map back from embedded code (the CSS
|
|
25396
|
+
* of `<style>` blocks). Volar's own handler would only return the mapped ones: TypeScript's
|
|
25397
|
+
* folds on the generated code do not map back, and neither VS Code's TypeScript (whose
|
|
25398
|
+
* tsserver plugin answers no outlining spans for `.tsrx` files) nor TypeScript 7 folds
|
|
25399
|
+
* `.tsrx` files. No Volar service plugin offers folding ranges (`stripFoldingRanges` in
|
|
25400
|
+
* `servicePlugins.js`), so Volar registers no handler that would replace this one.
|
|
25401
|
+
* @param {Connection} connection
|
|
25402
|
+
* @param {LanguageServer} server
|
|
25403
|
+
*/
|
|
25404
|
+
function register_folding_ranges(connection, server) {
|
|
25405
|
+
connection.onFoldingRanges(async (params, token) => {
|
|
25406
|
+
const uri = vscode_uri.URI.parse(params.textDocument.uri);
|
|
25407
|
+
const embedded = await (await server.project.getLanguageService(uri)).getFoldingRanges(uri, token) ?? [];
|
|
25408
|
+
if (token.isCancellationRequested) return null;
|
|
25409
|
+
const document = server.documents.get(uri);
|
|
25410
|
+
if (!document || !is_tsrx_document(params.textDocument.uri)) return embedded;
|
|
25411
|
+
return merge_folding_ranges([...collect_folding_ranges(document.getText(), uri.fsPath), ...embedded]);
|
|
25412
|
+
});
|
|
25413
|
+
}
|
|
25414
|
+
/**
|
|
25415
|
+
* The folds of a `.tsrx` source, following the folds TypeScript gives TSX: functions and
|
|
25416
|
+
* other blocks, `@{ ... }` bodies, each directive body and clause (`@else`, `@empty`,
|
|
25417
|
+
* `@case`, `@catch`, `@pending`), multi-line elements and `<style>` blocks, objects, arrays,
|
|
25418
|
+
* multi-line calls, template strings, groups of imports, comments and `// #region` markers.
|
|
25419
|
+
* While the source does not parse, folds follow indentation and region markers.
|
|
25420
|
+
* @param {string} text
|
|
25421
|
+
* @param {string} file_name
|
|
25422
|
+
* @returns {FoldingRange[]}
|
|
25423
|
+
*/
|
|
25424
|
+
function collect_folding_ranges(text, file_name) {
|
|
25425
|
+
const line_starts = [0];
|
|
25426
|
+
for (const match of text.matchAll(/\r\n|\r|\n/g)) line_starts.push(
|
|
25427
|
+
/** @type {number} */
|
|
25428
|
+
match.index + match[0].length
|
|
25429
|
+
);
|
|
25430
|
+
/** @param {number} offset */
|
|
25431
|
+
const line_of = (offset) => {
|
|
25432
|
+
let low = 0;
|
|
25433
|
+
let high = line_starts.length - 1;
|
|
25434
|
+
while (low < high) {
|
|
25435
|
+
const middle = low + high + 1 >> 1;
|
|
25436
|
+
if (line_starts[middle] <= offset) low = middle;
|
|
25437
|
+
else high = middle - 1;
|
|
25438
|
+
}
|
|
25439
|
+
return low;
|
|
25440
|
+
};
|
|
25441
|
+
/**
|
|
25442
|
+
* The start of each comment, by the offset where it ends, and its end by its start.
|
|
25443
|
+
* @type {Map<number, number>}
|
|
25444
|
+
*/
|
|
25445
|
+
const comment_starts = /* @__PURE__ */ new Map();
|
|
25446
|
+
/** @type {Map<number, number>} */
|
|
25447
|
+
const comment_ends = /* @__PURE__ */ new Map();
|
|
25448
|
+
/**
|
|
25449
|
+
* The offset of the first `character` from `offset` on, outside comments, or -1.
|
|
25450
|
+
* @param {string} character
|
|
25451
|
+
* @param {number} offset
|
|
25452
|
+
*/
|
|
25453
|
+
const find_after = (character, offset) => {
|
|
25454
|
+
let index = offset;
|
|
25455
|
+
while (index < text.length) {
|
|
25456
|
+
const comment_end = comment_ends.get(index);
|
|
25457
|
+
if (comment_end !== void 0) index = comment_end;
|
|
25458
|
+
else if (text[index] === character) return index;
|
|
25459
|
+
else index++;
|
|
25460
|
+
}
|
|
25461
|
+
return -1;
|
|
25462
|
+
};
|
|
25463
|
+
/**
|
|
25464
|
+
* The line of the token before `offset`, past blanks and comments, where a block opened on
|
|
25465
|
+
* a line of its own still folds from the line that opens it.
|
|
25466
|
+
* @param {number} offset
|
|
25467
|
+
*/
|
|
25468
|
+
const previous_token_line = (offset) => {
|
|
25469
|
+
let index = offset - 1;
|
|
25470
|
+
while (index > 0) {
|
|
25471
|
+
const comment_start = comment_starts.get(index + 1);
|
|
25472
|
+
if (comment_start !== void 0) index = comment_start - 1;
|
|
25473
|
+
else if (/\s/.test(text[index])) index--;
|
|
25474
|
+
else break;
|
|
25475
|
+
}
|
|
25476
|
+
return line_of(Math.max(index, 0));
|
|
25477
|
+
};
|
|
25478
|
+
/** @type {FoldingRange[]} */
|
|
25479
|
+
const ranges = [];
|
|
25480
|
+
/**
|
|
25481
|
+
* @param {number} start_line
|
|
25482
|
+
* @param {number} end Offset after the last folded character.
|
|
25483
|
+
* @param {FoldingRange['kind']} [kind] Comment and region folds end where their text ends.
|
|
25484
|
+
*/
|
|
25485
|
+
const fold = (start_line, end, kind) => {
|
|
25486
|
+
let end_line = line_of(end - 1);
|
|
25487
|
+
if (!kind && CLOSING_CHARACTERS.has(text[end - 1])) end_line--;
|
|
25488
|
+
if (end_line > start_line) ranges.push(kind ? {
|
|
25489
|
+
startLine: start_line,
|
|
25490
|
+
endLine: end_line,
|
|
25491
|
+
kind
|
|
25492
|
+
} : {
|
|
25493
|
+
startLine: start_line,
|
|
25494
|
+
endLine: end_line
|
|
25495
|
+
});
|
|
25496
|
+
};
|
|
25497
|
+
/** @type {AST.CommentWithLocation[]} */
|
|
25498
|
+
const comments = [];
|
|
25499
|
+
/** @type {AST.Program} */
|
|
25500
|
+
let ast;
|
|
25501
|
+
try {
|
|
25502
|
+
ast = (0, _tsrx_core.parseModule)(text, file_name, {
|
|
25503
|
+
loose: true,
|
|
25504
|
+
preserveParens: true,
|
|
25505
|
+
comments
|
|
25506
|
+
});
|
|
25507
|
+
} catch {
|
|
25508
|
+
return merge_folding_ranges(fallback_folding_ranges(text));
|
|
25509
|
+
}
|
|
25510
|
+
for (const comment of comments) {
|
|
25511
|
+
comment_starts.set(comment.end, comment.start);
|
|
25512
|
+
comment_ends.set(comment.start, comment.end);
|
|
25513
|
+
}
|
|
25514
|
+
/**
|
|
25515
|
+
* @param {any} node
|
|
25516
|
+
* @param {any} parent
|
|
25517
|
+
*/
|
|
25518
|
+
const visit = (node, parent) => {
|
|
25519
|
+
switch (node.type) {
|
|
25520
|
+
case "Program":
|
|
25521
|
+
fold_import_groups(node.body);
|
|
25522
|
+
break;
|
|
25523
|
+
case "BlockStatement":
|
|
25524
|
+
case "JSXCodeBlock":
|
|
25525
|
+
if (FUNCTION_TYPES.has(parent?.type) && parent.body === node) fold(function_start_line(parent), node.end);
|
|
25526
|
+
else if (ATTACHED_BLOCK_PARENTS.has(parent?.type)) fold(previous_token_line(node.start), node.end);
|
|
25527
|
+
else fold(line_of(node.start), node.end);
|
|
25528
|
+
break;
|
|
25529
|
+
case "ClassBody":
|
|
25530
|
+
case "TSInterfaceBody":
|
|
25531
|
+
case "TSEnumBody":
|
|
25532
|
+
case "TSModuleBlock":
|
|
25533
|
+
fold(previous_token_line(node.start), node.end);
|
|
25534
|
+
break;
|
|
25535
|
+
case "SwitchStatement":
|
|
25536
|
+
case "JSXSwitchExpression":
|
|
25537
|
+
fold(previous_token_line(find_after("{", node.discriminant.end)), node.end);
|
|
25538
|
+
break;
|
|
25539
|
+
case "StaticBlock":
|
|
25540
|
+
fold(line_of(find_after("{", node.start)), node.end);
|
|
25541
|
+
break;
|
|
25542
|
+
case "SwitchCase":
|
|
25543
|
+
if (Array.isArray(node.consequent) && node.consequent.length > 0) fold(line_of(node.test?.end ?? node.start), node.consequent.at(-1).end);
|
|
25544
|
+
break;
|
|
25545
|
+
case "ObjectExpression":
|
|
25546
|
+
case "ArrayExpression":
|
|
25547
|
+
case "ObjectPattern":
|
|
25548
|
+
case "ArrayPattern":
|
|
25549
|
+
case "TSTypeLiteral":
|
|
25550
|
+
case "TSTupleType":
|
|
25551
|
+
fold(parent?.type === "ArrayExpression" || parent?.type === "CallExpression" ? line_of(node.start) : previous_token_line(node.start), node.end);
|
|
25552
|
+
break;
|
|
25553
|
+
case "CallExpression":
|
|
25554
|
+
if (node.arguments.length > 0) fold(previous_token_line(find_after("(", node.typeArguments?.end ?? node.callee.end)), node.end);
|
|
25555
|
+
break;
|
|
25556
|
+
case "ArrowFunctionExpression":
|
|
25557
|
+
if (node.body.type !== "BlockStatement" && node.body.type !== "JSXCodeBlock" && node.body.type !== "ParenthesizedExpression") fold(previous_token_line(node.body.start), node.body.end);
|
|
25558
|
+
break;
|
|
25559
|
+
case "ImportDeclaration":
|
|
25560
|
+
case "ExportNamedDeclaration":
|
|
25561
|
+
case "ExportAllDeclaration":
|
|
25562
|
+
fold_braces((node.specifiers ?? []).filter((specifier) => specifier.type === "ImportSpecifier" || specifier.type === "ExportSpecifier"));
|
|
25563
|
+
fold_braces(node.attributes ?? []);
|
|
25564
|
+
break;
|
|
25565
|
+
case "JSXOpeningElement":
|
|
25566
|
+
if (node.attributes.length > 0) fold(line_of(node.attributes[0].start), node.attributes.at(-1).end);
|
|
25567
|
+
break;
|
|
25568
|
+
case "JSXElement":
|
|
25569
|
+
case "JSXStyleElement":
|
|
25570
|
+
if (node.closingElement) fold(line_of(node.start), node.end);
|
|
25571
|
+
break;
|
|
25572
|
+
case "TemplateLiteral":
|
|
25573
|
+
case "ParenthesizedExpression":
|
|
25574
|
+
case "JSXFragment": fold(line_of(node.start), node.end);
|
|
25575
|
+
}
|
|
25576
|
+
for (const key in node) {
|
|
25577
|
+
if (SKIPPED_KEYS.has(key)) continue;
|
|
25578
|
+
const value = node[key];
|
|
25579
|
+
if (Array.isArray(value)) {
|
|
25580
|
+
for (const child of value) if (is_node(child)) visit(child, node);
|
|
25581
|
+
} else if (is_node(value)) visit(value, node);
|
|
25582
|
+
}
|
|
25583
|
+
};
|
|
25584
|
+
/**
|
|
25585
|
+
* A function folds from its `(` when its parameters span lines, else from its body's `{`.
|
|
25586
|
+
* @param {any} node
|
|
25587
|
+
*/
|
|
25588
|
+
const function_start_line = (node) => {
|
|
25589
|
+
if (node.params.length > 0) {
|
|
25590
|
+
const open = previous_token_line(node.params[0].start);
|
|
25591
|
+
if (open !== line_of(node.params.at(-1).end)) return open;
|
|
25592
|
+
}
|
|
25593
|
+
return previous_token_line(node.body.start);
|
|
25594
|
+
};
|
|
25595
|
+
/**
|
|
25596
|
+
* Two or more imports in a row fold together.
|
|
25597
|
+
* @param {AST.Node[]} statements
|
|
25598
|
+
*/
|
|
25599
|
+
const fold_import_groups = (statements) => {
|
|
25600
|
+
let first = 0;
|
|
25601
|
+
while (first < statements.length) {
|
|
25602
|
+
let last = first;
|
|
25603
|
+
while (last < statements.length && is_import(statements[last])) last++;
|
|
25604
|
+
if (last - first > 1) fold(
|
|
25605
|
+
line_of(
|
|
25606
|
+
/** @type {any} */
|
|
25607
|
+
statements[first].start
|
|
25608
|
+
),
|
|
25609
|
+
/** @type {any} */
|
|
25610
|
+
statements[last - 1].end,
|
|
25611
|
+
"imports"
|
|
25612
|
+
);
|
|
25613
|
+
first = last + 1;
|
|
25614
|
+
}
|
|
25615
|
+
};
|
|
25616
|
+
/**
|
|
25617
|
+
* The braces around `elements`: the names of `import { a, b } from` and `export { a, b }`,
|
|
25618
|
+
* and import attributes (`with { type: 'json' }`).
|
|
25619
|
+
* @param {any[]} elements
|
|
25620
|
+
*/
|
|
25621
|
+
const fold_braces = (elements) => {
|
|
25622
|
+
if (elements.length === 0) return;
|
|
25623
|
+
const close = find_after("}", elements.at(-1).end);
|
|
25624
|
+
if (close !== -1) fold(previous_token_line(elements[0].start), close + 1);
|
|
25625
|
+
};
|
|
25626
|
+
visit(ast, null);
|
|
25627
|
+
fold_comments(comments, text, line_of, (offset) => /^[ \t]*$/.test(text.slice(line_starts[line_of(offset)], offset)), fold);
|
|
25628
|
+
return merge_folding_ranges(ranges);
|
|
25629
|
+
}
|
|
25630
|
+
/**
|
|
25631
|
+
* Multi-line block comments, runs of two or more line comments each on a line of its own,
|
|
25632
|
+
* and `// #region` ... `// #endregion` pairs.
|
|
25633
|
+
* @param {AST.CommentWithLocation[]} comments
|
|
25634
|
+
* @param {string} text
|
|
25635
|
+
* @param {(offset: number) => number} line_of
|
|
25636
|
+
* @param {(offset: number) => boolean} first_on_line Whether only blanks precede `offset` on
|
|
25637
|
+
* its line.
|
|
25638
|
+
* @param {(start_line: number, end: number, kind: FoldingRange['kind']) => void} fold
|
|
25639
|
+
*/
|
|
25640
|
+
function fold_comments(comments, text, line_of, first_on_line, fold) {
|
|
25641
|
+
/** @type {number[]} */
|
|
25642
|
+
const regions = [];
|
|
25643
|
+
/** @type {AST.CommentWithLocation | null} */
|
|
25644
|
+
let first = null;
|
|
25645
|
+
/** @type {AST.CommentWithLocation | null} */
|
|
25646
|
+
let last = null;
|
|
25647
|
+
const end_run = () => {
|
|
25648
|
+
if (first && last && first !== last) fold(line_of(first.start), last.end, "comment");
|
|
25649
|
+
first = last = null;
|
|
25650
|
+
};
|
|
25651
|
+
for (const comment of comments) {
|
|
25652
|
+
const own_line = comment.type === "Line" && first_on_line(comment.start);
|
|
25653
|
+
const region = own_line ? REGION_MARKER.exec(comment.value.trim()) : null;
|
|
25654
|
+
if (region || !own_line || last && /\S/.test(text.slice(last.end, comment.start))) end_run();
|
|
25655
|
+
if (region) {
|
|
25656
|
+
if (!region[1]) regions.push(line_of(comment.start));
|
|
25657
|
+
else if (regions.length > 0) fold(regions.pop(), comment.end, "region");
|
|
25658
|
+
} else if (own_line) {
|
|
25659
|
+
first ??= comment;
|
|
25660
|
+
last = comment;
|
|
25661
|
+
} else if (comment.type === "Block") fold(line_of(comment.start), comment.end, "comment");
|
|
25662
|
+
}
|
|
25663
|
+
end_run();
|
|
25664
|
+
}
|
|
25665
|
+
/**
|
|
25666
|
+
* Folds by indentation, the way VS Code folds a file no provider folds, plus region markers.
|
|
25667
|
+
* @param {string} text
|
|
25668
|
+
* @returns {FoldingRange[]}
|
|
25669
|
+
*/
|
|
25670
|
+
function fallback_folding_ranges(text) {
|
|
25671
|
+
const lines = text.split(/\r\n|\r|\n/);
|
|
25672
|
+
/** @type {FoldingRange[]} */
|
|
25673
|
+
const ranges = [];
|
|
25674
|
+
/** @type {Array<{ indent: number, end_above: number }>} */
|
|
25675
|
+
const open = [{
|
|
25676
|
+
indent: -1,
|
|
25677
|
+
end_above: lines.length
|
|
25678
|
+
}];
|
|
25679
|
+
for (let line = lines.length - 1; line >= 0; line--) {
|
|
25680
|
+
const indent = indent_of(lines[line]);
|
|
25681
|
+
if (indent === -1) continue;
|
|
25682
|
+
let previous = open[open.length - 1];
|
|
25683
|
+
if (previous.indent > indent) {
|
|
25684
|
+
do {
|
|
25685
|
+
open.pop();
|
|
25686
|
+
previous = open[open.length - 1];
|
|
25687
|
+
} while (previous.indent > indent);
|
|
25688
|
+
if (previous.end_above - 1 > line) ranges.push({
|
|
25689
|
+
startLine: line,
|
|
25690
|
+
endLine: previous.end_above - 1
|
|
25691
|
+
});
|
|
25692
|
+
}
|
|
25693
|
+
if (previous.indent === indent) previous.end_above = line;
|
|
25694
|
+
else open.push({
|
|
25695
|
+
indent,
|
|
25696
|
+
end_above: line
|
|
25697
|
+
});
|
|
25698
|
+
}
|
|
25699
|
+
/** @type {number[]} */
|
|
25700
|
+
const regions = [];
|
|
25701
|
+
for (const [line, content] of lines.entries()) {
|
|
25702
|
+
const region = /^\s*\/\/(.*)$/.exec(content);
|
|
25703
|
+
const marker = region && REGION_MARKER.exec(region[1].trim());
|
|
25704
|
+
if (!marker) continue;
|
|
25705
|
+
if (!marker[1]) regions.push(line);
|
|
25706
|
+
else if (regions.length > 0) {
|
|
25707
|
+
const start = regions.pop();
|
|
25708
|
+
if (line > start) ranges.push({
|
|
25709
|
+
startLine: start,
|
|
25710
|
+
endLine: line,
|
|
25711
|
+
kind: "region"
|
|
25712
|
+
});
|
|
25713
|
+
}
|
|
25714
|
+
}
|
|
25715
|
+
return ranges;
|
|
25716
|
+
}
|
|
25717
|
+
/**
|
|
25718
|
+
* The width of a line's indentation, tabs counting to the next multiple of 4, or -1 for a
|
|
25719
|
+
* blank line.
|
|
25720
|
+
* @param {string} line
|
|
25721
|
+
*/
|
|
25722
|
+
function indent_of(line) {
|
|
25723
|
+
let width = 0;
|
|
25724
|
+
for (const character of line) if (character === " ") width++;
|
|
25725
|
+
else if (character === " ") width += 4 - width % 4;
|
|
25726
|
+
else return width;
|
|
25727
|
+
return -1;
|
|
25728
|
+
}
|
|
25729
|
+
/**
|
|
25730
|
+
* Sorted by line, one fold per first line: the one that reaches furthest, which is the one an
|
|
25731
|
+
* editor that keeps a single fold per line keeps for TSX.
|
|
25732
|
+
* @param {FoldingRange[]} ranges
|
|
25733
|
+
* @returns {FoldingRange[]}
|
|
25734
|
+
*/
|
|
25735
|
+
function merge_folding_ranges(ranges) {
|
|
25736
|
+
const sorted = [...ranges].sort((a, b) => a.startLine - b.startLine || b.endLine - a.endLine);
|
|
25737
|
+
return sorted.filter((range, index) => index === 0 || sorted[index - 1].startLine !== range.startLine);
|
|
25738
|
+
}
|
|
25739
|
+
/**
|
|
25740
|
+
* @param {unknown} value
|
|
25741
|
+
* @returns {boolean}
|
|
25742
|
+
*/
|
|
25743
|
+
function is_node(value) {
|
|
25744
|
+
return !!value && typeof value === "object" && typeof value.type === "string" && typeof value.start === "number";
|
|
25745
|
+
}
|
|
25746
|
+
/**
|
|
25747
|
+
* @param {AST.Node} statement
|
|
25748
|
+
* @returns {boolean}
|
|
25749
|
+
*/
|
|
25750
|
+
function is_import(statement) {
|
|
25751
|
+
return statement.type === "ImportDeclaration" || statement.type === "TSImportEqualsDeclaration";
|
|
25752
|
+
}
|
|
25753
|
+
|
|
25114
25754
|
//#endregion
|
|
25115
25755
|
//#region src/workspaceState.js
|
|
25756
|
+
/** Configs and package state, which every backend reacts to (`classifyWorkspaceChanges`). */
|
|
25757
|
+
const CONFIG_AND_PACKAGE_STATE_PATTERNS = [
|
|
25758
|
+
"**/*.json",
|
|
25759
|
+
"**/pnpm-lock.yaml",
|
|
25760
|
+
"**/pnpm-workspace.yaml",
|
|
25761
|
+
"**/yarn.lock",
|
|
25762
|
+
"**/bun.lock",
|
|
25763
|
+
"**/bun.lockb",
|
|
25764
|
+
"**/node_modules/.modules.yaml",
|
|
25765
|
+
"**/node_modules/.package-lock.json",
|
|
25766
|
+
"**/node_modules/.yarn-state.yml",
|
|
25767
|
+
"**/node_modules/.yarn-integrity"
|
|
25768
|
+
];
|
|
25116
25769
|
const WORKSPACE_FILE_PATTERNS = [
|
|
25117
25770
|
"**/*.tsrx",
|
|
25118
25771
|
"**/*.ts",
|
|
@@ -25123,13 +25776,44 @@ const WORKSPACE_FILE_PATTERNS = [
|
|
|
25123
25776
|
"**/*.jsx",
|
|
25124
25777
|
"**/*.cjs",
|
|
25125
25778
|
"**/*.mjs",
|
|
25126
|
-
|
|
25127
|
-
"**/pnpm-lock.yaml",
|
|
25128
|
-
"**/pnpm-workspace.yaml",
|
|
25129
|
-
"**/yarn.lock",
|
|
25130
|
-
"**/bun.lock",
|
|
25131
|
-
"**/bun.lockb"
|
|
25779
|
+
...CONFIG_AND_PACKAGE_STATE_PATTERNS
|
|
25132
25780
|
];
|
|
25781
|
+
/**
|
|
25782
|
+
* The files to watch on a backend. Only the classic backend hosts a TypeScript
|
|
25783
|
+
* project, which needs the TypeScript and JavaScript source events. On the other
|
|
25784
|
+
* backends the editor's TypeScript reads those files, and watching them in a large
|
|
25785
|
+
* workspace only floods the server with events from build output and dev servers.
|
|
25786
|
+
* @param {import('./backend.js').TypeScriptBackend} backend
|
|
25787
|
+
* @returns {string[]}
|
|
25788
|
+
*/
|
|
25789
|
+
function getWorkspaceFilePatterns(backend) {
|
|
25790
|
+
return backend === "classic" ? WORKSPACE_FILE_PATTERNS : ["**/*.tsrx", ...CONFIG_AND_PACKAGE_STATE_PATTERNS];
|
|
25791
|
+
}
|
|
25792
|
+
/**
|
|
25793
|
+
* Directories that installs, dev servers and builds write, such as Vite's
|
|
25794
|
+
* `node_modules/.vite/deps/package.json` or Next.js's `.next/package.json`. No
|
|
25795
|
+
* project the TSRX compiler resolves from lives in one. Keep in sync with
|
|
25796
|
+
* `file-events.js` in the VS Code extension, which drops the same events.
|
|
25797
|
+
*/
|
|
25798
|
+
const GENERATED_DIRECTORY_NAMES = /* @__PURE__ */ new Set([
|
|
25799
|
+
"node_modules",
|
|
25800
|
+
".next",
|
|
25801
|
+
".nuxt",
|
|
25802
|
+
".output",
|
|
25803
|
+
".svelte-kit",
|
|
25804
|
+
".turbo",
|
|
25805
|
+
".vercel"
|
|
25806
|
+
]);
|
|
25807
|
+
/**
|
|
25808
|
+
* Files that pnpm, npm, Yarn (node-modules linker) and Yarn 1 write directly in
|
|
25809
|
+
* `node_modules` at the end of every install.
|
|
25810
|
+
*/
|
|
25811
|
+
const INSTALL_MARKER_FILE_NAMES = /* @__PURE__ */ new Set([
|
|
25812
|
+
".modules.yaml",
|
|
25813
|
+
".package-lock.json",
|
|
25814
|
+
".yarn-state.yml",
|
|
25815
|
+
".yarn-integrity"
|
|
25816
|
+
]);
|
|
25133
25817
|
const PACKAGE_STATE_FILE_NAMES = /* @__PURE__ */ new Set([
|
|
25134
25818
|
"package.json",
|
|
25135
25819
|
"package-lock.json",
|
|
@@ -25159,6 +25843,39 @@ function isPackageStateFile(file_name) {
|
|
|
25159
25843
|
return PACKAGE_STATE_FILE_NAMES.has(node_path.default.basename(file_name).toLowerCase());
|
|
25160
25844
|
}
|
|
25161
25845
|
/**
|
|
25846
|
+
* The path segments of a file, relative to the workspace folder that holds it, so a
|
|
25847
|
+
* workspace opened inside a `node_modules` folder keeps its own events.
|
|
25848
|
+
* @param {string} file_name
|
|
25849
|
+
* @param {readonly string[]} workspace_folders
|
|
25850
|
+
*/
|
|
25851
|
+
function workspaceRelativeSegments(file_name, workspace_folders) {
|
|
25852
|
+
const normalized = normalizeFileName(file_name);
|
|
25853
|
+
let relative = normalized;
|
|
25854
|
+
for (const folder of workspace_folders) {
|
|
25855
|
+
const normalized_folder = normalizeFileName(folder).replace(/[\\/]+$/, "");
|
|
25856
|
+
if (normalized.startsWith(normalized_folder) && /[\\/]/.test(normalized[normalized_folder.length] ?? "") && normalized.length - normalized_folder.length - 1 < relative.length) relative = normalized.slice(normalized_folder.length + 1);
|
|
25857
|
+
}
|
|
25858
|
+
return relative.split(/[\\/]/);
|
|
25859
|
+
}
|
|
25860
|
+
/**
|
|
25861
|
+
* Whether a file under `node_modules` shows that an install finished: an install
|
|
25862
|
+
* marker, or the manifest of a package installed directly in a `node_modules`
|
|
25863
|
+
* folder (`node_modules/<name>/package.json`, `node_modules/@scope/<name>/package.json`),
|
|
25864
|
+
* which npm and Bun write for each package they install. The lockfile is not enough:
|
|
25865
|
+
* `git pull` can change it before the install that changes the TSRX compiler. A
|
|
25866
|
+
* `node_modules` inside build output (`.output/server/node_modules`,
|
|
25867
|
+
* `.next/standalone/node_modules`) is a copy a build writes, not an install.
|
|
25868
|
+
* @param {readonly string[]} segments Path segments relative to the workspace folder.
|
|
25869
|
+
*/
|
|
25870
|
+
function isInstallStateFile(segments) {
|
|
25871
|
+
const index = segments.indexOf("node_modules");
|
|
25872
|
+
if (index === -1 || segments.includes("node_modules", index + 1) || segments.slice(0, index).some((segment) => GENERATED_DIRECTORY_NAMES.has(segment))) return false;
|
|
25873
|
+
const rest = segments.slice(index + 1);
|
|
25874
|
+
if (rest.length === 1) return INSTALL_MARKER_FILE_NAMES.has(rest[0]);
|
|
25875
|
+
const name = rest.slice(0, rest[0]?.startsWith("@") ? 2 : 1);
|
|
25876
|
+
return rest.length === name.length + 1 && rest[rest.length - 1] === "package.json" && name.every((segment) => !segment.startsWith("."));
|
|
25877
|
+
}
|
|
25878
|
+
/**
|
|
25162
25879
|
* @param {string} file_name
|
|
25163
25880
|
*/
|
|
25164
25881
|
function normalizeFileName(file_name) {
|
|
@@ -25191,11 +25908,16 @@ function trackTypeScriptConfigDependencies(config_files, project) {
|
|
|
25191
25908
|
/**
|
|
25192
25909
|
* Classify watched changes before mutating project state. Package changes need
|
|
25193
25910
|
* a process restart because Node does not expose a supported way to evict a
|
|
25194
|
-
* loaded ESM compiler and its transitive module graph.
|
|
25911
|
+
* loaded ESM compiler and its transitive module graph. A file in a generated
|
|
25912
|
+
* directory restarts the server only when it shows that an install finished
|
|
25913
|
+
* (`isInstallStateFile`), and reloads projects only when a project loaded it as a
|
|
25914
|
+
* config: dev servers rewrite such files all the time, and restarting on each one
|
|
25915
|
+
* kept a large workspace restarting the server.
|
|
25195
25916
|
* @param {import('@volar/language-server').FileEvent[]} changes
|
|
25196
25917
|
* @param {ReadonlySet<string>} [tracked_config_files]
|
|
25918
|
+
* @param {readonly string[]} [workspace_folders] File system paths of the workspace folders.
|
|
25197
25919
|
*/
|
|
25198
|
-
function classifyWorkspaceChanges(changes, tracked_config_files = /* @__PURE__ */ new Set()) {
|
|
25920
|
+
function classifyWorkspaceChanges(changes, tracked_config_files = /* @__PURE__ */ new Set(), workspace_folders = []) {
|
|
25199
25921
|
let reloadProjects = false;
|
|
25200
25922
|
let restartLanguageServer = false;
|
|
25201
25923
|
/** @type {Set<string>} */
|
|
@@ -25203,8 +25925,10 @@ function classifyWorkspaceChanges(changes, tracked_config_files = /* @__PURE__ *
|
|
|
25203
25925
|
for (const change of changes) {
|
|
25204
25926
|
const uri = vscode_uri.URI.parse(change.uri);
|
|
25205
25927
|
const file_name = uri.scheme === "file" ? uri.fsPath : uri.path;
|
|
25206
|
-
|
|
25207
|
-
|
|
25928
|
+
const segments = workspaceRelativeSegments(file_name, workspace_folders);
|
|
25929
|
+
const generated = segments.some((segment) => GENERATED_DIRECTORY_NAMES.has(segment));
|
|
25930
|
+
if (!generated && isTypeScriptConfigFile(file_name) || tracked_config_files.has(normalizeFileName(file_name))) reloadProjects = true;
|
|
25931
|
+
if (generated ? isInstallStateFile(segments) : isPackageStateFile(file_name)) restartLanguageServer = true;
|
|
25208
25932
|
else if (isTypeDefinitionFile(file_name)) changedTypeDefinitions.add(file_name);
|
|
25209
25933
|
}
|
|
25210
25934
|
return {
|
|
@@ -25214,6 +25938,32 @@ function classifyWorkspaceChanges(changes, tracked_config_files = /* @__PURE__ *
|
|
|
25214
25938
|
};
|
|
25215
25939
|
}
|
|
25216
25940
|
/**
|
|
25941
|
+
* Run `restart` once, after package changes have stopped for `delay` ms, so a burst
|
|
25942
|
+
* of them, such as an install, restarts the server once; or `max_delay` ms after
|
|
25943
|
+
* the first change at the latest, so a steady stream cannot hold it off.
|
|
25944
|
+
* @param {() => void} restart
|
|
25945
|
+
* @param {number} [delay]
|
|
25946
|
+
* @param {number} [max_delay]
|
|
25947
|
+
* @returns {() => void} Call on each change that needs a restart.
|
|
25948
|
+
*/
|
|
25949
|
+
function createRestartScheduler(restart, delay = 1e3, max_delay = 1e4) {
|
|
25950
|
+
/** @type {ReturnType<typeof setTimeout> | undefined} */
|
|
25951
|
+
let timer;
|
|
25952
|
+
/** @type {number | undefined} */
|
|
25953
|
+
let first_change;
|
|
25954
|
+
let restarted = false;
|
|
25955
|
+
return () => {
|
|
25956
|
+
if (restarted) return;
|
|
25957
|
+
const now = Date.now();
|
|
25958
|
+
first_change ??= now;
|
|
25959
|
+
clearTimeout(timer);
|
|
25960
|
+
timer = setTimeout(() => {
|
|
25961
|
+
restarted = true;
|
|
25962
|
+
restart();
|
|
25963
|
+
}, Math.min(delay, first_change + max_delay - now));
|
|
25964
|
+
};
|
|
25965
|
+
}
|
|
25966
|
+
/**
|
|
25217
25967
|
* @param {import('@volar/language-server').FileEvent[]} changes
|
|
25218
25968
|
* @param {{
|
|
25219
25969
|
* restartLanguageServer: () => void,
|
|
@@ -25223,9 +25973,10 @@ function classifyWorkspaceChanges(changes, tracked_config_files = /* @__PURE__ *
|
|
|
25223
25973
|
* invalidateTypeDefinitions: (file_name?: string) => void,
|
|
25224
25974
|
* }} hooks
|
|
25225
25975
|
* @param {ReadonlySet<string>} [tracked_config_files]
|
|
25976
|
+
* @param {readonly string[]} [workspace_folders]
|
|
25226
25977
|
*/
|
|
25227
|
-
function handleWorkspaceChanges(changes, hooks, tracked_config_files) {
|
|
25228
|
-
const effects = classifyWorkspaceChanges(changes, tracked_config_files);
|
|
25978
|
+
function handleWorkspaceChanges(changes, hooks, tracked_config_files, workspace_folders) {
|
|
25979
|
+
const effects = classifyWorkspaceChanges(changes, tracked_config_files, workspace_folders);
|
|
25229
25980
|
if (effects.restartLanguageServer) {
|
|
25230
25981
|
hooks.restartLanguageServer();
|
|
25231
25982
|
return effects;
|
|
@@ -25266,6 +26017,7 @@ function createTsrxLanguageServer(options = {}) {
|
|
|
25266
26017
|
const server = (0, import_node.createServer)(connection);
|
|
25267
26018
|
register_formatting(connection, (uri) => server.documents.get(vscode_uri.URI.parse(uri)));
|
|
25268
26019
|
register_closing_tags(connection, server);
|
|
26020
|
+
register_folding_ranges(connection, server);
|
|
25269
26021
|
connection.listen();
|
|
25270
26022
|
/** @type {WeakSet<Function>} */
|
|
25271
26023
|
const wrappedFunctions = /* @__PURE__ */ new WeakSet();
|
|
@@ -25273,8 +26025,9 @@ function createTsrxLanguageServer(options = {}) {
|
|
|
25273
26025
|
const trackedTypeScriptConfigFiles = /* @__PURE__ */ new Set();
|
|
25274
26026
|
/** @type {Set<Set<string>>} */
|
|
25275
26027
|
const compilerResolutionDependencySets = /* @__PURE__ */ new Set();
|
|
25276
|
-
let restartScheduled = false;
|
|
25277
26028
|
let clientRestarts = false;
|
|
26029
|
+
/** @type {import('./backend.js').TypeScriptBackend} */
|
|
26030
|
+
let activeBackend = "classic";
|
|
25278
26031
|
/**
|
|
25279
26032
|
* Shown once the client is initialized, each as its own warning: the classic
|
|
25280
26033
|
* backend skipped the `typescript.tsdk` option, or did not find a `typescript`
|
|
@@ -25283,14 +26036,13 @@ function createTsrxLanguageServer(options = {}) {
|
|
|
25283
26036
|
*/
|
|
25284
26037
|
const typescriptNotices = [];
|
|
25285
26038
|
/**
|
|
25286
|
-
* Restart the process so Node drops the complete ESM compiler graph
|
|
25287
|
-
*
|
|
25288
|
-
* server
|
|
25289
|
-
* "Cannot call write after a stream
|
|
26039
|
+
* Restart the process so Node drops the complete ESM compiler graph, once
|
|
26040
|
+
* package state has settled (`createRestartScheduler`). A client that restarts
|
|
26041
|
+
* the server itself stops sending first. When the server exits by itself, the
|
|
26042
|
+
* client's next message fails (VS Code showed "Cannot call write after a stream
|
|
26043
|
+
* was destroyed").
|
|
25290
26044
|
*/
|
|
25291
|
-
|
|
25292
|
-
if (restartScheduled) return;
|
|
25293
|
-
restartScheduled = true;
|
|
26045
|
+
const restartLanguageServer = createRestartScheduler(() => {
|
|
25294
26046
|
if (clientRestarts) {
|
|
25295
26047
|
log("Asking the client to restart the server after package state changed.");
|
|
25296
26048
|
connection.sendNotification(RESTART_NOTIFICATION);
|
|
@@ -25298,7 +26050,7 @@ function createTsrxLanguageServer(options = {}) {
|
|
|
25298
26050
|
}
|
|
25299
26051
|
log("Restarting after package state changed.");
|
|
25300
26052
|
setTimeout(() => process.exit(0), 50);
|
|
25301
|
-
}
|
|
26053
|
+
});
|
|
25302
26054
|
/**
|
|
25303
26055
|
* Ensure TypeScript hosts always see TSRX compiler defaults.
|
|
25304
26056
|
* @param {unknown} target
|
|
@@ -25375,6 +26127,7 @@ function createTsrxLanguageServer(options = {}) {
|
|
|
25375
26127
|
}
|
|
25376
26128
|
for (const notice of typescriptNotices) logError(notice);
|
|
25377
26129
|
}
|
|
26130
|
+
activeBackend = backend;
|
|
25378
26131
|
if (ts === void 0) {
|
|
25379
26132
|
const compilerResolutionDependencies = /* @__PURE__ */ new Set();
|
|
25380
26133
|
compilerResolutionDependencySets.add(compilerResolutionDependencies);
|
|
@@ -25432,10 +26185,10 @@ function createTsrxLanguageServer(options = {}) {
|
|
|
25432
26185
|
server.project.reload();
|
|
25433
26186
|
},
|
|
25434
26187
|
requestRefresh: (clearDiagnostics) => server.languageFeatures.requestRefresh(clearDiagnostics)
|
|
25435
|
-
}, trackedTypeScriptConfigFiles).reloadProjects) log("Reloaded TypeScript projects after workspace configuration changed.");
|
|
26188
|
+
}, trackedTypeScriptConfigFiles, server.workspaceFolders.all.filter((folder) => folder.scheme === "file").map((folder) => folder.fsPath)).reloadProjects) log("Reloaded TypeScript projects after workspace configuration changed.");
|
|
25436
26189
|
});
|
|
25437
26190
|
try {
|
|
25438
|
-
await server.fileWatcher.watchFiles(
|
|
26191
|
+
await server.fileWatcher.watchFiles(getWorkspaceFilePatterns(activeBackend));
|
|
25439
26192
|
log("Workspace file watchers registered.");
|
|
25440
26193
|
} catch (err) {
|
|
25441
26194
|
logError("Failed to register file watchers:", err);
|
|
@@ -25454,9 +26207,10 @@ function createTsrxLanguageServer(options = {}) {
|
|
|
25454
26207
|
}
|
|
25455
26208
|
/**
|
|
25456
26209
|
* Advertise what the server's own handlers serve: the formatters `register_formatting`
|
|
25457
|
-
* serves (whole document and range),
|
|
25458
|
-
* serves on `>`, unless the client closes tags another
|
|
25459
|
-
* No Volar service plugin advertises
|
|
26210
|
+
* serves (whole document and range), the folds `register_folding_ranges` serves, and the
|
|
26211
|
+
* closing tags `register_closing_tags` serves on `>`, unless the client closes tags another
|
|
26212
|
+
* way (`closes_tags_on_type`). No Volar service plugin advertises any of them
|
|
26213
|
+
* (`stripFormatting`, `stripFoldingRanges`).
|
|
25460
26214
|
* @template {import('@volar/language-server/node').InitializeResult} T
|
|
25461
26215
|
* @param {T} initResult
|
|
25462
26216
|
* @param {import('@volar/language-server/node').InitializeParams} params
|
|
@@ -25465,6 +26219,7 @@ function createTsrxLanguageServer(options = {}) {
|
|
|
25465
26219
|
function with_own_handlers(initResult, params) {
|
|
25466
26220
|
initResult.capabilities.documentFormattingProvider = true;
|
|
25467
26221
|
initResult.capabilities.documentRangeFormattingProvider = true;
|
|
26222
|
+
initResult.capabilities.foldingRangeProvider = true;
|
|
25468
26223
|
if (closes_tags_on_type(params)) initResult.capabilities.documentOnTypeFormattingProvider = CLOSING_TAGS_ON_TYPE;
|
|
25469
26224
|
return initResult;
|
|
25470
26225
|
}
|
|
@@ -25502,4 +26257,4 @@ Object.defineProperty(exports, 'createTsrxLanguageServer', {
|
|
|
25502
26257
|
return createTsrxLanguageServer;
|
|
25503
26258
|
}
|
|
25504
26259
|
});
|
|
25505
|
-
//# sourceMappingURL=server-
|
|
26260
|
+
//# sourceMappingURL=server-ni8rJaUl.js.map
|