@canonical/terrazzo-lsp

中文文档
0.44.0发布于 2026/10/23LGPL-3.0TypeScriptES Module构建来源已验证近 30 天下载 6040

Language server providing CSS custom property intelligence for design token workflows. Includes completions, hover, diagnostics, go-to-definition, rename, document colours, and workspace symbols.

原始使用文档
文档目录12 节
  1. Features
  2. Editor Setup
  3. CLI
  4. Diagnostics Reference
  5. CSS diagnostics example
  6. DTCG diagnostics example
  7. Suppression syntax
  8. Configuration
  9. Full configuration reference
  10. VS Code extension settings
  11. Development
  12. Architecture

@canonical/terrazzo-lsp

Language server providing CSS custom property intelligence for design token workflows. Reads tokens.json build artifacts and provides editor features for CSS and SCSS files.

Features

FeatureDescription
CompletionsContext-aware suggestions for var(--...) references, prioritised by type assignability, semantic tier, and provenance.
HoverToken metadata including resolved value, colour swatch, alias chain, tier badge, selector context, and source location.
DiagnosticsType mismatch detection, missing/stale fallback warnings, unreachable token analysis, primitive usage warnings, and more.
Go to DefinitionJump from a var() reference to the token declaration.
RenameRename a CSS custom property across all files in the import graph.
Document ColoursInline colour swatches and colour picker for token-backed colour values.
Semantic TokensSyntax highlighting distinguishing artifact tokens, local properties, and external references.
Workspace SymbolsSearch tokens across the workspace by name or type.

Editor Setup

VS Code (recommended):

npm install -D @canonical/design-tokens
npx @canonical/terrazzo-lsp-extension

The extension auto-detects bun first and falls back to node >= 22.

CLI

npx terrazzo-lsp --stdio                # Start LSP server on stdio
npx terrazzo-lsp --stdio --allow-degraded  # Start with reduced capabilities when config is missing
npx terrazzo-lsp check [globs]          # Run diagnostics on CSS files
npx terrazzo-lsp status                 # Show config and artifact status
npx terrazzo-lsp inspect <var>          # Inspect a CSS custom property
npx terrazzo-lsp resolve <spec>         # Resolve an import specifier
npx terrazzo-lsp graph <file>           # Show import graph from a file

Diagnostics Reference

The LSP emits 14 diagnostic codes. CSS diagnostics run on every CSS/SCSS file in the workspace. DTCG diagnostics run once when loading tokens.json artifacts and validate conformance to the DTCG 2025.10 specification. Every diagnostic can be configured to "error", "warning", "info", or "off" in terrazzo-lsp.config.json.

CodeConfig KeyDefaultDescription
css/unknown-varunknownPropertiesoffA var() reference does not match any known custom property.
css/missing-fallbackmissingFallbackwarningA var() reference to a non-artifact property has no fallback value and no @property registration. Skipped for artifact tokens since they are guaranteed to be defined.
css/stale-fallbackstaleFallbackwarningThe fallback literal in a var() does not match the token's current resolved value.
css/type-mismatchtypeMismatcherrorA token's DTCG type is incompatible with the CSS property (e.g. colour token in padding).
css/type-uncertaintypeUncertaininfoA typed token appears in a shorthand or context where multiple value types are acceptable.
css/unreachable-tokenunreachableTokenwarningThe token's artifact output file is not reachable through the @import graph or global stylesheets.
css/primitive-tokenprimitiveTokenwarningDirect usage of a primitive-tier token where a semantic alias should be preferred.
css/scoped-usagescopedDeclarationwarningA token declared under a specific selector scope is used in a broader scope.
css/no-color-schemelightDarkNoSchemeinfoA light-dark() value is used without a color-scheme declaration on the selector or an ancestor.
dtcg/broken-aliasbrokenAliaserrorAn alias reference in the artifact points to a token ID that does not exist.
dtcg/schema-violationschemaViolationerrorA token's value is invalid for its declared $type (e.g. $type: color with a non-colour value).
dtcg/circular-aliascircularAliaserrorThe alias chain forms a cycle — a token ID appears more than once in the resolution path.
dtcg/missing-typeinferredTypeinfoA token has no explicit $type and its type is ambiguous.
dtcg/draft-syntaxdraftFormatinfoA token uses pre-standardisation draft field syntax (value/type without $ prefix).

