### DefaultConfig Example Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/configuration.md Example usage of DefaultConfig. ```go config := types.DefaultConfig() ``` -------------------------------- ### Multi-Schema Workspaces Configuration Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/docs/SCHEMA_VERSIONING.md Example JSON configuration for package.json or LSP settings to support multiple token files with different schemas. ```json // package.json or LSP configuration { "tokenFiles": [ { "path": "legacy/tokens.json", "schemaVersion": "draft" }, { "path": "new/design.tokens.json" // Auto-detects 2025.10 from $schema field } ] } ``` -------------------------------- ### SetOutput Example Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/logging.md Example usage of the SetOutput function. ```go var buf bytes.Buffer log.SetOutput(&buf) defer log.SetOutput(os.Stderr) // Log messages go to buf instead of stderr ``` -------------------------------- ### Info Example Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/logging.md Example usage of the Info function. ```go log.Info("Loading tokens from: %s", filePath) log.Info("Loaded %d tokens", manager.Count()) ``` -------------------------------- ### Level.String Example Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/logging.md Example usage of the Level.String method. ```go log.SetLevel(log.LevelInfo) current := log.GetLevel() println(current.String()) // Outputs: "LevelInfo" ``` -------------------------------- ### Replacing groupMarkers with $root Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/docs/SCHEMA_VERSIONING.md Example showing the replacement of groupMarkers with the $root token for migration. ```json // Before (Draft with groupMarkers) "color": { "_": { "$type": "color", "$value": "#DD0000" }, "light": { ... } } // After (2025.10) "color": { "$root": { "$type": "color", "$value": { "colorSpace": "srgb", ... } }, "light": { ... } } ``` -------------------------------- ### Warn Example Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/logging.md Example usage of the Warn function. ```go log.Warn("Deprecated feature used: %s", featureName) ``` -------------------------------- ### SetLevel Example Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/logging.md Example usage of the SetLevel function. ```go log.SetLevel(log.LevelDebug) // Show all messages log.SetLevel(log.LevelInfo) // Hide debug messages log.SetLevel(log.LevelWarn) // Show only warnings and errors ``` -------------------------------- ### New reference syntax Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/docs/SCHEMA_VERSIONING.md Example illustrating both curly brace and JSON Pointer reference syntaxes, both of which are supported in 2025.10. ```json // Both still work in 2025.10 "alias1": { "$value": "{color.primary}" // Curly braces }, "alias2": { "$ref": "#/color/primary" // JSON Pointer (2025.10+) } ``` -------------------------------- ### Example New Schema Fixture Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/docs/SCHEMA_VERSIONING.md An example JSON fixture for the new 2026.01 schema version, including the $schema declaration and a basic token structure. ```json { "$schema": "https://www.designtokens.org/schemas/2026.01.json", "color": { "primary": { "$value": { ... }, "$type": "color" } } } ``` -------------------------------- ### Feature Flag Check Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/docs/SCHEMA_VERSIONING.md Example of how to check for feature support using the SupportsFeature() method. ```go handler, _ := registry.Get(schemaVersion) if handler.SupportsFeature("json-pointer") { // Enable JSON Pointer references } ``` -------------------------------- ### In-Memory Filesystem Example Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/CLAUDE.md Shows how to use `testing/fstest.MapFS` for tests requiring filesystem abstraction. ```go import "testing/fstest" fs := fstest.MapFS{ "tokens.json": &fstest.MapFile{ Data: []byte(`{"color": {"$value": "#fff"}}`), }, } ``` -------------------------------- ### Debug Example Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/logging.md Example usage of the Debug function. ```go log.Debug("Method %s started", methodName) log.Debug("Found %d tokens", count) ``` -------------------------------- ### Updating color values Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/docs/SCHEMA_VERSIONING.md Example demonstrating the change in color value representation from string to structured object during migration. ```json // Before (Draft) "primary": { "$type": "color", "$value": "#FF6B35" } // After (2025.10) "primary": { "$type": "color", "$value": { "colorSpace": "srgb", "components": [1.0, 0.42, 0.21], "alpha": 1.0, "hex": "#FF6B35" } } ``` -------------------------------- ### Logging Example Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/README.md Example of how to use the internal logging package for different log levels. ```go import "bennypowers.dev/dtls/internal/log" log.Debug("Detailed message: %v", value) log.Info("Important event: %s", event) log.Warn("Non-critical issue: %s", issue) log.Error("Failure: %v", err) ``` -------------------------------- ### Install the language server binary Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/CONTRIBUTING.md Installs the built binary to `~/.local/bin/design-tokens-language-server`. ```sh make install ``` -------------------------------- ### CSS Example Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/internal/parser/html/testdata/style-tag.html A simple CSS example demonstrating variable usage. ```css :root { --color-primary: #0000ff; } .button { color: var(--color-primary); background: var(--bg-color, #fff); } ``` -------------------------------- ### Current JSON Configuration Example Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/ideas/AUTODISCOVER.md Example of how users currently configure token files explicitly in package.json. ```json { "designTokensLanguageServer": { "tokensFiles": [ "./tokens/colors.json", "./tokens/spacing.json" ] } } ``` -------------------------------- ### Error Example Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/logging.md Example usage of the Error function. ```go log.Error("Failed to parse file: %v", err) log.Error("Invalid token: %s", tokenName) ``` -------------------------------- ### Loading Test Data Example Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/CLAUDE.md Demonstrates how to load test data files using paths relative to the test file. ```go func TestDetectVersion(t *testing.T) { content, err := os.ReadFile("testdata/detection/explicit-draft.json") require.NoError(t, err) // ... } ``` -------------------------------- ### Log Format Example Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/logging.md Example output format for log messages. ```text [DTLS] INFO: Loading tokens from: /home/user/tokens.json [DTLS] ERROR: Failed to parse file: unexpected token [DTLS] DEBUG: Method initialize started [DTLS] WARN: Deprecated feature used: autoDiscover ``` -------------------------------- ### Good Logging Example Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/CLAUDE.md Demonstrates the correct usage of the internal log package for logging messages in the Go application. ```go // GOOD - Uses internal log package import "bennypowers.dev/dtls/internal/log" log.Info("Loading tokens from: %s", filePath) log.Error("Failed to parse file: %v", err) log.Debug("Method %s started", methodName) ``` -------------------------------- ### Command Line Entry Point Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/README.md Starts the Design Tokens Language Server using standard input/output. ```go // cmd/design-tokens-language-server/main.go server, _ := lsp.NewServer() server.RunStdio() // Start LSP server on stdin/stdout ``` -------------------------------- ### ParseCSSFromDocument Example Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/parsers.md Example usage of ParseCSSFromDocument. ```go result, err := parser.ParseCSSFromDocument(":root { --color-primary: #ff0000; }", "css") if err != nil { log.Fatal(err) } // Use result... ``` -------------------------------- ### IsCSSSupportedLanguage Example Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/parsers.md Example usage of IsCSSSupportedLanguage. ```go if parser.IsCSSSupportedLanguage("css") { // Can parse CSS from this language } ``` -------------------------------- ### Testing Log Output Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/logging.md Example test function to capture and assert log output. ```go import ( "bytes" "testing" "bennypowers.dev/dtls/internal/log" ) func TestSomething(t *testing.T) { var buf bytes.Buffer log.SetOutput(&buf) defer log.SetOutput(nil) // Test code that logs... log.Info("Test message") output := buf.String() if !strings.Contains(output, "Test message") { t.Error("Expected message not found") } } ``` -------------------------------- ### CSSContentSpans Example Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/parsers.md Example usage of CSSContentSpans for HTML with embedded styles. ```go // For HTML with embedded styles spans := parser.CSSContentSpans(" ", "html") // Returns: [":root { --color: red; }"] ``` -------------------------------- ### Server Log Examples Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/errors.md Examples of log messages that might appear in the server logs. ```text [DTLS] ERROR: Failed to parse file: unexpected token [DTLS] DEBUG: Method textDocument/hover started [DTLS] ERROR: textDocument/hover error: token not found ``` -------------------------------- ### Adding $schema field Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/docs/SCHEMA_VERSIONING.md Example of adding the $schema field to a token file for migration from Draft to 2025.10. ```json { "$schema": "https://www.designtokens.org/schemas/2025.10.json", ... } ``` -------------------------------- ### Example JSON for Group Markers Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/extensions/vscode/README.md Demonstrates how to structure a token file to use group markers. ```json { "color": { "red": { "GROUP": { "$value": "#FF0000", "$description": "Red color", "darker": { "$value": "#AA0000", "$description": "Darker red color" } } } } } ``` -------------------------------- ### Example package.json configuration for Group Markers Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/extensions/vscode/README.md Shows how to configure the extension in package.json to recognize custom group markers. ```json "designTokensLanguageServer": { "prefix": "my-ds", "groupMarkers": ["GROUP"] } ``` -------------------------------- ### RunStdio Method Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/server.md Starts the LSP server using stdin/stdout transport, communicating with the editor via JSON-RPC protocol. ```go server, _ := lsp.NewServer() if err := server.RunStdio(); err != nil { log.Fatal("Server failed:", err) } ``` -------------------------------- ### Zero-Config with Auto-Discovery (After) Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/ideas/AUTODISCOVER.md Example of `package.json` configuration when auto-discovery is enabled, requiring no explicit file paths. ```json { "designTokensLanguageServer": { // No configuration needed! // Auto-discovers: // - tokens.json // - *.tokens.json // - design-tokens.json // etc. } } ``` -------------------------------- ### Bad Logging Example Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/CLAUDE.md Illustrates incorrect logging practices that will corrupt the LSP protocol by writing to stdout. ```go // BAD - Will corrupt LSP protocol fmt.Println("Loading tokens...") // BREAKS LSP! fmt.Printf("Error: %v\n", err) // BREAKS LSP! log.Println("Debug message") // Wrong logger! fmt.Fprintf(os.Stdout, "msg\n") // BREAKS LSP! ``` -------------------------------- ### Example CSS Variables Output Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/README.md Shows how design tokens are exposed as CSS custom properties, with examples of naming conventions. ```css :root { --color-primary: #ff0000; } ``` -------------------------------- ### Get Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/documents.md Retrieves a document by URI. ```go func (m *Manager) Get(uri string) *Document ``` ```go doc := manager.Get("file:///home/user/tokens.json") if doc != nil { println(doc.Content()) } ``` -------------------------------- ### Log Message Example Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/errors.md Example of an error reported to the client via a `window/logMessage` notification. ```json { "type": 1, "message": "textDocument/hover: token not found: color-primary" } ``` -------------------------------- ### Test Schema Handler Color Formatting Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/docs/SCHEMA_VERSIONING.md Adds a test case to verify the color formatting logic for the V2026_01SchemaHandler. ```go func TestV2026_01SchemaHandler_FormatColorForCSS(t *testing.T) { handler := &schema.V2026_01SchemaHandler{} // Test color formatting for this version } ``` -------------------------------- ### Test Logging Output Capture Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/CLAUDE.md Example of how to capture log output in tests by redirecting the log output to a buffer. ```go import ( "bytes" "bennypowers.dev/dtls/internal/log" ) func TestSomething(t *testing.T) { var buf bytes.Buffer log.SetOutput(&buf) defer log.SetOutput(nil) // Test code that logs... output := buf.String() assert.Contains(t, output, "expected message") } ``` -------------------------------- ### textDocument/definition Example Response (Location) Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/endpoints.md An example JSON response for the textDocument/definition endpoint when a single location is returned. ```json { "uri": "file:///home/user/tokens.json", "range": { "start": { "line": 5, "character": 8 }, "end": { "line": 5, "character": 25 } } } ``` -------------------------------- ### Test Schema Handler Feature Support Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/docs/SCHEMA_VERSIONING.md Adds a test case to verify that the V2026_01SchemaHandler correctly reports its supported features. ```go func TestV2026_01SchemaHandler_SupportsFeature(t *testing.T) { handler := &schema.V2026_01SchemaHandler{} assert.True(t, handler.SupportsFeature("resolution-order")) assert.True(t, handler.SupportsFeature("json-pointer")) // Test all features } ``` -------------------------------- ### FindByPrefix Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/tokens.md Returns all tokens whose names start with the given prefix. ```Go func (m *Manager) FindByPrefix(prefix string) []*Token ``` ```Go colorTokens := manager.FindByPrefix("color-") ``` -------------------------------- ### Explicit Configuration (Before Auto-Discovery) Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/ideas/AUTODISCOVER.md Example of manual configuration for design tokens files in `package.json`. ```json { "designTokensLanguageServer": { "tokensFiles": [ "./design/tokens/colors.json", "./design/tokens/spacing.json", "./design/tokens/typography.json" ] } } ``` -------------------------------- ### Define Schema Version Constants and URL Mapping Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/docs/SCHEMA_VERSIONING.md Adds a new schema version constant and maps its corresponding URL in the schemaURLs map. ```go const ( Unknown SchemaVersion = "unknown" Draft SchemaVersion = "draft" V2025_10 SchemaVersion = "2025.10" V2026_01 SchemaVersion = "2026.01" // NEW VERSION ) // Map schema URLs to versions var schemaURLs = map[string]SchemaVersion{ "https://www.designtokens.org/schemas/draft.json": Draft, "https://www.designtokens.org/schemas/2025.10.json": V2025_10, "https://www.designtokens.org/schemas/2026.01.json": V2026_01, // NEW URL } ``` -------------------------------- ### Register the New Schema Handler Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/docs/SCHEMA_VERSIONING.md Adds the newly implemented V2026_01SchemaHandler to the registry in the NewRegistry() function. ```go func NewRegistry() *Registry { r := &Registry{ handlers: make(map[SchemaVersion]SchemaHandler) } // Register built-in handlers r.Register(&DraftSchemaHandler{}) r.Register(&V2025_10SchemaHandler{}) r.Register(&V2026_01SchemaHandler{}) // NEW HANDLER return r } ``` -------------------------------- ### Package.json Configuration Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/extensions/vscode/README.md Example configuration block for designTokensLanguageServer in a project's package.json. ```json { "name": "@my-design-system/elements", "designTokensLanguageServer": { "prefix": "my-ds", "tokensFiles": [ "npm:@my-design-system/tokens/tokens.json", { "path": "npm:@his-design-system/tokens/tokens.json", "prefix": "his-ds", "groupMarkers": ["GROUP"] }, { "path": "./docs/docs-site-tokens.json", "prefix": "docs-site" }, { "path": "~/secret-projects/fanciest-tokens.json", "prefix": "shh" } ] } } ``` -------------------------------- ### Update Schema Detection with Duck Typing Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/docs/SCHEMA_VERSIONING.md Adds duck typing heuristics to detect the new schema version based on unique features. ```go func detectByFeatures(content []byte) (SchemaVersion, error) { // Check for version-specific reserved fields if hasField(content, "newFeature2026") { return V2026_01, nil } // Existing detection logic... } ``` -------------------------------- ### Prefix Field Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/configuration.md Global CSS variable prefix. Example: "ds" generates "--ds-color-primary". Can be overridden per-file. ```go Prefix string ``` -------------------------------- ### Implement SchemaHandler Interface for a New Version Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/docs/SCHEMA_VERSIONING.md Defines a new handler type for the 2026.01 schema, implementing the SchemaHandler interface with version-specific logic for validation, formatting, and feature support. ```go // V2026_01SchemaHandler implements SchemaHandler for the 2026.01 schema type V2026_01SchemaHandler struct{} func (h *V2026_01SchemaHandler) Version() SchemaVersion { return V2026_01 } func (h *V2026_01SchemaHandler) ValidateTokenNode(node *yaml.Node) error { // Add version-specific validation logic // Check for required fields, validate structure, etc. return nil } func (h *V2026_01SchemaHandler) FormatColorForCSS(colorValue interface{}) string { // Implement color formatting for this version // Handle new color formats introduced in this version return "" } func (h *V2026_01SchemaHandler) SupportsFeature(feature string) bool { // Declare which features this version supports switch feature { case "curly-brace-references", "json-pointer", "extends", "root": return true case "resolution-order": // Example new feature return true default: return false } } ``` -------------------------------- ### Get Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/tokens.md Retrieves a token by name or CSS variable reference. Supports multiple formats: - Token name with hyphens: "color-primary" - DTCG path with dots: "color.primary" - CSS variable without prefix: "--color-primary" - CSS variable with prefix: "--prefix-color-primary" Returns the first matching token if multiple exist across files. ```Go func (m *Manager) Get(nameOrVar string) *Token ``` ```Go token := manager.Get("color-primary") if token != nil { println(token.Value) } ``` -------------------------------- ### GetBuildInfo Function Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/utilities.md Returns detailed build information as a map. ```go func GetBuildInfo() map[string]string ``` ```go info := version.GetBuildInfo() println("Commit:", info["gitCommit"]) ``` -------------------------------- ### GetConfig Method Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/configuration.md Returns the current server configuration (user settings only). ```go func (s *Server) GetConfig() ServerConfig ``` -------------------------------- ### NewServer Constructor Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/server.md Creates a new Design Tokens LSP server with all internal managers and protocol handlers initialized. ```go package main import ( "log" "bennypowers.dev/dtls/lsp" ) func main() { server, err := lsp.NewServer() if err != nil { log.Fatal("Failed to create server:", err) } if err := server.RunStdio(); err != nil { log.Fatal("Server error:", err) } } ``` -------------------------------- ### Server Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/types.md The main Language Server implementation. ```go type Server struct { // Fields are unexported; use methods for access } ``` -------------------------------- ### Diagnostic Message Example Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/errors.md Example of a parsing or token error presented as a document diagnostic. ```json { "range": { "start": { "line": 5, "character": 8 }, "end": { ... } }, "severity": 1, "message": "Undefined token reference: color-unknown", "source": "design-tokens" } ``` -------------------------------- ### PathToURI Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/utilities.md Converts a file system path to a file:// URI. Handles Windows and POSIX paths correctly. ```go func PathToURI(path string) string ``` ```go uri := uriutil.PathToURI("C:\\Users\\test\\tokens.json") // Returns: "file:///C:/Users/test/tokens.json" ``` -------------------------------- ### DefaultConfig Function Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/configuration.md Returns the default server configuration. ```go func DefaultConfig() ServerConfig ``` -------------------------------- ### Request Response Error Example Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/errors.md Example of a request failure returning an LSP error object. ```json { "jsonrpc": "2.0", "id": 1, "error": { "code": -32603, "message": "textDocument/hover: internal error", "data": { "details": "panic: ..." } } } ``` -------------------------------- ### SetConfig Method Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/configuration.md Updates the server configuration. ```go func (s *Server) SetConfig(config ServerConfig) ``` -------------------------------- ### ServerConfig Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/types.md User-provided configuration for the server. ```go type ServerConfig struct { TokensFiles []any Resolvers []string Prefix string GroupMarkers []string GroupMarkersSet bool NetworkFallback bool NetworkTimeout int CDN string } ``` -------------------------------- ### LSP Error Handling Example Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/endpoints.md Standard LSP error response format. ```json { "jsonrpc": "2.0", "id": 1, "error": { "code": -32600, "message": "Invalid request", "data": { "details": "..." } } } ``` -------------------------------- ### ServerConfig Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/configuration.md User-provided configuration for the language server. ```go type ServerConfig struct { // TokensFiles specifies token files to load // Can be strings (paths) or objects with path, prefix, groupMarkers TokensFiles []any // Resolvers specifies DTCG resolver documents Resolvers []string // Prefix is the global CSS variable prefix Prefix string // GroupMarkers are token names treated as group names GroupMarkers []string // GroupMarkersSet tracks if GroupMarkers was explicitly provided GroupMarkersSet bool // NetworkFallback enables CDN fallback for npm: specifiers NetworkFallback bool // NetworkTimeout is max time in seconds for CDN requests NetworkTimeout int // CDN selects the CDN provider for network fallback CDN string } ``` -------------------------------- ### Build Command Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/README.md Basic command to build the design-tokens-language-server executable. ```bash go build ./cmd/design-tokens-language-server ``` -------------------------------- ### TokenFile Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/tokens.md Configuration for a token file source. ```go type TokenFile struct { Path string // Path to the token file Prefix string // CSS variable prefix GroupMarkers []string // Token names that can also be groups } ``` -------------------------------- ### GetAll Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/tokens.md Returns all stored tokens. ```Go func (m *Manager) GetAll() []*Token ``` -------------------------------- ### GetAll Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/documents.md Returns all managed documents. ```go func (m *Manager) GetAll() []*Document ``` -------------------------------- ### Hybrid Approach (Explicit + Auto-Discovery) Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/ideas/AUTODISCOVER.md Example of `package.json` configuration that combines explicit file paths (including npm packages) with auto-discovered files. ```json { "designTokensLanguageServer": { "tokensFiles": [ "npm:@company/design-tokens", // Explicit npm package "./custom-tokens.json" // Explicit local file // Plus any auto-discovered files in workspace ] } } ``` -------------------------------- ### Coverage Measurement Commands Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/CLAUDE.md Commands to measure code coverage, including generating a detailed HTML report. ```bash go test -cover ./... # For detailed HTML report: go test -coverprofile=coverage.out ./... go tool cover -html=coverage.out ``` -------------------------------- ### Build with Version Info Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/README.md Command to build the executable with specific version information injected via ldflags. ```bash go build -ldflags "\ -X bennypowers.dev/dtls/internal/version.Version=v0.3.0 \ -X bennypowers.dev/dtls/internal/version.GitCommit=abc1234 \ -X bennypowers.dev/dtls/internal/version.GitTag=v0.3.0 \ -X bennypowers.dev/dtls/internal/version.BuildTime=2024-01-15" \ ./cmd/design-tokens-language-server ``` -------------------------------- ### ServerContext Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/types.md Interface providing all dependencies for LSP handlers. ```go type ServerContext interface { // Document operations Document(uri string) *documents.Document DocumentManager() *documents.Manager AllDocuments() []*documents.Document // Token operations Token(name string) *tokens.Token TokenManager() *tokens.Manager TokenCount() int // Workspace operations RootURI() string RootPath() string SetRootURI(uri string) SetRootPath(path string) // Configuration GetConfig() ServerConfig SetConfig(config ServerConfig) LoadPackageJsonConfig() error IsTokenFile(path string) bool ShouldProcessAsTokenFile(uri string) bool // Workspace initialization LoadTokensFromConfig() error RegisterFileWatchers(ctx *glsp.Context) error // Document token loading LoadTokensFromDocumentContent(uri, languageID, content string) error // File tracking RemoveLoadedFile(path string) // LSP context GLSPContext() *glsp.Context SetGLSPContext(ctx *glsp.Context) // Client capability detection ClientDiagnosticCapability() *bool SetClientDiagnosticCapability(hasCapability bool) ClientCapabilities() *protocol.ClientCapabilities SetClientCapabilities(caps protocol.ClientCapabilities) // Capability helpers SupportsSnippets() bool PreferredHoverFormat() protocol.MarkupKind SupportsDefinitionLinks() bool SupportsDiagnosticRelatedInfo() bool SupportsCodeActionLiterals() bool // Diagnostics mode UsePullDiagnostics() bool SetUsePullDiagnostics(use bool) PublishDiagnostics(context *glsp.Context, uri string) error // Semantic tokens SemanticTokenCache() SemanticTokenCacher } ``` -------------------------------- ### Programmatic Usage Entry Point Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/README.md Initializes the Design Tokens Language Server programmatically and provides access to its core components. ```go package main import "bennypowers.dev/dtls/lsp" func main() { server, _ := lsp.NewServer() defer server.Close() // Access components config := server.GetConfig() tokens := server.TokenManager() documents := server.DocumentManager() // Use server... } ``` -------------------------------- ### Path Field Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/configuration.md The path to the token file. Can be: - Absolute path: "/home/user/tokens.json" - Relative path: "./tokens.json" - npm protocol: "npm:@design-tokens/tokens" ```go Path string ``` -------------------------------- ### Example Design Token JSON Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/README.md Illustrates the structure of a design token file using the Design Token Community Group (DTCG) format. ```json { "$schema": "https://tokens.tools/schemas/2025-10/schema.json", "color": { "primary": { "$value": "#ff0000", "$type": "color" } } } ``` -------------------------------- ### Update Parser Logic for New Schema Version Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/docs/SCHEMA_VERSIONING.md Modifies the parser logic to route to version-specific parsing if the new schema version introduces breaking changes to token structure. ```go func (p *Parser) extractTokensWithSchemaVersion(...) error { // Route to version-specific logic switch version { case schema.Draft: // Draft-specific parsing case schema.V2025_10: // 2025.10-specific parsing case schema.V2026_01: // NEW VERSION // 2026.01-specific parsing } } ``` -------------------------------- ### Configuration Loading Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/modules.md The flow for loading configuration, including package.json and token files. ```mermaid Client sends workspace/didChangeConfiguration ↓ LoadPackageJsonConfig() [if in workspace] ↓ [Merge with existing] mergePackageJsonConfig(clientConfig, packageJsonConfig) ↓ [Load tokens from files/resolvers] LoadTokensFromConfig() ↓ [Load each token file] tokens.Manager.Add(token) [for each token] ↓ [Resolve token references] ResolveAllTokens() ↓ [Ready for queries] ``` -------------------------------- ### GetVersion Function Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/utilities.md Returns the version string. Set at build time via ldflags or determined from build info. ```go func GetVersion() string ``` ```go v := version.GetVersion() println("Version:", v) ``` -------------------------------- ### GetState Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/configuration.md Returns a snapshot of runtime state (NOT configuration). For configuration, use GetConfig() separately. ```go func (s *Server) GetState() ServerState ``` -------------------------------- ### ServerState Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/types.md Snapshot of runtime state (NOT configuration). ```go type ServerState struct { RootPath string } ``` -------------------------------- ### IsTokenFile Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/server.md Checks if a file path is configured as a token file. Verifies against configuration and loaded files map. ```go func (s *Server) IsTokenFile(path string) bool ``` -------------------------------- ### LoadPackageJsonConfig Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/configuration.md Reads and merges configuration from package.json. Client-sent configuration takes precedence over package.json values. ```go func (s *Server) LoadPackageJsonConfig() error ``` ```go server, _ := lsp.NewServer() err := server.LoadPackageJsonConfig() ``` -------------------------------- ### TokenFileSpec Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/configuration.md Specification for a token file with optional configuration. ```go type TokenFileSpec struct { // Path to the token file (required) // Can be absolute, relative, or npm: protocol Path string `json:"path"` // Prefix for CSS variables from this file (optional) Prefix string `json:"prefix,omitempty"` // GroupMarkers are token names that can also be groups (optional) GroupMarkers []string `json:"groupMarkers,omitempty"` } ``` -------------------------------- ### Build binaries for all platforms Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/CONTRIBUTING.md Generates build binaries for Linux, macOS, and Windows. ```sh make build-all ``` -------------------------------- ### Build the language server Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/CONTRIBUTING.md Clones the repository and builds the Design Tokens Language Server binary. ```sh make build ``` -------------------------------- ### Core Logic for Loading Tokens (Go) Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/ideas/AUTODISCOVER.md Go function demonstrating the core logic for determining whether to use explicit configuration or auto-discovery. ```go // LoadTokensFromConfig determines how to load tokens based on configuration func (s *Server) LoadTokensFromConfig() error { cfg := s.GetConfig() state := s.GetState() // Explicit configuration takes precedence if cfg.TokensFiles != nil { s.setAutoDiscoveryMode(false) if len(cfg.TokensFiles) == 0 { // Empty array: try auto-discovery if workspace exists if state.RootPath != "" { s.setAutoDiscoveryMode(true) return s.loadTokenFilesAutoDiscover() } return nil } // Non-empty: load explicit files return s.loadExplicitTokenFiles() } // No configuration: auto-discover if workspace exists if state.RootPath != "" { s.tokens.Clear() s.setAutoDiscoveryMode(true) return s.loadTokenFilesAutoDiscover() } return nil } ``` -------------------------------- ### NewSet Function Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/utilities.md Creates a new set with initial values. ```go func NewSet[T comparable](vs ...T) Set[T] ``` ```go set := collections.NewSet("x", "y", "z") ``` -------------------------------- ### ByteOffsetToUTF16Uint32 Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/utilities.md Like ByteOffsetToUTF16 but returns uint32, clamped to valid range for LSP compatibility. ```go func ByteOffsetToUTF16Uint32(s string, byteOffset int) uint32 ``` -------------------------------- ### Server State and Configuration Structs (Go) Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/ideas/AUTODISCOVER.md Go structs representing server state and configuration, highlighting the runtime state for auto-discovery. ```go type ServerState struct { AutoDiscoveryMode bool // Runtime state RootPath string // Workspace root } type ServerConfig struct { TokensFiles []any // User configuration Prefix string GroupMarkers []string } ``` -------------------------------- ### SetConfig Parameters Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/configuration.md Parameter table for SetConfig method. ```go config | ServerConfig | yes | — | New configuration ``` -------------------------------- ### NewDocument Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/documents.md Creates a new document. ```go func NewDocument(uri, languageID string, version int, content string) *Document ``` ```go doc := documents.NewDocument( "file:///home/user/tokens.json", "json", 1, `{}`, ) ``` -------------------------------- ### Manager Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/types.md Manages text documents. ```go type Manager struct { // Fields are unexported } ``` -------------------------------- ### GetBySourceFile Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/tokens.md Returns all tokens loaded from a specific file. ```Go func (m *Manager) GetBySourceFile(filePath string) []*Token ``` -------------------------------- ### TokensFiles Field Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/configuration.md Specifies token files to load. Can be specified as: - String: `["./tokens.json", "npm:@foo/tokens"]` - Object: `[{"path": "./tokens.json", "prefix": "ds"}]` If empty, no automatic token loading occurs. ```go TokensFiles []any ``` -------------------------------- ### Enable Debug Logging Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/errors.md Go code snippet to enable debug logging for the language server. ```go import "bennypowers.dev/dtls/internal/log" log.SetLevel(log.LevelDebug) ``` -------------------------------- ### GetSourceFiles Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/tokens.md Returns a list of all unique source files that have tokens loaded. ```go func (m *Manager) GetSourceFiles() []string ``` -------------------------------- ### Build-Time Variables Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/utilities.md Defines build-time variables for version information. ```go var ( Version = "dev" // Version string (set via ldflags) GitCommit = "unknown" // Git commit hash GitTag = "unknown" // Git tag BuildTime = "unknown" // Build timestamp GitDirty = "" // "dirty" if uncommitted changes ) ``` ```bash go build -ldflags \ -X bennypowers.dev/dtls/internal/version.Version=v0.3.0 \ -X bennypowers.dev/dtls/internal/version.GitCommit=abc1234 \ -X bennypowers.dev/dtls/internal/version.GitTag=v0.3.0 \ -X bennypowers.dev/dtls/internal/version.BuildTime=2024-01-15 \ -X bennypowers.dev/dtls/internal/version.GitDirty= ``` -------------------------------- ### LoadTokensFromDocumentContent Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/configuration.md Loads tokens from an open document content. Used for files with Design Tokens $schema declaration. ```go func (s *Server) LoadTokensFromDocumentContent(uri, languageID, content string) error ``` -------------------------------- ### Testing Command Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/README.md Command to run all tests in the project. ```bash go test ./... ``` -------------------------------- ### TokenFile Type Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/types.md Configuration for a token file source. ```go type TokenFile struct { Path string Prefix string GroupMarkers []string } ``` -------------------------------- ### Run linter Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/CONTRIBUTING.md Executes golangci-lint to check code quality. ```sh make lint ``` -------------------------------- ### SetGLSPContext Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/server.md Sets the GLSP protocol context. ```go func (s *Server) SetGLSPContext(ctx *glsp.Context) ``` -------------------------------- ### FromURL Variable Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/utilities.md Detects schema version from a $schema URL. ```go var FromURL = asimonimSchema.FromURL ``` -------------------------------- ### FromString Variable Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/utilities.md Detects schema version from a version string. ```go var FromString = asimonimSchema.FromString ``` -------------------------------- ### CDN Field Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/configuration.md CDN provider for network fallback. Valid values: "unpkg", "esm.sh", "esm.run", "jspm", "jsdelivr". Defaults to "unpkg" if empty. Only effective if NetworkFallback is true. ```go CDN string ``` -------------------------------- ### ServerState Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/configuration.md Runtime state snapshot (NOT configuration). Returned by GetState() for thread-safe access. ```go type ServerState struct { // RootPath is the workspace root path (file system) RootPath string } ``` -------------------------------- ### Add Method Source: https://github.com/bennypowers/design-tokens-language-server/blob/main/_autodocs/api-reference/utilities.md Adds one or more values to the set. ```go func (s Set[T]) Add(vs ...T) ```