@tsrx/language-server 0.6.1 → 0.6.3

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.
package/README.md CHANGED
@@ -47,7 +47,9 @@ none.
47
47
  On the `classic` backend, it uses the first `typescript` it finds:
48
48
 
49
49
  1. The `typescript.tsdk` initialization option, when the editor passes one: the
50
- `lib` folder of a TypeScript installation.
50
+ `lib` folder of a TypeScript installation. The `typescript` package folder
51
+ above it works too. When the folder does not contain TypeScript, the server
52
+ shows a warning that names the folder, and goes on to the next step.
51
53
  2. The project's: `node_modules/typescript` in each open workspace folder and its
52
54
  parent folders, the way Node finds a package. The first folder that has one
53
55
  wins. When the editor names no folder, the server searches from the folder it
@@ -64,10 +66,10 @@ npm install -D typescript
64
66
  pnpm add -D typescript
65
67
  ```
66
68
 
67
- When the server finds no `typescript`, or finds TypeScript 7, it still starts and
68
- shows one warning that says what it found and what to do. `.tsrx` files then get
69
- no type checking, hover or completions. TSRX compile errors, CSS in `<style>`, the
70
- outline, formatting and closing tags still work.
69
+ When the server does not find `typescript`, or finds TypeScript 7, it still starts
70
+ and shows one warning that says what it found and what to do. `.tsrx` files then
71
+ do not get type checking, hover or completions. TSRX compile errors, CSS in
72
+ `<style>`, the outline, formatting and closing tags still work.
71
73
 
72
74
  To use another TypeScript than the one it finds, pass that TypeScript's `lib`
73
75
  folder:
@@ -219,6 +221,44 @@ Other formatters for `.tsrx` files return no edits:
219
221
  In VS Code, TSRX is the default formatter for `.tsrx` files, so neither gets in
220
222
  the way.
221
223
 
224
+ ## Closing tags
225
+
226
+ When you type the `>` that ends an opening tag, the server inserts the closing tag
227
+ after the cursor: `<div>` becomes `<div></div>`. It does not close a void element
228
+ such as `<br>`, a self-closing tag such as `<div />`, or a tag that is already
229
+ closed.
230
+
231
+ Editors ask for the closing tag in one of two ways:
232
+
233
+ - **On-type formatting** (`textDocument/onTypeFormatting`), with `>` as the only
234
+ trigger character. A text edit cannot move the cursor, so the cursor stays
235
+ between the tags only in an editor that keeps it before text inserted at the
236
+ cursor. Zed 1.17 or newer, Neovim and JetBrains IDEs do. The READMEs of the TSRX
237
+ plugins for
238
+ [Zed](https://github.com/tsrx-org/tsrx/tree/main/packages/zed-plugin#closing-tags),
239
+ [Neovim](https://github.com/tsrx-org/tsrx/tree/main/packages/nvim-plugin#closing-tags),
240
+ [Sublime Text](https://github.com/tsrx-org/tsrx/tree/main/packages/sublime-text-plugin#closing-tags)
241
+ and
242
+ [JetBrains IDEs](https://github.com/tsrx-org/tsrx/tree/main/packages/intellij-plugin#closing-tags)
243
+ say what each editor needs.
244
+ - **Volar's `volar/client/autoInsert` request**, which the VS Code extension
245
+ sends. The server answers with a snippet (`$0</div>`) that puts the cursor
246
+ between the tags.
247
+
248
+ To turn closing tags off, set `tsrx.autoClosingTags.enabled` to `false`. The
249
+ server reads it through `workspace/configuration`.
250
+
251
+ An editor that closes tags another way sets the `closeTagsOnType` initialization
252
+ option to `false`. The server then offers no on-type formatting, so the editor
253
+ does not get a second closing tag. The VS Code extension does this, because VS
254
+ Code's TypeScript closes the tags, or on TypeScript 7 the extension sends
255
+ `volar/client/autoInsert`:
256
+
257
+ ```jsonc
258
+ // LSP initialize params
259
+ { "initializationOptions": { "closeTagsOnType": false } }
260
+ ```
261
+
222
262
  ## Restarts after package changes
223
263
 
224
264
  When a `package.json` or a lockfile changes (`pnpm install`, for example), the
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- const require_server = require('./server-BnzVhVsF.js');
2
+ const require_server = require('./server-CpRcmosU.js');
3
3
 
4
4
  //#region src/language-server.js
5
5
  require_server.createTsrxLanguageServer();
@@ -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$3,
6421
+ URI: () => URI$4,
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$3, 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;
6430
+ var DocumentUri, URI$4, 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$3 || (URI$3 = {}));
6445
+ })(URI$4 || (URI$4 = {}));
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$3.is(candidate.uri) && Is.string(candidate.name);
8280
+ return Is.objectLiteral(candidate) && URI$4.is(candidate.uri) && Is.string(candidate.name);
8281
8281
  }
8282
8282
  WorkspaceFolder.is = is;
8283
8283
  })(WorkspaceFolder || (WorkspaceFolder = {}));
@@ -22522,10 +22522,12 @@ function resolve_typescript_backend({ argv = [], initializationOptions } = {}) {
22522
22522
  /**
22523
22523
  * The TypeScript installation the classic backend hosts, from the Volar-style
22524
22524
  * `typescript.tsdk` initialization option: the absolute path of a TypeScript
22525
- * `lib` directory (the one containing `typescript.js`). An editor may pass
22526
- * the TypeScript it runs for the workspace. Without it the server loads the
22527
- * `typescript` package resolvable from its own location (the peer
22528
- * dependency). The VS Code extension uses the plugin backend, which loads none.
22525
+ * `lib` directory (the one containing `typescript.js`), or of the `typescript`
22526
+ * package directory above it. An editor may pass
22527
+ * the TypeScript it runs for the workspace. Without it, or when it names no
22528
+ * TypeScript installation, the server searches the project and then its own
22529
+ * location (`find_typescript`). The VS Code extension uses the plugin backend,
22530
+ * which loads none.
22529
22531
  * @param {unknown} initializationOptions
22530
22532
  * @returns {string | undefined}
22531
22533
  */
@@ -22543,7 +22545,9 @@ function resolve_typescript_tsdk(initializationOptions) {
22543
22545
  * Finding the `typescript` package the classic backend runs, in this order:
22544
22546
  *
22545
22547
  * 1. the `typescript.tsdk` initialization option: an editor's choice, the `lib`
22546
- * directory of a TypeScript installation;
22548
+ * directory of a TypeScript installation or the `typescript` package directory
22549
+ * itself (a folder with neither is skipped, and the server warns with
22550
+ * `tsdk_notice`);
22547
22551
  * 2. the project's own `typescript`: `node_modules/typescript` in each open
22548
22552
  * workspace folder (or, when the client names none, the server's working
22549
22553
  * directory) and its parent folders, as Node resolves a package, the first
@@ -22603,15 +22607,16 @@ function find_typescript_package(from_dir) {
22603
22607
  */
22604
22608
  function find_typescript({ tsdk, workspace_dirs, server_dir }) {
22605
22609
  if (tsdk !== void 0) {
22606
- const lib = node_path.default.resolve(tsdk);
22607
- const dir = node_path.default.dirname(lib);
22608
- const version = package_version(dir);
22609
- if (version !== void 0) return {
22610
- dir: node_fs.default.realpathSync(dir),
22611
- lib,
22612
- version,
22613
- source: "tsdk"
22614
- };
22610
+ const folder = node_path.default.resolve(tsdk);
22611
+ for (const [dir, lib] of [[node_path.default.dirname(folder), folder], [folder, node_path.default.join(folder, "lib")]]) {
22612
+ const version = package_version(dir);
22613
+ if (version !== void 0) return {
22614
+ dir: node_fs.default.realpathSync(dir),
22615
+ lib,
22616
+ version,
22617
+ source: "tsdk"
22618
+ };
22619
+ }
22615
22620
  }
22616
22621
  for (const workspace_dir of workspace_dirs) {
22617
22622
  const found = find_typescript_package(workspace_dir);
@@ -22633,32 +22638,54 @@ function find_typescript({ tsdk, workspace_dirs, server_dir }) {
22633
22638
  function is_usable_typescript(version) {
22634
22639
  return Number.parseInt(version, 10) < 7;
22635
22640
  }
22641
+ /** What the server does not provide without TypeScript, for the notices. */
22642
+ const NO_FEATURES = "The TSRX language server will not be able to provide type checking, hover or completions in .tsrx files.";
22636
22643
  /** What still works without TypeScript, for the notices. */
22637
- const STILL_WORKS = "TSRX compile errors, CSS in <style>, the outline, formatting and closing tags still work.";
22644
+ const STILL_WORKS = "These features still work: TSRX compile errors, CSS in <style>, the outline, formatting and closing tags.";
22645
+ /**
22646
+ * The notice the server shows when the `typescript.tsdk` option is set but
22647
+ * `find_typescript` skipped it: the folder has no `typescript` package.
22648
+ * @param {string} tsdk the option's value
22649
+ * @param {FoundTypeScript | undefined} found the `typescript` found instead
22650
+ * @returns {string}
22651
+ */
22652
+ function tsdk_notice(tsdk, found) {
22653
+ const sentences = ["The TSRX language server does not use the typescript.tsdk startup option.", `The folder in this option does not contain TypeScript: ${node_path.default.resolve(tsdk)}.`];
22654
+ if (found && is_usable_typescript(found.version)) {
22655
+ const from = found.source === "server" ? "the server installation" : "the project";
22656
+ sentences.push(`The server uses TypeScript ${found.version} from ${from} instead: ${found.dir}.`);
22657
+ }
22658
+ sentences.push("Set this option to the lib folder of a TypeScript installation, for example /path/to/node_modules/typescript/lib.");
22659
+ return sentences.join(" ");
22660
+ }
22638
22661
  /**
22639
- * The notice the server shows when it found no `typescript` it can run.
22662
+ * The notice the server shows when it did not find a `typescript` it can run.
22640
22663
  * @param {FoundTypeScript | undefined} found
22641
22664
  * @param {readonly string[]} workspace_dirs
22642
22665
  * @returns {string}
22643
22666
  */
22644
22667
  function typescript_notice(found, workspace_dirs) {
22645
22668
  if (found) return [
22646
- `The TSRX language server found typescript ${found.version} at ${found.dir}.`,
22647
- "It cannot run TypeScript 7 or newer, so type checking, hover and completions in .tsrx files are off.",
22669
+ `The TSRX language server found TypeScript ${found.version} in ${found.dir}.`,
22670
+ "The server cannot run TypeScript 7 or newer.",
22671
+ NO_FEATURES,
22648
22672
  STILL_WORKS,
22649
- "For TypeScript 7, run its own language server (tsc --lsp) with @tsrx/content-mapper. To use another TypeScript, set the typescript.tsdk startup option to its lib folder.",
22650
- "See https://github.com/tsrx-org/tsrx/tree/main/packages/language-server#which-typescript-it-uses"
22673
+ "To use TypeScript 7, run the TypeScript 7 language server (tsc --lsp) with @tsrx/content-mapper.",
22674
+ "To use a different TypeScript, set the typescript.tsdk startup option to the lib folder of that TypeScript.",
22675
+ "For more information, see https://github.com/tsrx-org/tsrx/tree/main/packages/language-server#which-typescript-it-uses"
22651
22676
  ].join(" ");
22652
22677
  return [
22653
- `The TSRX language server found no typescript package in ${workspace_dirs.join(", ")}, its parent folders, or next to the server,`,
22654
- "so type checking, hover and completions in .tsrx files are off.",
22678
+ `The TSRX language server did not find TypeScript in ${workspace_dirs.join(", ")}, in the server installation, or in their parent folders.`,
22679
+ NO_FEATURES,
22655
22680
  STILL_WORKS,
22656
- "Install typescript in the project (npm install -D typescript, or pnpm add -D typescript), then restart the language server."
22681
+ "Install TypeScript in the project: npm install -D typescript, or pnpm add -D typescript.",
22682
+ "Then restart the TSRX language server."
22657
22683
  ].join(" ");
22658
22684
  }
22659
22685
 
22660
22686
  //#endregion
22661
22687
  //#region src/autoInsertPlugin.js
22688
+ /** @import * as AST from 'estree' */
22662
22689
  /** @import { LanguageServicePlugin } from '@volar/language-server' */
22663
22690
  const { log: log$8 } = createLogging("[TSRX Auto-Insert Plugin]");
22664
22691
  /**
@@ -22684,20 +22711,25 @@ const VOID_ELEMENTS = /* @__PURE__ */ new Set([
22684
22711
  "wbr"
22685
22712
  ]);
22686
22713
  /**
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
+ /**
22687
22720
  * Auto-insert plugin for TSRX.
22688
- * Handles auto-closing tags when typing '>' after a tag name
22721
+ * Handles auto-closing tags when typing '>' after a tag name. The VS Code extension
22722
+ * asks for them with Volar's `volar/client/autoInsert` request; other editors get
22723
+ * them through `textDocument/onTypeFormatting` (`closingTagsHandler.js`).
22689
22724
  * @returns {LanguageServicePlugin}
22690
22725
  */
22691
22726
  function createAutoInsertPlugin() {
22692
22727
  return {
22693
22728
  name: "tsrx-auto-insert",
22694
- capabilities: {
22695
- autoInsertionProvider: {
22696
- triggerCharacters: [">"],
22697
- configurationSections: ["tsrx.autoClosingTags.enabled"]
22698
- },
22699
- documentOnTypeFormattingProvider: { triggerCharacters: [">"] }
22700
- },
22729
+ capabilities: { autoInsertionProvider: {
22730
+ triggerCharacters: [">"],
22731
+ configurationSections: ["tsrx.autoClosingTags.enabled"]
22732
+ } },
22701
22733
  create(context) {
22702
22734
  return {
22703
22735
  /**
@@ -22761,17 +22793,103 @@ async provideAutoInsertSnippet(document, position, lastChange, _token) {
22761
22793
  return null;
22762
22794
  }
22763
22795
  const closingTag = `</${tagName}>`;
22764
- if (sourceCode.startsWith(closingTag, sourceOffset + 1)) {
22796
+ const element = virtualCode.isDotCompletionMode ? null : findElement(virtualCode.sourceAst, sourceOffset + 1);
22797
+ if (element ? !isUnclosed(element, sourceCode) : sourceCode.startsWith(closingTag, sourceOffset + 1)) {
22765
22798
  log$8("Closing tag already exists, skipping");
22766
22799
  return null;
22767
22800
  }
22768
22801
  log$8("Inserting closing tag:", closingTag);
22769
- return `$0${closingTag}`;
22802
+ return `$0${escapeSnippetText(closingTag)}`;
22770
22803
  } };
22771
22804
  }
22772
22805
  };
22773
22806
  }
22774
22807
  /**
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
+ * Escape `text` so that a snippet inserts it as written. `\`, `$` and `}` are snippet
22876
+ * syntax: unescaped, the `$Foo` in `</$Foo>` is a variable, which VS Code replaces
22877
+ * with nothing.
22878
+ * @param {string} text
22879
+ * @returns {string}
22880
+ */
22881
+ function escapeSnippetText(text) {
22882
+ return text.replace(/[\\$}]/g, "\\$&");
22883
+ }
22884
+ /**
22885
+ * The text that a snippet made by `escapeSnippetText` inserts: `</\$Foo>` inserts `</$Foo>`.
22886
+ * @param {string} snippet
22887
+ * @returns {string}
22888
+ */
22889
+ function unescapeSnippetText(snippet) {
22890
+ return snippet.replace(/\\([\\$}])/g, "$1");
22891
+ }
22892
+ /**
22775
22893
  * Match an opening tag `<name …>` that ends exactly at the end of `text` and return its name.
22776
22894
  *
22777
22895
  * Attribute expressions may themselves contain `>` (`<style apply={x > y ? a : b}>`,
@@ -22781,11 +22899,14 @@ async provideAutoInsertSnippet(document, position, lastChange, _token) {
22781
22899
  * expression, not closing the tag), an earlier `>` already closed the tag, or the tag is
22782
22900
  * self-closing (`<style apply={theme} />`).
22783
22901
  *
22902
+ * A name is made of JavaScript identifier characters, `.` and `-`, so `$` and non-ASCII
22903
+ * letters can appear anywhere in it (`<ui.$Item>`, `<Café>`).
22904
+ *
22784
22905
  * @param {string} text - Source text from the tag's `<` up to and including the typed `>`
22785
22906
  * @returns {string | null}
22786
22907
  */
22787
22908
  function matchOpeningTag(text) {
22788
- const nameMatch = text.match(/^<([@$\w][\w.-]*)/);
22909
+ const nameMatch = text.match(/^<([@$_\p{ID_Start}][$\p{ID_Continue}\u200C\u200D.-]*)/u);
22789
22910
  if (!nameMatch) return null;
22790
22911
  let depth = 0;
22791
22912
  /** @type {string | null} */
@@ -24557,7 +24678,8 @@ function createTypeScriptServices(ts) {
24557
24678
  /** @import { LanguageServicePlugin } from '@volar/language-server' */
24558
24679
  /** @import { TypeScriptBackend } from './backend.js' */
24559
24680
  /**
24560
- * Strip whole-document formatting capabilities from a Volar service plugin.
24681
+ * Strip the formatting capabilities from a Volar service plugin, on-type
24682
+ * formatting included.
24561
24683
  *
24562
24684
  * The bundled TypeScript (`typescript-syntactic`) and CSS services advertise a
24563
24685
  * `documentFormattingProvider`. Because they run against the virtual TS/CSS code
@@ -24566,17 +24688,20 @@ function createTypeScriptServices(ts) {
24566
24688
  * (`formattingHandler.js`): a plugin that offered formatting would make Volar
24567
24689
  * register its own `textDocument/formatting` handler, which would replace that one,
24568
24690
  * and the language client would list a second formatter that does nothing
24569
- * (removed first by Ripple-TS/ripple#1318). On-type formatting is left intact.
24570
- * TypeScript 7 registers a formatter for `.tsrx` files that returns no edits
24571
- * (`native-lsp.test.js` pins it), so the VS Code extension makes TSRX the `[tsrx]`
24572
- * default formatter.
24691
+ * (removed first by Ripple-TS/ripple#1318). TypeScript 7 registers a formatter for
24692
+ * `.tsrx` files that returns no edits (`native-lsp.test.js` pins it), so the VS Code
24693
+ * extension makes TSRX the `[tsrx]` default formatter.
24694
+ *
24695
+ * On-type formatting is the same: TypeScript's `;`, `}` and newline triggers
24696
+ * return nothing for `.tsrx` files (their mappings turn formatting off), and the
24697
+ * server answers `>` itself with the closing tag (`closingTagsHandler.js`).
24573
24698
  *
24574
24699
  * @template {{ capabilities?: Record<string, unknown> }} T
24575
24700
  * @param {T} plugin
24576
24701
  * @returns {T}
24577
24702
  */
24578
- function stripDocumentFormatting(plugin) {
24579
- const { documentFormattingProvider: _fmt, documentRangeFormattingProvider: _rangeFmt, ...capabilities } = plugin.capabilities ?? {};
24703
+ function stripFormatting(plugin) {
24704
+ const { documentFormattingProvider: _fmt, documentRangeFormattingProvider: _rangeFmt, documentOnTypeFormattingProvider: _onTypeFmt, ...capabilities } = plugin.capabilities ?? {};
24580
24705
  return {
24581
24706
  ...plugin,
24582
24707
  capabilities
@@ -24608,7 +24733,7 @@ function createServicePlugins(backend, ts) {
24608
24733
  const shared_last = [
24609
24734
  createDefinitionPlugin(),
24610
24735
  createDocumentSymbolPlugin(),
24611
- stripDocumentFormatting((0, volar_service_css.create)())
24736
+ stripFormatting((0, volar_service_css.create)())
24612
24737
  ];
24613
24738
  if (backend === "native" || backend === "plugin") return [
24614
24739
  ...shared_first,
@@ -24622,7 +24747,7 @@ function createServicePlugins(backend, ts) {
24622
24747
  ...shared_first,
24623
24748
  createCompileErrorDiagnosticPlugin(),
24624
24749
  ...shared_last,
24625
- ...createTypeScriptServices(ts).map(stripDocumentFormatting),
24750
+ ...createTypeScriptServices(ts).map(stripFormatting),
24626
24751
  createTypeScriptDiagnosticFilterPlugin(),
24627
24752
  createHoverPlugin({ typescriptBackend: backend }),
24628
24753
  createDocumentHighlightPlugin({ typescriptBackend: backend })
@@ -24789,7 +24914,7 @@ function at_least(version, minimum) {
24789
24914
  * Answer `textDocument/formatting` and `textDocument/rangeFormatting` (Format
24790
24915
  * Selection, format on paste) for `.tsrx` files with `format_tsrx`, on the
24791
24916
  * plain LSP connection: Volar only formats generated code, never the `.tsrx`
24792
- * source, and its TypeScript and CSS formatters stay off (`stripDocumentFormatting`
24917
+ * source, and its TypeScript and CSS formatters stay off (`stripFormatting`
24793
24918
  * in `servicePlugins.js`), so this is the server's only formatter.
24794
24919
  *
24795
24920
  * When the project lacks `prettier` or `@tsrx/prettier-plugin`, or has a Prettier
@@ -24906,6 +25031,86 @@ async function formatting_enabled(connection, uri) {
24906
25031
  }
24907
25032
  }
24908
25033
 
25034
+ //#endregion
25035
+ //#region src/closingTagsHandler.js
25036
+ /** @import { Connection, DocumentOnTypeFormattingParams, InitializeParams, LanguageServer, ServerCapabilities, TextEdit } from '@volar/language-server' */
25037
+ /**
25038
+ * The on-type formatting the server offers: closing tags on `>`, and nothing else.
25039
+ * @type {NonNullable<ServerCapabilities['documentOnTypeFormattingProvider']>}
25040
+ */
25041
+ const CLOSING_TAGS_ON_TYPE = { firstTriggerCharacter: ">" };
25042
+ /**
25043
+ * Whether the client gets its closing tags through `textDocument/onTypeFormatting`.
25044
+ * A client that closes tags another way sets the `closeTagsOnType` initialization
25045
+ * option to `false`: the VS Code extension, where VS Code's TypeScript closes them,
25046
+ * or the extension asks for them with Volar's `volar/client/autoInsert` request.
25047
+ * @param {InitializeParams} params
25048
+ */
25049
+ function closes_tags_on_type(params) {
25050
+ return params.initializationOptions?.closeTagsOnType !== false;
25051
+ }
25052
+ /**
25053
+ * Close tags in every editor: answer `textDocument/onTypeFormatting` for `>` with
25054
+ * an edit that inserts the closing tag at the cursor. Only the VS Code extension
25055
+ * sends Volar's `volar/client/autoInsert` request. This handler asks the same
25056
+ * plugin (`provideAutoInsertSnippet` in `autoInsertPlugin.js`), drops the
25057
+ * snippet's `$0` and removes its escapes (`$0</\$Foo>` inserts `</$Foo>`). No
25058
+ * Volar service plugin offers on-type formatting (`stripFormatting` in
25059
+ * `servicePlugins.js`), so Volar registers no handler that would replace this one.
25060
+ *
25061
+ * A text edit cannot place the cursor. Editors that leave the cursor before text
25062
+ * inserted at the cursor (Zed 1.17 and newer, Neovim in Insert mode) keep it
25063
+ * between the tags. `tsrx.autoClosingTags.enabled: false` turns it off.
25064
+ * @param {Connection} connection
25065
+ * @param {LanguageServer} server
25066
+ */
25067
+ function register_closing_tags(connection, server) {
25068
+ connection.onDocumentOnTypeFormatting(
25069
+ /**
25070
+ * @param {DocumentOnTypeFormattingParams} params
25071
+ * @returns {Promise<TextEdit[] | null>}
25072
+ */
25073
+ async (params, token) => {
25074
+ if (params.ch !== ">" || !is_tsrx_document(params.textDocument.uri)) return null;
25075
+ const uri = vscode_uri.URI.parse(params.textDocument.uri);
25076
+ const document = server.documents.get(uri);
25077
+ if (!document) return null;
25078
+ const offset = document.offsetAt(params.position);
25079
+ if (document.getText().charAt(offset - 1) !== ">") return null;
25080
+ if (!await closing_tags_enabled(connection, params.textDocument.uri)) return null;
25081
+ const snippet = await (await server.project.getLanguageService(uri)).getAutoInsertSnippet(uri, params.position, {
25082
+ rangeOffset: offset - 1,
25083
+ rangeLength: 0,
25084
+ text: ">"
25085
+ }, token);
25086
+ if (token.isCancellationRequested || !snippet?.startsWith("$0")) return null;
25087
+ return [{
25088
+ range: {
25089
+ start: params.position,
25090
+ end: params.position
25091
+ },
25092
+ newText: unescapeSnippetText(snippet.slice(2))
25093
+ }];
25094
+ }
25095
+ );
25096
+ }
25097
+ /**
25098
+ * `tsrx.autoClosingTags.enabled`, which defaults to true. A client that does not
25099
+ * answer `workspace/configuration` leaves closing tags on.
25100
+ * @param {Connection} connection
25101
+ * @param {string} uri
25102
+ */
25103
+ async function closing_tags_enabled(connection, uri) {
25104
+ try {
25105
+ return await connection.workspace.getConfiguration({
25106
+ scopeUri: uri,
25107
+ section: "tsrx.autoClosingTags.enabled"
25108
+ }) !== false;
25109
+ } catch {
25110
+ return true;
25111
+ }
25112
+ }
25113
+
24909
25114
  //#endregion
24910
25115
  //#region src/workspaceState.js
24911
25116
  const WORKSPACE_FILE_PATTERNS = [
@@ -25060,6 +25265,7 @@ function createTsrxLanguageServer(options = {}) {
25060
25265
  const connection = (0, import_node.createConnection)();
25061
25266
  const server = (0, import_node.createServer)(connection);
25062
25267
  register_formatting(connection, (uri) => server.documents.get(vscode_uri.URI.parse(uri)));
25268
+ register_closing_tags(connection, server);
25063
25269
  connection.listen();
25064
25270
  /** @type {WeakSet<Function>} */
25065
25271
  const wrappedFunctions = /* @__PURE__ */ new WeakSet();
@@ -25070,11 +25276,12 @@ function createTsrxLanguageServer(options = {}) {
25070
25276
  let restartScheduled = false;
25071
25277
  let clientRestarts = false;
25072
25278
  /**
25073
- * Shown once the client is initialized, when the classic backend found no
25074
- * `typescript` it can run and the server started without TypeScript features.
25075
- * @type {string | undefined}
25279
+ * Shown once the client is initialized, each as its own warning: the classic
25280
+ * backend skipped the `typescript.tsdk` option, or did not find a `typescript`
25281
+ * it can run and the server started without TypeScript features.
25282
+ * @type {string[]}
25076
25283
  */
25077
- let typescriptNotice;
25284
+ const typescriptNotices = [];
25078
25285
  /**
25079
25286
  * Restart the process so Node drops the complete ESM compiler graph. A
25080
25287
  * client that restarts the server itself stops sending first. When the
@@ -25154,17 +25361,19 @@ function createTsrxLanguageServer(options = {}) {
25154
25361
  let ts;
25155
25362
  if (backend === "classic") {
25156
25363
  const workspace_dirs = workspace_folder_paths(params);
25364
+ const tsdk = resolve_typescript_tsdk(params.initializationOptions);
25157
25365
  const found = find_typescript({
25158
- tsdk: resolve_typescript_tsdk(params.initializationOptions),
25366
+ tsdk,
25159
25367
  workspace_dirs,
25160
25368
  server_dir: SERVER_DIR
25161
25369
  });
25370
+ if (tsdk !== void 0 && found?.source !== "tsdk") typescriptNotices.push(tsdk_notice(tsdk, found));
25162
25371
  if (found && is_usable_typescript(found.version)) ts = load_typescript(found);
25163
25372
  else {
25164
- typescriptNotice = typescript_notice(found, workspace_dirs);
25165
- logError(typescriptNotice);
25373
+ typescriptNotices.push(typescript_notice(found, workspace_dirs));
25166
25374
  backend = "plugin";
25167
25375
  }
25376
+ for (const notice of typescriptNotices) logError(notice);
25168
25377
  }
25169
25378
  if (ts === void 0) {
25170
25379
  const compilerResolutionDependencies = /* @__PURE__ */ new Set();
@@ -25175,7 +25384,7 @@ function createTsrxLanguageServer(options = {}) {
25175
25384
  });
25176
25385
  const initResult = server.initialize(params, (0, import_node.createSimpleProject)([languagePlugin]), createServicePlugins(backend));
25177
25386
  log("Server initialization complete");
25178
- return with_formatting(initResult);
25387
+ return with_own_handlers(initResult, params);
25179
25388
  }
25180
25389
  const initResult = server.initialize(params, (0, import_node.createTypeScriptProject)(ts, void 0, ({ configFileName, projectHost, sys }) => {
25181
25390
  wrapCompilerOptionsProvider(projectHost, "getCompilationSettings");
@@ -25200,7 +25409,7 @@ function createTsrxLanguageServer(options = {}) {
25200
25409
  };
25201
25410
  }), createServicePlugins(backend, ts));
25202
25411
  log("Server initialization complete");
25203
- return with_formatting(initResult);
25412
+ return with_own_handlers(initResult, params);
25204
25413
  } catch (initError) {
25205
25414
  logError("Server initialization failed:", initError);
25206
25415
  throw initError;
@@ -25209,9 +25418,9 @@ function createTsrxLanguageServer(options = {}) {
25209
25418
  connection.onInitialized(async () => {
25210
25419
  log("Server initialized.");
25211
25420
  server.initialized();
25212
- if (typescriptNotice) connection.sendNotification("window/showMessage", {
25421
+ for (const message of typescriptNotices) connection.sendNotification("window/showMessage", {
25213
25422
  type: 2,
25214
- message: typescriptNotice
25423
+ message
25215
25424
  });
25216
25425
  server.fileWatcher.onDidChangeWatchedFiles(({ changes }) => {
25217
25426
  for (const configDependencies of compilerResolutionDependencySets) trackTypeScriptConfigDependencies(trackedTypeScriptConfigFiles, { configDependencies });
@@ -25244,15 +25453,19 @@ function createTsrxLanguageServer(options = {}) {
25244
25453
  };
25245
25454
  }
25246
25455
  /**
25247
- * Advertise the formatters `register_formatting` serves (whole document and range); no Volar service plugin
25248
- * advertises one (`stripDocumentFormatting`).
25456
+ * Advertise what the server's own handlers serve: the formatters `register_formatting`
25457
+ * serves (whole document and range), and the closing tags `register_closing_tags`
25458
+ * serves on `>`, unless the client closes tags another way (`closes_tags_on_type`).
25459
+ * No Volar service plugin advertises either (`stripFormatting`).
25249
25460
  * @template {import('@volar/language-server/node').InitializeResult} T
25250
25461
  * @param {T} initResult
25462
+ * @param {import('@volar/language-server/node').InitializeParams} params
25251
25463
  * @returns {T}
25252
25464
  */
25253
- function with_formatting(initResult) {
25465
+ function with_own_handlers(initResult, params) {
25254
25466
  initResult.capabilities.documentFormattingProvider = true;
25255
25467
  initResult.capabilities.documentRangeFormattingProvider = true;
25468
+ if (closes_tags_on_type(params)) initResult.capabilities.documentOnTypeFormattingProvider = CLOSING_TAGS_ON_TYPE;
25256
25469
  return initResult;
25257
25470
  }
25258
25471
  /**
@@ -25289,4 +25502,4 @@ Object.defineProperty(exports, 'createTsrxLanguageServer', {
25289
25502
  return createTsrxLanguageServer;
25290
25503
  }
25291
25504
  });
25292
- //# sourceMappingURL=server-BnzVhVsF.js.map
25505
+ //# sourceMappingURL=server-CpRcmosU.js.map