CSS diagnostics example

The example below triggers every CSS diagnostic in one file:

/* Assume the following tokens exist in the artifact:
 *   --color-fg           : oklch(17.2% 0 0)        tier: semantic, type: color
 *   --spacing-sm         : 0.5rem                   tier: semantic, type: dimension
 *   --color-palette-blue : oklch(50% 0.15 250)      tier: primitive, type: color
 *   --button-pad         : 0.75rem                  tier: semantic, scoped to .button
 *   --unreachable-token  : 1rem                     (in a file not imported by this sheet)
 */

/* css/unknown-var — off by default, enable via config */
.unknown   { margin: var(--does-not-exist); }

/* css/missing-fallback — no fallback for a non-artifact property */
.missing   { padding: var(--local-pad); }

/* css/stale-fallback — resolved value is 0.5rem, not 16px */
.stale     { gap: var(--spacing-sm, 16px); }

/* css/type-mismatch — colour token in a length context */
.type-err  { width: var(--color-fg); }

/* css/type-uncertain — dimension in a shorthand accepting many types */
.type-warn { background: var(--spacing-sm); }

/* css/unreachable-token — output file not in @import graph */
.unreach   { margin: var(--unreachable-token); }

/* css/primitive-token — prefer semantic alias */
.primitive { color: var(--color-palette-blue); }

/* css/scoped-usage — --button-pad is scoped to .button */
.card      { padding: var(--button-pad); }

/* css/no-color-scheme — light-dark() without color-scheme */
.no-scheme { color: light-dark(black, white); }

DTCG diagnostics example

DTCG diagnostics surface problems in the token definitions themselves. These appear on the tokens.json artifact entry, not in CSS files:

{
  // dtcg/broken-alias — alias target does not exist
  "color.ghost":   { "aliasChain": ["color.nonexistent"], "type": "color" },

  // dtcg/schema-violation — "not-a-colour" is not a valid CSS colour
  "color.invalid": { "valueLight": "not-a-colour", "type": "color" },

  // dtcg/circular-alias — loop-a → loop-b → loop-a
  "color.loop-a":  { "aliasChain": ["color.loop-b", "color.loop-a"], "type": "color" },

  // dtcg/missing-type — no $type field, type is ambiguous
  "spacing.bare":  { "valueLight": "4px", "type": null },

  // dtcg/draft-syntax — uses pre-standard value/type without $ prefix
  "color.legacy":  { "type": "color", "extensions": { "com.terrazzo.draft-syntax": true } }
}

Suppression syntax

Diagnostics can be suppressed inline with comments:

/* Disable all checks for a region: */
/* terrazzo-lsp-disable */
.suppressed { width: var(--color-fg); }
/* terrazzo-lsp-enable */

/* Disable a specific code for the next line: */
/* terrazzo-lsp-disable css/primitive-token */
.selective { color: var(--color-palette-blue); }
/* terrazzo-lsp-enable css/primitive-token */

Configuration

Create a terrazzo-lsp.config.json in your workspace root:

{
  "artifacts": ["@canonical/design-tokens/dist/tokens.json"],
  "globalStylesheets": [".storybook/styles.css"]
}

If no config file is present, the output panel logs every candidate path it tried, prints a ready-to-copy starter config, and then exits. For temporary degraded startup, pass --allow-degraded.

{ "artifacts": ["@canonical/design-tokens/dist/tokens.json"] }

Full configuration reference

