Skip to content

Latest commit

 

History

History
176 lines (155 loc) · 65.3 KB

architecture.md

File metadata and controls

176 lines (155 loc) · 65.3 KB

Architecture

Spec for how the plugin turns a tsserver request inside a tagged template into a CSS language service call and back. Authoritative for the invariants below; change this file first when changing them.

Request flow

  1. tsserver require()s the package root (src/index.ts), which returns a factory producing TsServerStyledPlugin (src/tsserver/tsserver-plugin.ts).
  2. create() checks the host TypeScript version, then wraps the host language service with decorateWithTemplateLanguageService from typescript-template-language-service-decorator.
  3. The decorator finds tagged templates whose tag matches a configured tag name (matching rules: docs/tsserver-host.md, "Tag matching"), replaces each ${...} via getTemplateSubstitutions (src/template/template-substitutions.ts), and calls StyledTemplateLanguageService (src/template-language-service.ts) with a TemplateContext and template-relative positions.
  4. Each feature (src/features/*) asks the virtual document provider for an SCSS document, calls vscode-css-languageservice, and translates results back to template-relative offsets. The decorator shifts those to file offsets.

Substitution invariants

  • Output length equals input length, always. Every template offset is also a virtual-text offset (plus the wrapper length).
  • Every fill writes its characters over every character of its placeholder, line terminators included, in order ($a:0 plus spaces for a mixin broken across lines when a ; follows and the statement rule holds): at runtime the interpolated value holds none of the source's line breaks, and a kept one would split a name, an at-rule prelude, a string, a url(...) token, or a // comment. A placeholder shorter than a branch's fill gets the next fill in that branch's chain (below), ending at the plain fill: the replacement character over every character. Position mapping never depends on the substituted text's line breaks (the line map in the "Virtual document" section reads the raw text; Emmet, which reads lines from text, gets the line view in the "Completions" section).
  • Solid fill: a placeholder that starts inside a comment (/* */ or //), a string, or an unquoted url(...) argument run fills with x, and no branch below applies to it; content there is opaque to the CSS service, and another branch's fill (block position's whitespace, the hex fill's 000 inside url(#...)) would change the token. A run that starts with a backslash does not count: an escape, whose backslash may take the placeholder's first character into the escape's identifier at code. An unquoted url(...) argument whose function name starts with an escape (\75 rl() also starts with a backslash and is excluded with the escapes, since the run list does not tell the two apart; a placeholder there gets its branch's fill. Whether a placeholder starts inside a run depends only on the text before it. A // comment holding a multi-line interpolation continues through it: the solid fill leaves no line terminator inside the placeholder, so the CSS service reads the comment as one unbroken, multi-line comment, matching runtime, where the interpolated value holds no line break either.
  • Cost is linear in template length for any number or arrangement of placeholders (many on one line included), and builds no per-character tables over the whole text: the document is rebuilt after every edit, so a whole-text pass is paid per keystroke. Forward scans are lazy and shared across placeholders (each kind of scan remembers the range it last covered, so a later query inside that range reuses the answer; the selector list scan below and the search for a comment's closing */ do the same). The scans that must know what is code (the selector-shape search, the selector list scan, and the running statement boundaries that set where each placeholder's statement starts) read the text's characters directly and step over its non-code runs (comments, strings, escapes, and unquoted url() arguments) whole, each scan keeping its own place in one list of those runs, since each placeholder lies past the previous one. One forward walk with the boundary scanner finds the list, stopping only where the scanner can act (a quote, /, a backslash, ), or a u before r or a backslash), so a text with few such characters, the common case, costs about one search more than plain code. The selector list scan reads a line's last code character back over that line's trailing whitespace and comments only. The running line facts (whether the line holds non-whitespace before a placeholder, and its latest line break or statement boundary, where a line break or non-whitespace character inside a comment or string still counts) jump from one line break or statement boundary to the next and read each stretch between for non-whitespace with one search. The statement rule's look-back past comments jumps between the characters that can open a comment or string instead of visiting every character; the at-rule condition test looks back over at most one gap and one word, and reads each statement's leading whitespace and comments once. The JavaScript escape replacement below is one pass over the masked text, or one search when the text holds no backslash. The masked text and its non-code runs are built once, and the solid fill is decided by one walk of the placeholders against those runs. A template with no placeholders is returned unchanged. pnpm test:scaling guards the linear bound; a before-and-after benchmark guards the constant factor.
  • Placeholder spans: every scan walks them in ascending order, clamped into the template, with overlapping spans merged into their union (spans that only touch stay separate, as adjacent placeholders do) and empty spans dropped (they substitute nothing). The decorator supplies spans in that shape already; a span list from ./api's getSubstitutions in any other order, overlapping, empty, or out of range is normalized once, with one copy and one sort. The output depends only on span positions, so the same spans in any order give the same output.
  • Each branch of getSubstitution targets one placeholder shape (property value, whole declaration, property name, selector, at-rule condition, hex color); comments in src/template/template-substitutions.ts show each shape.
  • Masked text: the template text with every placeholder as x's over its whole length (so a line fact never starts a new line inside a placeholder) and JavaScript escapes replaced as the virtual document replaces them (the "Virtual document" section), so a JavaScript-escaped quote, ;, or brace reads as the character styled-components receives. Every rule below reads the masked text; the output keeps the raw text between placeholders.
  • Name characters, for the rules below: ASCII letters, digits, -, _, and every UTF-16 code unit from U+0080 up except U+2028 and U+2029, which are line terminators, in the masked text (where adjacent placeholders form one name). This is vscode-css-languageservice 6.3.10's _identChar, so a non-ASCII space such as U+00A0 is a name character, as the CSS scanner reads it. The same set serves every name reader in the "Virtual document" section: the boundary scanner, the @layer name, and the url function name in the JavaScript escape replacement.
  • Block position (a placeholder standing in for whole declarations, such as a mixin or a css fragment) is filled with whitespace, or, when a ; follows it, with the dummy declaration $a:0 (then a:0, then whitespace, for a shorter placeholder) if the statement rule's look-back below holds and with x's otherwise (nothing before it to anchor a declaration to). A placeholder is in block position when either rule holds:
    • Statement rule: the last significant character before it in the masked text, across lines and past comments (a string counts as one significant character at its opening quote, an escape at its backslash, an unquoted url(...) argument at its (), is ;, {, }, or the template start, or is the end of a preceding placeholder that the statement rule itself placed in block position (so ${a} ${b} on one line is two mixins, and so is color: red; /* note */ ${a}); and the next non-whitespace character after it is none of {, :, ,, &, ., #, [, >, +, ~, *, % (a rule body, a property name, a selector list, a selector continuation, or a percentage such as the keyframe selector ${step}% {). A placeholder inside a comment or string never passes this rule.
      • Matches styled-components v7's slot classification (isStandaloneSlot in packages/styled-components/src/parser/source.ts, an undocumented internal), except , and %: v7 excludes neither, and the plugin adds , so a placeholder that starts a selector list stays x-filled, the safe direction, and % so a placeholder before % stays a number.
      • Not modeled: v7's missing-semicolon recovery (shouldRecoverFragmentSlot), which promotes a slot to block position when its value is a css fragment containing ;, {, or } (color: red ${fragment};). The plugin sees only the ${...} syntax, never the fragment's value, so such a slot stays a value.
    • Line rule: only whitespace precedes it on its own line, and the next non-whitespace character after it is none of {, :, ,, %. A placeholder placed only by this rule never passes block position on to the next placeholder, so padding:\n ${a} ${b}; and border:\n ${a}\n ${b}; keep ${b} a value.
  • Property name: the next non-whitespace character after the placeholder, or after the name characters joined directly to its end, is :, without the selector shape below. Such a placeholder is never in block position. Filled with $a plus x's (x's for a one-character placeholder), except:
    • Inside a custom property name (the statement starts with --): x's.
    • Joined to name characters directly before or after it (padding-${side}:, ${side}-top:, border-${side}-color:): the Sass interpolation #{x} plus spaces, which the parser reads as part of one property name and the linter never reports as an unknown property. A placeholder shorter than 4 characters gets x's.
  • Selector: that : is followed, on its own line, by a { or & at code with no ; or } at code before it (a ; or } ends the declaration first, so padding-${s}: 0; &:hover { and ${p}: 0; &:hover { keep a property name), or by a line break at code after which the next non-whitespace character is { (${Child}:not(:last-child) with { on the next line). At code means outside comments, strings, escapes, and unquoted url(...) arguments, read with the boundary scanner (the "Virtual document" section): a ;, {, }, &, or line break inside one decides nothing (${Link}:hover /* a; b */ { and ${Link}:not([x="a;b"]) { are selectors, ${p}: "a{b"; a property name), and a // comment ends at its line break, which counts. A line whose last code character is , (comments skipped) continues a selector list: the search goes on over the next line, and over each further line ending in ,, for a { or & (${C}:hover, then ${C}:focus {), stopping at a ; or } (a declaration value continued after ,, such as ${prop}: a, then b;) or a blank line. Filled with & plus spaces (nothing for an empty placeholder), except when joined to name characters or right after ., #, &, or : (&.${className}:hover {), where it is part of a name: x's.
  • At-rule condition: in an @media, @supports, or @container prelude that starts the statement (at the start of the placeholder's own line, or, for a prelude split over lines, right after the last ;, {, or } at code before it, in both cases after any whitespace, block comments, and // comments; an unterminated block comment hides the at-keyword), a placeholder separated by whitespace and comments, line breaks included, from a preceding and, or, or not, right after @supports, right after the container name (@container card ${query}), or right after @media and followed by a separate or (which follows only a condition, never a media type: @media ${a} or ${b}) stands for a condition. Filled with (x, spaces, and ) in @media and @container, and with x(, spaces, and ) in @supports, which the parser reads as a function-shaped supports condition (the plain fill for a placeholder shorter than 3 characters). Otherwise, right after @media or @container, the x-filled placeholder already reads as a media type or a container name.
  • Hex color: right after #. Filled with 000 plus spaces (the plain fill for a placeholder shorter than 3 characters).
  • Every other placeholder is a value: x's, or 0s right before %.

Virtual document

  • Contents: wrapper line, substituted template text with JavaScript escapes replaced (below), then \n}. Wrapper is one of:
    • @keyframes custom {\n when the tag name is keyframes.
    • :root{all:\n (the value wrapper) when the tag name is css and the substituted text is value-shaped, such as css`1px solid red` or css`${fadeIn} 1s linear`: it validates the text as the value of all (a known property, so the wrapper line reports nothing of its own; vscode-css-languageservice does not check a value against its property's grammar). Value-shaped means all of: no ;, {, or } outside strings, comments, and unquoted url(...) arguments; no : outside strings, comments, and parentheses; some non-whitespace text; the trimmed text is not a single identifier, escapes included (css`dis` is a property name being typed, which needs property completions); and the first non-whitespace character does not start a selector or at-rule (&, >, +, ~, *, [, @, or a . not followed by a digit). The test jumps between the characters that can change its answer (the boundary scanner's own, ;, {, }, :, and parentheses) and stops at the first structural one.
    • A css fragment that misses value shape only because its trimmed text is a single identifier (css`red`, css`none`, css`${x}px`, css`colr`) reads as a value as much as a property name, so it keeps :root{\n for completions, and validation reports only the diagnostics both readings report: the template is validated a second time under the value wrapper, and a diagnostic is kept only when the value reading has one with the same code, message, and range (both wrappers are one line, so a range past the wrapper names the same template span in either). The wrapper's own ambiguity (colon expected, semi-colon expected) is therefore silent. The validation cache stores the kept list.
    • :root{\n otherwise.
  • Reading: everything besides the raw text that shapes a template's document and its diagnostics: the wrapper, whether the template's top level is a nested position for the @layer rewrite (below), and whether a css template is a single identifier (the double validation above). All three are pure functions of the tag kind and the raw template text; nothing else enters (no configuration, no provider state), because the substituted text and its escape replacement are themselves pure functions of the raw text (the placeholder spans are the ${...} positions in it). Tag kind: keyframes, css, a global-style tag (createGlobalStyle, globalCss, injectGlobal), or any other tag. So the same raw text under two tag kinds can read differently (@layer x { color: red; } in styled.div and in createGlobalStyle; colr in css and in styled.div). getReadingKey names the tag kind as a string; the validation cache key and canReuseVirtualDocument (both in the "Caching" section) use it with the raw text and never compute the reading. The reading is computed only when a document is built or an offset translation needs the wrapper, and kept per TemplateContext and for the last (tag kind, raw text) pair, so a fresh context for unchanged text reuses it.
  • Line map comes from a line-start table computed once from context.rawText (the original, unsubstituted template source), never from the substituted text and never from TemplateContext.toPosition/toOffset: template line L, character C is virtual line L + 1, character C. Virtual line 0 is the wrapper. The table uses TypeScript's own line-terminator rules (\r\n, a lone \n, a lone \r, U+2028, U+2029; docs/tsserver-host.md). Built once per TemplateContext as a TemplateLineMap (createTemplateLineMap, src/virtual-document/template-line-map.ts, which keeps it per context, so the document and the session provider share one table) and threaded through every position a feature translates, not recomputed per diagnostic, hover, folding, or code-fix result: translating a large result set stays linear in the result count. VirtualDocumentSessionProvider.getDocument and getParsedDocument return it with the document. The same module maps a virtual range back to template offsets (fromVirtualDocSpan, fromVirtualDocSpanStrict) under the rules below; features take their offsets from these and never call TemplateContext.toOffset.
  • One boundary scanner (nonCodeEnd, src/virtual-document/css-code-scanner.ts, with the character predicates every reader shares) decides what is comment, string, escape, or code for these scans, so they never disagree: separator normalization and the @layer rewrite below, the value-shape test above, the stray closing brace search in diagnostics, the statement rule's look-back, the statement boundaries that start an at-rule condition's statement and the custom-property test's text, the selector-shape search in substitution, the nearest non-whitespace character and the joined name after a placeholder, the { that opens a rule body on the next line, and the at-keyword look-back, caret placement, and at-rule prelude test in completions. Those three substitution scans (the nearest non-whitespace character and the joined name after a placeholder, and the { that opens a rule body on the next line) skip whole comment runs, never strings or unquoted url(...) arguments, which are significant content: a comment between a placeholder and the character that decides its role never hides that character (${Child} /* note */ { color: red; } is a selector, ${p} /* note */: red; a property name, and a comment alone on the line before a rule body still opens it). The line rule, and the hex-color and custom-property -- tests of the text before a placeholder, still do not skip comments or strings; the at-rule condition's at-keyword test skips only the whitespace and comments that open its statement. The scanner's rules follow vscode-css-languageservice 6.3.10's own SCSS scanner and the parser that drives it (Scanner.comment, SCSSScanner.comment, Scanner._escape, Parser._parseURILiteral), reading U+2028 and U+2029 outside strings as the \n the virtual document turns them into:
    • A block comment runs from /* to the next */, or to the end of the text when unterminated.
    • A // line comment (SCSS) ends at the next \n, \r, \f, U+2028, or U+2029.
    • A ' or " string runs through its matching quote, or ends before an unescaped \n, \r, or \f. A backslash escapes one character, or a line break (a \r\n pair counts as one), or up to six hex digits plus one optional space, tab, or line break after them. A quote inside a comment opens no string.
    • Outside strings and comments, a backslash escapes the same way (up to six hex digits plus one optional space, tab, or line break, or else one character) except before a line break, where it escapes nothing, and at the end of the template text, where it also escapes nothing because the virtual document follows the text with a line break. An escaped character is identifier text: an escaped quote opens no string, an escaped / opens no comment, an escaped brace, ;, or @ is not structural, and the escape joins the identifier it starts or continues (\41 url is one identifier).
    • An unquoted url(...) argument opens where an identifier whose name, with escapes decoded and compared case-insensitively, is url or url-prefix is followed directly by (, as the CSS parser reads one: \75 rl( opens one, image-url( and #url( do not. The parser reads the argument as trivia (whitespace and block comments), one token, then trivia again, with // comments off (SCSSScanner.comment tests !this.inURL for // only). So inside it:
      • A /* opens a block comment only where a token can start: right after the (, right after a string or another comment, or after whitespace that no escape took (url(/* x */a.png), url(a.png /* x */)). Next to url characters, / and * are url content (url(a/*x*/b.png) is one url).
      • // opens no comment.
      • An escape steps over its own characters, so an escaped ) does not close the argument; an unescaped ) does.
      • Every structural reader skips the argument the way it skips a string: a ;, {, or } in it (url(a;b.png), url(a/*;*/b.png)) ends no statement, opens or closes no block, and makes a css fragment no less value-shaped. The look-back reads the argument as one significant character at its (, so a placeholder or caret inside it follows the (.
      • Not modeled: the url token ends at whitespace that follows url characters (url(a b)), where the parser reports an error; the argument stays open here until the ).
    • \f ends a string or // comment here but starts no new line for position mapping (the line map above).
    • A look-back query at the end of a string or comment with no closing delimiter (a string cut off by a line break or the end of the text, an unclosed block comment, a line comment the text ends inside) is inside it: a caret there still types into it. A query at the end of a closed one is after it.
  • JavaScript escapes: the template text is the raw source between the backticks, while styled-components (v6 and v7) receives the cooked strings, each escape already resolved to its character (interleave in packages/styled-components/src/utils/interleave.ts reads the TemplateStringsArray elements, never .raw). Each run of adjacent escape sequences becomes a same-length stand-in for its cooked text (replaceJavaScriptEscapes, src/virtual-document/javascript-escapes.ts) before every other scan in this section reads the text (the value-shape test, separator normalization, the @layer rewrite, and the stray closing brace search in diagnostics). Substitution replaces them in its masked text before any decision (the "Substitution invariants" section). After substitution, getTemplateCssText (same file) computes the replaced text once per TemplateContext, the one source for the virtual document, the value-shape test, and the stray closing brace search; completions read the virtual document, so they see the same text:
    • The cooked text is written right-aligned in the run's span, with spaces before it (\"x\" reads as "x ", \\ as \). A cooked control character (below U+0020, and U+007F) or U+2028 or U+2029 is written as a space, so \n, \t, and a line continuation (a backslash before a line break, cooked to nothing) become spaces, except for padding inside an unquoted url(...) argument (below).
    • When the cooked run ends with a backslash that escapes what follows (an odd count), the padding goes inside that CSS escape instead of before it: as leading zeros before the hex digits that follow ("\\f101" reads as "\0f101"), while the zeros and digits together stay within six. The CSS escape reads on over hex digits from later runs too: when a later run's cooked text continues those digits, that run joins the stand-in and the zeros go after the backslash for the whole escape ("\\4\x31" reads as "\000041"); outside an unquoted url(...) argument, when the joined zeros and digits would pass six, each run keeps its own stand-in (x\\fa\x34; reads as x\0fa\034;). Otherwise as the escaped character's own hex code, padded to fill the room (u\\rl( reads as u\72l(), when the code fits and the character after it is none of a hex digit, whitespace, a backslash, or the end of the text.
    • Otherwise, inside an unquoted url(...) argument, where a space would end the url token, every run's padding is _, after its cooked text and before a trailing escaping backslash unless placed as below, and none of the name rules below apply: url(a\\(b) reads as url(a_\(b), url(a/\x41y.png) as url(a/A___y.png), and a line continuation (url(foo\ then a line break, then bar.png)) as url(foo__bar.png). The stand-in holds no line break there, which position mapping allows (the line map below counts the raw one). Placement inside the argument:
      • The _ goes before a ) in the cooked text that closes the argument, and before CSS whitespace that ends the url token, so it never lands outside the argument or forms a second token: url(a.png\x20) reads as url(a.png___ ). A ) a cooked backslash escapes, and whitespace a CSS escape takes (after a backslash, or one after a hex escape's digits), is url content: url(\x5c\x31\n\\f) reads as url(\1 ________\f).
      • A run that cooks to whitespace alone at the argument's start is leading trivia, padded with spaces (url(\x204a) reads as url( 4a)); right after a hex escape a previous run left open, the whitespace comes first, so the escape takes it, and the _ follows.
      • A cooked quote as the argument's first content makes the argument a quoted string: the run is padded as outside a url (url(\x22\x22) reads as url( "")).
    • The argument is found by reading back from the run over url characters to the ( of a url or url-prefix function, with whitespace allowed only right after that (; a quote, a paren, or other whitespace means no url, unless a CSS escape takes it (a cooked backslash right before it, or one whitespace after a hex escape of at most six digits: url(a\\"b\x41) and url(a\\41 b\x41) stay one url). A url function name must be written literally: the name is the run of name characters before the ( in the raw text (the name characters defined above), so a name character before url, a non-ASCII letter included, makes a different function name (äurl(, image-url(), and so does a #, @, or backslash before it; a name spelled with an escape inside it or joined to an escape run before it (u\x72l(, \x75rl(, u\\rl(, \x20url() opens no url here, and the runs in its argument are padded as outside one. Inside the argument, a run whose cooked text leaves a CSS hex escape open takes that escape whole (the hex digits after it, raw or from later runs, which then join its stand-in), and its padding goes as leading zeros after the backslash while the escape stays within six digits, or else as _ before the backslash, never between the digits and the whitespace the escape takes: url(a\\4\x31 b) reads as url(a\000041 b), and url(a\\\x34\x31 b) as url(a_______\41 b). Each run's look-back stops where the previous run ended and takes that run's answer, unless its cooked text holds a character no CSS escape takes that ends the url token (CSS whitespace, a quote, or a paren) or that the stand-in writes as a space; a character that only JavaScript counts as whitespace (U+00A0, U+3000, U+FEFF) is url content. So the text is read once.
    • Inside a name, spaces between the name and the run would split it, so when the stand-in starts with a name character or a CSS escape, or is exactly ( right after a name (url() takes no whitespace before its (: url\x28a) reads as url(a)), the run continues the name before it: name characters read back from the run (to where the previous stand-in ended), plus one leading #, ., @, :, or !. When the character before that name is whitespace, ;, {, }, (, ,, or the template start, the padding moves in front of the whole name and the name reaches the CSS service spelled as it is cooked: co\x6Cr reads as colr (one unknown property, colr), ba\x63kground as background, r\x65d as red, .md\\:flex as .md\:flex. A later run in the same name adds its padding to the same spaces (\x63ol\x6Fr reads as color).
    • Otherwise, where whitespace in front of the name would split a larger token (&.bt\x6E, a:ho\x76er, color:r\x65d), the last cooked character becomes a CSS hex escape filling the padding, followed directly by the text after the run when that character is none of a hex digit, whitespace, a backslash, or the end of the text (&.bt\06e{), and ended by one space otherwise (&.bor\64 er, since the CSS scanner absorbs one space after a hex escape). The CSS service reads the escaped name as one identifier; a property name spelled with a CSS escape is checked as written, which is why the move in front comes first.
    • The padding stays spaces before the cooked text, splitting the name, when neither applies: the name is a hash or starts with a digit, where an escaped digit would start an identifier (color:#f\x66f, margin:1\x30px); the code does not fit six hex digits (a character outside the Basic Multilingual Plane after &.a); the cooked text ends with a CSS escape. A stand-in that starts with any other character (colr\x3a red) keeps its spaces between the name and the run, so an edit to the name alone does not touch the run.
    • A cooked line break inside a // comment is a space here, so the comment runs to the real end of its line and hides the rest of that line from validation.
    • An invalid escape (\1, \x4, \u{110000}, cooked to undefined at runtime) stays as written.
  • U+2028 and U+2029 become \n outside quoted CSS strings (the CSS scanner does not treat them as whitespace) and stay verbatim inside strings. Replacement is one character for one character.
  • Nested block @layer workaround: vscode-css-languageservice's SCSS parser parses a block @layer inside a style rule without its nested flag, so a declaration directly in the layer body (@layer utilities { color: red; }) reports a false { expected (microsoft/vscode-css-languageservice#530). The virtual text rewrites each block @layer prelude that sits in a nested position (the @layer keyword in any letter case, as the parser matches keywords, plus an optional single layer name of name characters, dotted names and the anonymous form included, up to its {) to spaces with one & just before the {, so the parser reads a nested & { ... } rule with the same body. Nested position is any brace depth inside the template, plus the template's own top level, except when the tag is a global-style tag (createGlobalStyle, globalCss, injectGlobal), whose top level is the stylesheet's top level; which of the two the template's top level is belongs to its reading (above). A comment in the prelude separates tokens as whitespace does and is blanked with the rest of the prelude (@layer /* note */ base {). Statement-form @layer a, b;, a list prelude (@layer a, b {), a prelude holding an unterminated comment, and a prelude holding any other character (a string) stay untouched. The same string, comment, and url(...) aware scan as the separator normalization does both jobs in one linear pass that jumps between the characters either job can act on (the boundary scanner's own, @, braces, and the separators) and copies each stretch between them unchanged, skipped when the text has neither separator nor @layer. Output length equals input length. Remove this rewrite once the plugin depends on a vscode-css-languageservice release containing the upstream fix.
  • Mapping back to the template:
    • diagnostics, hover, folding: a position on the closing \n} clamps to the template end, so end-of-template syntax errors (unclosed block, truncated declaration) are reported; a position inside the opening wrapper is dropped.
    • a hover without its own range: the one character at the caret, or an empty span when the caret sits at the template end, so the span never covers the closing backtick.
    • code-fix text edits: any position outside the template body is rejected, because the wrapper does not exist in the source file.
    • Escape runs: the span of raw text each run of JavaScript escapes and its stand-in cover (the escaped character after it included when the stand-in took it, the hex digits and later runs a joined CSS hex escape takes, and the name characters before and between the runs when the padding moved in front of the name), computed in the same pass as the replaced text (getTemplateEscapeRuns) and carried on the TemplateLineMap, which computes them on first read and only when the raw text holds a backslash (no placeholder fill holds one, so without one in the raw text there are no runs). That first read calls back into the TemplateContext the TemplateLineMap was built from (getTemplateEscapeRuns reads context.text), even when a reused line map (the "Caching" section) answers a later, different context's request: safe only because VirtualDocumentSessionProvider.ensureDocument builds a TemplateLineMap solely alongside createVirtualDocument for that same context, and createVirtualDocument already reads that context's substituted text (getTemplateCssText, which shares getTemplateEscapeRuns's own per-context cache in javascript-escapes.ts), so the escape-runs read always hits that cache instead of substituting again. A caller that could obtain a TemplateLineMap without createVirtualDocument having already run for its own building context would read a stale context's .text there. A diagnostic, hover, folding, or completion replacement span whose start or end falls strictly inside a run widens to cover the whole run (\x63olr is underlined whole, not 3olr). A code fix is dropped when any of its edits overlaps a run, or, when empty, sits strictly inside one: the edit is written for the stand-in, so applied to the escape as written it corrupts it (renaming \x63olr to color would write \x6color). An edit that only touches a run's edge is kept.

Completions

  • A completion list merges, in order: CSS items, SCSS items filtered to pseudo-class functions, nested at-rules (below), then Emmet abbreviations.
  • Caret placement, decided on the virtual text (wrapper included) with the boundary scanner (the "Virtual document" section):
    • Inside a comment or string, the end of one with no closing delimiter included: no completions at all. The CSS language service offers nothing useful there: none inside a value string, and only selector names inside an attribute-selector string.
    • No declaration can start: the last structural code character before the caret (;, {, }, or :) is : (a value, a selector with a pseudo-class such as &:hover m10 {, or a media feature such as @media (min-width: m10)), or the statement that character ends, past whitespace and comments, starts with @ (an at-rule prelude such as @media m10 {). The value wrapper of a value-shaped css fragment counts, so its whole text is a value. Emmet items that expand to a whole declaration (their label holds a :, such as float: left; for fl) are dropped, because accepting one inserts a declaration where none fits. Value expansions (#121212 for #12, !important) stay.
    • Anywhere else, including an empty template and a line typed above a nested rule (m10 before &:hover {, where a declaration can start): every source above.
    • Cost: the structural search runs only when an Emmet item expands to a declaration, and costs at most two passes over the text before the caret (one in the common case, where the nearest structural character is code), plus the whitespace and comments that open the caret's statement.
  • Emmet line view: @vscode/emmet-helper 2.11.0 reads the caret's line from the document text between \n characters (getCurrentLine) and indexes it by the caret's character, while positions follow the template's own lines (the line map in the "Virtual document" section). A template line can end without a \n in the virtual text: under a fill, under an escape stand-in (a line continuation), at a lone \r, or at a U+2028 or U+2029 kept inside a string. So Emmet gets a fresh document built over the template text with \n written at the end of every template line: the same length as the substituted text, and a document whose own lines are exactly the template's lines, so its line-based reads (getText, getLineRange, lineCount) and its position mapping (offsetAt, positionAt) all agree with each other; the view is the document itself when every template line already ends in \n. Every other consumer reads positions through the document's own mapping.
  • Nested at-rules: vscode-css-languageservice offers no at-rules inside a style rule (CSS mode returns none; SCSS mode returns only Sass directives, which the SCSS filter drops). When the caret ends or sits inside an at-keyword (@ and the name characters around the caret, the set in the "Substitution invariants" section, as the CSS scanner reads one: @, @me, @mé) that is code (not inside a comment or string) and whose preceding significant character in the template, past comments, is ;, {, }, or the template start, the list adds the at-rules valid nested in a style rule (@media, @supports, @container, @layer, @scope, @starting-style) and the ones styled-components hoists to the top level (@keyframes, @property, @font-face, @font-palette-values, @page, @counter-style), skipping a label the list already has.
    • Inclusion rule for hoisted at-rules: one the styled-components v7 emitter writes at the stylesheet's top level, outside the component's selector, through either of its two branches in packages/styled-components/src/parser/emit-web.ts (an undocumented internal): a name in DECL_BODY_AT_RULES, whose body emitAtRule writes as bare declarations, or a keyframes name, which the parser reads into its own keyframes node (isKeyframesName, packages/styled-components/src/parser/atRuleNames.ts) and emitKeyframes writes as keyframe blocks of declarations; whose body v7 keeps as the author wrote it; and that the CSS language service completes at the top level. Applied to each candidate:
      • @font-face, @page, @property, @counter-style, @font-palette-values: the declaration branch; bodies of declarations, kept; completed. Included.
      • @keyframes: the keyframes branch; keyframe blocks, kept; completed. Included.
      • @color-profile, @viewport: the declaration branch, but the CSS language service does not complete them. Left out.
      • @font-feature-values: the declaration branch, but its body holds feature-value blocks (@styleset, @swash), which emitAtRule drops because it writes only declarations. Left out.
      • Vendor-prefixed keyframes (@-webkit-keyframes, @-moz-keyframes, @-o-keyframes): the keyframes branch, and they pass the rule, but they are left out: legacy prefixed syntax is not worth supporting (AGENTS.md, "User experience"), and the unprefixed @keyframes is offered.
    • Name, kind, and documentation come from the CSS language service's own top-level at-rule completions (the catalog); a name absent from the catalog is not offered.
    • The replacement span covers the whole at-keyword at the caret.
  • Every entry is translated the same way: name, kind, kind modifiers, sort text, replacement span; never insert text, a snippet flag, or filter text.
  • Entry details for a name the list at that position does not hold (and the recovery fallback, the "Exception recovery" section): the name as the only display part, kind unknown, no kind modifiers, documentation, or tags.

Diagnostics

  • Validation: the SCSS service's doValidation over the virtual document, intersected with the value reading for a single-identifier css fragment (the "Virtual document" section), then extended by the keyframe property check below, memoized by RawValidationCache (the "Caching" section). With validate: false: no diagnostics and no code fixes.
  • Keyframe property check: the language service lints an unknown property only inside a style rule, so a declaration in a keyframe selector (from, to, 50%, or a list of them) is never checked. After doValidation, the plugin walks the already parsed stylesheet for KeyframeSelector nodes and checks each Declaration in them:
    • A selector counts when its enclosing keyframes at-rule has the keyword @keyframes in any letter case; a vendor-prefixed keyframes at-rule (@-webkit-keyframes) is excluded.
    • The check mirrors the language service's unknown-property rule: a name is known when it is in the default CSS data or in lint.validProperties; a name with one leading - (not --) follows lint.unknownVendorSpecificProperties instead; custom properties are skipped; a leading * or _ is dropped before the lookup; a name that holds an interpolation is skipped. Codes, messages, levels, and defaults (unknownProperties warning, unknownVendorSpecificProperties ignore) match the main validation.
    • The diagnostic range is the property node on the document doCodeActions reads, so the "Rename to ..." code action finds the declaration.
    • The walk runs only when the document text holds @keyframes in any letter case and at least one of the two rules would report; any other template pays for one text search.
    • Everything else stays with the main validation: a bare declaration in a keyframes tag, declarations in an @media rule there, declarations in a vendor-prefixed keyframes at-rule, and every other lint rule.
    • The check runs only with the built-in virtual-document provider and only with the default styles language service. A custom StylesLanguageServiceFactory may add CSS data the default list does not know, so its keyframe declarations stay unchecked instead of falsely reported.
  • Shown list (DiagnosticsFeature.getShownDiagnostics), the one list diagnostics and code fixes both read: each raw diagnostic mapped to template offsets under the diagnostics rule in "Mapping back to the template" (the "Virtual document" section: clamped at the closing wrapper, dropped inside the opening one, widened to whole escape runs), then the stray closing brace rule below.
  • Empty rules: with the built-in virtual-document provider, an emptyRules lint diagnostic is dropped when the rule body contains a template interpolation. The interpolation may produce declarations at runtime, so the plugin cannot prove that rule empty. The diagnostic stays for a genuinely empty body, including when an interpolation appears only in the selector. Rule-body braces are found in the template's CSS text after JavaScript escapes are cooked, so a JavaScript escape can contribute a structural brace. The boundary scanner ignores braces in comments, strings, CSS escapes, and unquoted url(...) arguments; an unclosed body extends to the template end while the user is editing. A custom provider owns its document's structure, so its diagnostics are not filtered against the template text.
  • Translation: the diagnostic's own code when numeric, CSS_DIAGNOSTIC_CODE (9999) otherwise; severity Error or none as Error, Warning as Warning, Information and Hint as Message; source is the plugin identity.
  • Stray closing brace: css-ruleorselectorexpected ("at-rule or selector expected") at the template end reports the wrapper's own closing brace, which the template's content closed early.
    • Causes: a stray }, or an unattached ;. An empty template reports nothing.
    • Always kept: never dropped because another diagnostic exists in the template (an unrelated lint warning, or one from the brace's own cascade).
    • Re-anchored to the stray }: the first } in the template's CSS text (getTemplateCssText) with no matching opener, read after JavaScript escapes are cooked, so a JavaScript escape can contribute a structural brace. The boundary scanner ignores a } in a string, comment, CSS escape, or unquoted url(...) argument; no placeholder fill holds a brace. The span is that one character.
    • No stray } (an unattached ;): stays at the template end, zero length.
    • The same code anywhere else in the template is a real diagnostic and stays where reported. Other end-of-template diagnostics (} expected, property value expected) carry other codes and stay.

Code fixes

  • Supported codes: CSS_DIAGNOSTIC_CODE only, a constant that builds no language service. A request whose error codes omit it gets no fixes.
  • A request asks about the shown diagnostics (the "Diagnostics" section) whose template span holds its caret (an empty request; start inclusive, end exclusive) or shares at least one character with its selection. None asked about: no fixes and no CSS service call. So a diagnostic the single-identifier intersection drops gets no fix, and a request after a diagnostics request is answered from the validation cache.
  • The asked-about raw diagnostics go to the SCSS service's doCodeActions with the request's range mapped into the virtual document. Only _css.applyCodeAction commands whose third argument is an array of text edits become fixes; each edit maps under the code-fix rule in "Mapping back to the template", and a command with any unmappable edit is dropped whole.

Exception recovery

  • Every StyledTemplateLanguageService entry point runs inside one recover wrapper, so a throw never reaches tsserver: the decorator forwards each result straight into the response for the whole file, TypeScript's own diagnostics included.
  • On a throw: one line <method> threw and was recovered: <stack> through the plugin logger (the tsserver log; a service constructed with a language service factory instead of a logger writes none), then the fallback:
    • completions: an empty completion list, a fresh object per call.
    • completion entry details: the unknown-entry details (the "Completions" section).
    • quick info: none.
    • diagnostics, code fixes, outlining spans: an empty list.
  • getSupportedCodeFixes returns its constant and cannot throw.
  • A recovered throw leaves the service answering later requests.

Caching

  • One cached virtual document and parsed stylesheet per service, reused only when canReuseVirtualDocument holds: same file name, same raw (unsubstituted) template text, same tag kind (the "Virtual document" section, "Reading"). Raw text, not substituted text: two placeholders of equal length can substitute identically while having different line maps. Same tag kind, because the same raw text under another tag kind can read differently; the reading is a pure function of the two, so the check computes neither the reading nor the substituted text.
  • A request answered from a cache (a validation hit, a reused document or completion result) never reads TemplateContext.text, which the decorator substitutes lazily, once per context, and every request brings a fresh context: an empty-template test or a template-end bound reads rawText.length (substitution keeps the length). test/unit/template-language-service.test.ts ("substitution on unchanged templates") counts substitutions to guard it.
  • A reused document's positionAt/offsetAt never call back into the TemplateContext that built it, only the line-start table above: TemplateContext.toPosition/toOffset are memoized by the decorator against the template's position in the file at the moment that context was constructed (StandardTemplateContext, typescript-template-language-service-decorator), so a request that edits the file outside the template moves the template without invalidating a reusable cache entry, and a document that kept consulting the old context would map to the wrong span for the rest of that session.
  • Completions cache the last result per position with the same reuse rule, both the raw CSS items and the translated tsserver entries, and clear on configuration change.
  • The nested at-rule catalog (the "Completions" section) is requested once per service on first use and kept for its lifetime: it does not depend on configuration.
  • A third-party VirtualDocumentProvider without canReuseVirtualDocument gets no reuse.
  • Diagnostics additionally memoize raw (untranslated) vscode.Diagnostic[] validation results across every template in a file, not just the one-entry virtual-document cache above. RawValidationCache (src/features/diagnostics.ts) is a least-recently-used map keyed by the tag kind (getReadingKey, the "Virtual document" section, "Reading") plus the template's own raw text. A file with many templates otherwise re-parses and re-validates every template on every request, because the one-entry cache above is evicted by the next template before the same template comes around again.
  • The validation cache is bounded by both an entry count (MAX_VALIDATION_CACHE_ENTRIES) and an estimated total byte size (MAX_VALIDATION_CACHE_BYTES), whichever binds first. An entry's estimated size is its key length plus, per diagnostic, its message length (both counted as UTF-16 code units times 2 bytes) plus a fixed per-diagnostic overhead constant (VALIDATION_CACHE_DIAGNOSTIC_OVERHEAD_BYTES). An entry estimated larger than the byte budget alone is never cached. pnpm test:scaling guards the byte budget with a long edit session through a realistic multi-kilobyte, many-diagnostic template.
  • The validation cache stores only raw vscode diagnostics, never translated ts.Diagnostics (which hold file: SourceFile and must not outlive the request). Reuse is trusted only for the built-in StyledVirtualDocumentProvider (checked by instanceof, not by a third-party object merely defining a same-named canReuseVirtualDocument, which this cache never calls), because only that provider's virtual text and validation are verified as a pure function of the tag kind and the raw text. A hit builds no document and computes no reading. It needs a line map only when it holds a diagnostic to map (an empty hit maps nothing): the session's line map when the session's cached document is reusable for that template, and a fresh line map otherwise. The cache clears on configuration change because lint settings change validation results.
  • The validation key length-prefixes the tag kind key before the raw text (buildValidationCacheKey, src/features/diagnostics.ts), so two different (tag kind key, raw text) pairs cannot concatenate to the same characters.
  • A stored key is copied so it references none of the open file's text (flattenCacheKey), only when the cache stores it (set). context.rawText is a slice of the whole open file's text, and V8 represents a slice of a long string as a view into its parent rather than a copy; the copy is a near-free defense against depending on that unspecified behavior (node --expose-gc test/performance/validation-cache-key-flattening-probe.mjs verifies it). A lookup (peek) compares the caller's unflattened key against stored keys by content, then re-inserts under the matching entry's already-flattened key on a hit.
  • Flattening uses pure UTF-16 concatenation and slicing, not a Node-only Buffer: this file is reachable from ./api, which a bundler could ship to a browser, and a UTF-8 round trip would rewrite an unpaired surrogate to U+FFFD, colliding two templates that differ only in one.

Configuration

  • Source: compilerOptions.plugins[] entry at startup, then configurePlugin requests. Each project has an internal ProjectConfigurationManager, while the package-root factory shares one internal dynamic configuration store across project plugin instances in the same tsserver ProjectService (src/tsserver/editor-configuration.ts). The store records none, the last valid legacy replacement, or the last valid editor overlay, so a project created later in the same session inherits the same dynamic state as existing projects. A WeakMap isolates separate embedded hosts in one process. The managers build on the public PluginConfigurationManager (src/configuration/plugin-configuration.ts), which normalizes JSON-shaped input, the shape tsconfig and configurePlugin deliver, and never throws on it, including when its logger throws. Parsing, logging, and applying configuration to each manager are contained so no exception escapes into tsserver; the calls to Project.getCompilerOptions() and Project.refreshDiagnostics() are unguarded because they are tsserver host calls that cannot throw (docs/tsserver-host.md).
  • Normalization per field:
    • tags: a list of strings, or one string as a one-item list. Anything else is rejected.
    • validate: a boolean, or the string "true" or "false". Anything else is rejected.
    • lint, emmet: an object; anything else is rejected. Inside lint, a level setting (every key of StyledPluginLintConfiguration except validProperties) takes "ignore", "warning", or "error", plus the aliases "off" (as "ignore") and "warn" (as "warning"), each in any letter case ("Error" as "error"); another value is rejected and the key dropped, so a key with a plugin default (defaultConfiguration.lint, such as emptyRules) keeps that default, and any other key gets the CSS language service's own default for that rule. The log message names the plugin default where one applies. validProperties takes a list, keeping its string entries and rejecting the rest, or one string as a one-item list. Unknown lint keys and every emmet key pass through unchanged.
    • A rejected value falls back to its default and logs one message to the tsserver log naming the setting, the accepted form, and the value received. An accepted alias or letter-case variant logs nothing, and neither does an absent field or a null or undefined top-level configuration. A field set to null is rejected.
    • A top-level key that is not one of the fields above is ignored and logs one message naming it and those fields, plus a "Did you mean" suggestion: the setting nearest by edit distance with letter case ignored, when that distance is at most 40% of the key's length (at least 1), so tag suggests tags and validation suggests validate. The keys tsserver adds to the configuration it passes (name and global, docs/tsserver-host.md) log nothing.
  • A normal configurePlugin update keeps the 1.0.1 behavior: it becomes the complete effective runtime configuration, fields absent from the update return to defaults, and any editor overlay is deactivated. The shared store broadcasts the normalized legacy snapshot to every live manager, including managers belonging to older decorators retained after a project reload.
  • A plain object with its own editorConfiguration key is instead an editor overlay envelope. Its editorConfiguration.extraTags field must be an array. String entries are trimmed, empty strings and non-string entries are dropped, and the rest are stably deduplicated. A non-empty input array from which every entry is dropped is invalid and preserves the current dynamic state; only the literal empty array clears the overlay. A valid normalized list replaces the previous overlay and is appended after each project's base tags with stable deduplication. It cannot change validate, lint, or emmet. An invalid envelope preserves the last valid dynamic state for the current tsserver session and never falls back to normal replacement behavior. A host that persists configuration must keep and replay its last valid payload, since a new process cannot recover an invalid payload's predecessor from old process memory.
  • Legacy runtime replacement and editor overlay are mutually exclusive dynamic states. A valid editor envelope, including extraTags: [], deactivates the legacy replacement, restores each project's original base, and appends the overlay. This last-kind-wins rule makes the effective state reproducible when a host restarts tsserver and replays its last valid plugin configuration.
  • TsServerStyledPlugin.create reads the project's base from the matching compilerOptions.plugins[] entry: the entry that is PluginCreateInfo.config itself, otherwise the entry whose name equals PluginCreateInfo.config.name, which can be an npm alias of this package. This preserves the base when tsserver puts a dynamic override in PluginCreateInfo.config after a pre-project configurePlugin request. When PluginCreateInfo.config is the project's own entry (the same object, or a structurally equal one), it is only the base: an editorConfiguration key in it is an unknown setting, not an envelope, and it never becomes shared legacy state. A separately constructed PluginCreateInfo.config with the same effective plugin settings as that project entry is still the project base; tsserver's injected name and global fields do not make it a legacy replacement. Only different effective settings become shared legacy state. Each created language service has a separate base manager. The shared store keeps live managers in a Set and wraps each project's close() once to remove all its managers, including those retained after reloads, before calling the original close method.
  • Effective configuration changes notify the language service through the existing onUpdatedConfig path. After all live managers receive the configuration, including older decorators retained after a reload, the shared store calls refreshDiagnostics() on one live project. This sends one event for all open files in that ProjectService. A failure while applying configuration to one manager is logged and does not stop the others from updating. Repeating the same normalized overlay, sending an initial overlay that leaves the project configuration unchanged, an invalid envelope, or an equivalent legacy snapshot does not notify, clear caches, or refresh diagnostics.
  • Editor configuration parsing and tag merging are linear in the number of base and additional tags and run only when configuration changes.
  • Defaults (tags, lint levels) live in PluginConfigurationManager.defaultConfiguration; user-facing documentation in docs/usage.md.

Public surface

  • Package root: the tsserver plugin factory only, at lib/index.js (1.0.1's exact main path), a CommonJS bundle. tsdown builds it as lib/index.cjs (cjsDefault turns export default createPlugin into module.exports = createPlugin) and a build:done hook renames it to lib/index.js and writes a nested lib/package.json ({"type": "commonjs"}) so Node and every supported TypeScript version's classic plugin resolution treat it as CommonJS despite the package root's own "type": "module". The rename matters because tsserver always loads plugins by reading main and resolving it with classic Node10 require(), never through the exports map: a .cjs-suffixed main fails to resolve on TypeScript 4.4 and older (docs/tsserver-host.md), the same class of gap already recorded there for a .mjs main. The single exports["."] condition (types plus default, no import/require split) serves this same file to both a require() caller and an import caller: Node's ESM loader synthesizes the default export from module.exports for the latter. Types are lib/index.d.cts (and a copy at lib/index.d.ts, see below), tsdown-generated from src/index.ts using export =, which every supported TypeScript version (5.0 through current) parses; a .cts consumer reads it as import plugin = require(...), an ESM consumer reads it as a default import.
  • Deep subpaths 1.0.1 resolved without any exports map keep resolving through explicit entries: ./lib/index, ./lib/index.js (both redirect to the root's lib/index.js runtime and lib/index.d.cts types), ./lib/api, ./lib/api.js (both resolve to the physical lib/api.js runtime and lib/api.d.ts types described below), and ./package.json. tsserver's own plugin loader only ever reads main for ., never these subpaths or the exports map at all, so they exist purely for a consumer's own require()/import(). Unlike ./api, these two subpaths carry one { types, default } mapping with no import/require split, because 1.0.1 shipped lib/api.js as a plain CommonJS file: a require() and an import x from of it both got the whole CommonJS exports object back, a shape a real ES module cannot reproduce (it never synthesizes a default export, so a consumer default-importing one gets TS1192). lib/api.js and lib/api.d.ts are real files, not only exports entries, so a resolver that ignores exports entirely (webpack 4, Jest before 28, the resolve package's default configuration) still finds them by walking node_modules for a file at the literal requested path; each is a thin CommonJS re-export of the ./api build below (module.exports = require('./esm/api.cjs'); export * from './esm/api.cjs'), written by the build:done hook in tsdown.config.ts, so this deep subpath and ./api's require condition share one module.exports object instead of shipping the compiled bundle twice. test/package-api/runtime.ts loads this file by its absolute path in the extracted tarball, bypassing exports the same way, to prove it is a real file rather than only an exports redirect target.
  • @styled/typescript-styled-plugin/api (import and require): StyledTemplateLanguageService, PluginConfigurationManager (and its ConfigurationManager alias, matching 1.0.1's class name), getTemplateSettings, and the configuration and provider types listed in src/api.ts. Removing or narrowing anything here is breaking and ships in a major changeset. Runtime is a real dual build: import gets lib/esm/api.mjs, require gets lib/esm/api.cjs, a genuine CommonJS bundle (not a stub) generated from the same src/api.ts by the same tsdown config's CommonJS format, so require('@styled/typescript-styled-plugin/api') works on every Node version this package supports, not only ones with require(esm) support; ./lib/api and ./lib/api.js (above) always resolve to this same CommonJS bundle, regardless of import or require syntax. Types mirror the runtime split: import gets lib/esm/api.d.mts (tsdown's normal ESM dts pass), require gets lib/esm/api.d.cts from the CommonJS format, which never imports from the ESM-only api.mjs (the cross-module-system import is what TS1479 flags on TypeScript 5.0 through 5.7) and cannot drift from the source the way a hand-kept copy could. Neither ./api bundle loads typescript-template-language-service-decorator at runtime: getTemplateSettings lives in src/template-settings.ts, apart from the tsserver entry that calls the decorator, and the decorator's TemplateSettings type reaches the declarations only.
  • moduleResolution: node10 ignores exports entirely, so a node10 consumer's deep import instead needs either a real file at the literal requested path or a typesVersions redirect. api uses typesVersions (package.json) to redirect to lib/esm/api.d.cts; lib/api and lib/api.js need no redirect, since node10's file-based lookup finds the physical lib/api.d.ts next to lib/api.js (above). lib/index and lib/index.js cannot use the same mechanism, because typesVersions also reaches the plugin loader itself for a subpath that equals main (docs/tsserver-host.md): lib/index.d.ts is instead a real, physically-copied file (mirroring 1.0.1's own lib/index.d.ts filename) that node10's default file-based lookup finds without any redirect.
  • Emitted declarations are contract: test/package-api type-checks the root entry (both a .cts import = require(...) consumer and an ESM default-import consumer), ./api (both conditions), a consumer written exactly to 1.0.1's published shape (consumer-1.0.1-shape.cts: an unguarded onConfigurationChanged call, a StyledPluginConfiguration with arbitrary lint/emmet keys, and a VirtualDocumentProvider implementation omitting the optional context parameter), and a moduleResolution: node10 consumer of the deep subpaths (consumer-node10.cts), and loads the packed tarball's root, ./api, and the deep subpaths from both require() and import(), including a default import of ./lib/api.js (test/package-api/runtime.ts). The type gates run against the minimum and maximum supported TypeScript plus two versions in between, plus the node10 consumer on the current version, all through pnpm test:package-api:consumers (scripts/test-package-api-types.ts), which runs each tsconfig.consumers.<gate>.json (the shared tsconfig.consumers.json base excepted) with the TypeScript its typescript/* paths entry names: that override maps the specifier to that exact version's own install (test/e2e/node_modules/<alias>/*, an alias declared in test/e2e/package.json), so the ambient typescript/lib/tsserverlibrary types match the compiler running the check instead of whichever typescript version the root resolves. Adding a TypeScript version means adding one tsconfig. The node10 gate additionally needs a real node_modules/@styled/typescript-styled-plugin self-link at the repository root, which the same runner creates when missing and re-points when it resolves anywhere else, because node10 resolution has no self-reference feature to fall back on the way node16/nodenext/bundler do. A moduleResolution: bundler gate (tsconfig.consumers.bundler.json) default-imports ./lib/api.js (consumer-lib-api-default.mts, also checked under the default node16-family config above) to prove the CommonJS shape holds under bundler resolution too.
  • StyledPluginConfiguration is the fully-resolved shape 1.0.1 published under this name (tags, validate, lint, emmet all required), with lint and emmet typed exactly as 1.0.1 declared them, the open { [key: string]: any } shape, not the closed StyledPluginLintConfiguration / StyledPluginEmmetConfiguration interfaces; those richer, closed shapes live on StyledPluginConfigurationInput, the partial shape for building a configuration from individual overrides, and on the standalone interfaces themselves.
  • The package root factory's declared return type has create and onConfigurationChanged both required, with onConfigurationChanged's parameter typed any, matching 1.0.1's own StyledPlugin class exactly rather than the host's ts.server.PluginModule (both members optional there): a non-exported StyledPlugin interface local to src/index.ts states this contract, and TsServerStyledPlugin (src/tsserver/tsserver-plugin.ts) already implements both members as required.