{
  "artifacts": [],
  "distDir": "dist",
  "scanGlobs": ["src/**/*.css", "src/**/*.scss"],
  "globalStylesheets": null,
  "diagnostics": {
    "unknownProperties": "off",
    "missingFallback": "warning",
    "staleFallback": "warning",
    "typeMismatch": "error",
    "typeUncertain": "info",
    "unreachableToken": "warning",
    "primitiveToken": "warning",
    "scopedDeclaration": "warning",
    "lightDarkNoScheme": "info",
    "brokenAlias": "error",
    "schemaViolation": "error",
    "circularAlias": "error",
    "inferredType": "info",
    "draftFormat": "info",
    "ignoreGlobs": []
  },
  "hover": {
    "showColourSwatches": true,
    "showSelectorContext": true,
    "showProvenanceBadge": true,
    "showAliasChain": true,
    "showSourceLocation": true,
    "showNavigationTier": true,
    "showSpecReferences": true
  },
  "inlayHints": {
    "enabled": false,
    "showColourSwatches": true
  },
  "logLevel": "info"
}
KeyDescription
artifactsPaths to tokens.json build artifacts. Bare specifiers resolve through node_modules/. Relative paths must start with ./ or ../.
distDirDirectory containing *.css.map files for source-mapping.
scanGlobsGlob patterns for CSS/SCSS files to scan for diagnostics.
globalStylesheetsCSS files implicitly reachable from every document. null means auto-derive from the artifact.
diagnosticsPer-diagnostic severity overrides. Values: "error", "warning", "info", "off".
diagnostics.ignoreGlobsGlob patterns for files excluded from diagnostics.
hoverToggle individual sections of the hover popup.
inlayHintsInlay hint display (disabled by default).
logLevelServer log verbosity: "off", "error", "warn", "info", "debug".

VS Code extension settings

SettingDefaultDescription
terrazzo-lsp.serverPath""Path to dist/esm/cli.js. If empty, uses the bundled server.
terrazzo-lsp.runtime""Runtime override. Empty = auto-detect (bun preferred, node >= 22 fallback).
terrazzo-lsp.trace.server"off""off" shows startup summary only. "verbose" adds per-request traces to the output channel.

Development

Architecture

The LSP server is organised into four main layers:

LayerPathResponsibility
Protocolprotocol/JSON-RPC message parsing, config loading, request/response matching
Runtimeruntime/Server lifecycle, document management, import graph building, worker dispatch
Graphgraph/Token graph data structure, artifact loading, reachability cache
Providersproviders/All LSP features: completions, hover, diagnostics, rename, etc.

Diagnostics pipeline:

CSS diagnostics:  orchestrateDiagnostics → per-rule check modules → makeDiagnostic
DTCG diagnostics: produceArtifactDiagnostics → per-rule check modules → makeDiagnostic

Each diagnostic rule lives in its own file (diagnostics/checkMissingFallback.ts, artifactDiagnostics/checkBrokenAlias.ts, etc.) with a co-located .tests.ts file. The orchestrator loops over usages (CSS) or tokens (DTCG) and delegates to each check function.

bun run build      # Compile LSP server (tsc)
bun run test       # Run tests
bun run check      # Lint + type check

版本与发布记录

@canonical/terrazzo-lsp 共发布 26 个版本,首次发布于 2026/03/08;过去 12 个月发布了 26 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.44.0latest2026/10/2317 天前
0.43.02026/10/011 个月前
0.43.0-experimental.0experimental2026/09/291 个月前
0.10.02026/09/092 个月前
0.9.02026/09/072 个月前
0.8.22026/08/282 个月前

关于 @canonical/terrazzo-lsp 的常见问题

@canonical/terrazzo-lsp 是什么?

Language server providing CSS custom property intelligence for design token workflows. Includes completions, hover, diagnostics, go-to-definition, rename, document colours, and workspace symbols.

如何安装 @canonical/terrazzo-lsp?

在项目目录运行 npm install @canonical/terrazzo-lsp,或使用 pnpm add / yarn add / bun add。它还提供命令行工具 terrazzo-lsp,可以用 npx terrazzo-lsp 直接运行。

@canonical/terrazzo-lsp 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@canonical/terrazzo-lsp 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@canonical/terrazzo-lsp 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@canonical/terrazzo-lsp 可以商用吗?

@canonical/terrazzo-lsp 使用 LGPL-3.0 许可。弱 Copyleft:作为库被调用时通常不要求开源你自己的代码,但修改库本身需以 LGPL 开源;前端打包合并后的适用边界存在不同理解。以上为概括,不构成法律意见,请以许可原文为准。

@canonical/terrazzo-lsp 的下载量有多少?

根据 npm 官方下载统计,@canonical/terrazzo-lsp 在 2026/10/09 – 2026/11/07 这 30 天内被下载 6,040 次,日均约 201 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@canonical/terrazzo-lsp 还在维护吗?

最新版本 0.44.0 发布于 2026/10/23(17 天前);至今共发布 26 个版本,其中过去 12 个月发布了 26 个;首次发布于 2026/03/08。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。