@stillwind/host 0.7.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +113 -0
- package/dist/browser.d.ts +2 -2
- package/dist/browser.js +9 -6
- package/dist/browser.js.map +1 -1
- package/dist/{index-BXbvCuG7.d.ts → index-DdFR_SNl.d.ts} +22 -3
- package/dist/index.d.ts +148 -6
- package/dist/index.js +288 -71
- package/dist/index.js.map +1 -1
- package/dist/{options-PMjJ1c8W.js → options-CHkqG1Gc.js} +2293 -1902
- package/dist/options-CHkqG1Gc.js.map +1 -0
- package/dist/{plugin-CxD6forV.js → plugin-CNOsrkrd.js} +21 -3
- package/dist/plugin-CNOsrkrd.js.map +1 -0
- package/dist/{resolution-C3cvLPzx.js → resolution-C5o_tmY3.js} +4 -1
- package/dist/resolution-C5o_tmY3.js.map +1 -0
- package/dist/{resolution-BI5eZllL.d.ts → resolution-C7e21ept.d.ts} +2 -1
- package/dist/resolution.d.ts +1 -1
- package/dist/resolution.js +1 -1
- package/package.json +15 -12
- package/dist/options-PMjJ1c8W.js.map +0 -1
- package/dist/plugin-CxD6forV.js.map +0 -1
- package/dist/resolution-C3cvLPzx.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"options-PMjJ1c8W.js","names":[],"sources":["../src/css/plugins/session.ts","../src/compilation/host.ts","../src/semantics/backend.ts","../src/compilation/module-source.ts","../src/compilation/module-graph.ts","../src/compilation/request.ts","../src/compilation/compiler.ts","../src/css/banners.ts","../src/css/plugins/host.ts","../src/css/plugins/runtime.ts","../src/css/css.ts","../src/editor/candidates.ts","../src/editor/design-system.ts","../src/compilation/project.ts","../src/editor/request.ts","../src/editor/source/order.ts","../src/editor/sort.ts","../src/semantics/checker-source.ts","../src/editor/previews.ts","../src/editor/source/bindings.ts","../src/editor/source/literal.ts","../src/editor/source/inputs.ts","../src/editor/colors.ts","../src/editor/completion.ts","../src/editor/source/query.ts","../src/editor/snapshot.ts","../src/css/plugins/paths.ts","../src/project/stylesheet-editor.ts","../src/project/options.ts"],"sourcesContent":["import { NativeDesignSystemLoader, type NativeProjectSession } from \"@stillwind/native\";\n\nimport type { PluginRuntime } from \"./runtime.ts\";\n\n/**\n * A session's plugin runtime and the definition generation that its design system contains.\n */\ninterface SessionPlugins {\n /** Runtime of the CSS graph that the session was created or reloaded from. */\n runtime: PluginRuntime;\n /** Value of {@link PluginRuntime.generation} that the session's design system contains. */\n generation: number;\n /** Loader of the session's design system after the last reload with definitions. */\n loader?: NativeDesignSystemLoader;\n}\n\n/** Runtimes of sessions whose design systems load plugins with dynamic families. */\nconst sessions = new WeakMap<NativeProjectSession, SessionPlugins>();\n\n/**\n * Associates a session with the plugin runtime of the CSS graph that it was created or reloaded\n * from, so that compilation can define dynamic candidates.\n *\n * @param session - Native session.\n * @param runtime - Runtime returned with the graph, or undefined to detach.\n * @param generation - Definition generation of the loader that the session uses. Defaults to\n * zero, the generation of the graph's original loader.\n */\nexport function attachPlugins(\n session: NativeProjectSession,\n runtime?: PluginRuntime,\n generation = 0,\n): void {\n if (runtime?.dynamic) {\n sessions.set(session, {\n runtime,\n generation,\n });\n } else {\n sessions.delete(session);\n }\n}\n\n/**\n * Compiles with the definitions of the attached plugins, and defines the dynamic candidates that\n * the compilation reports.\n *\n * A session whose design system lacks definitions that the runtime added later is reloaded\n * first. After each compilation, new candidates go to the plugins, and when they return CSS the\n * session is reloaded and `compile` runs again, at most `rounds` more times. A session without\n * plugins runs `compile` once.\n *\n * @param session - Native session whose output `compile` returns.\n * @param compile - Compiles the graph into the session and returns its module outputs.\n * @param rounds - Most reloads after the first compilation.\n * @returns The output of the last compilation.\n * @throws If a plugin, a reload, or `compile` fails.\n */\nexport async function compileWithPlugins<\n Output extends {\n modules: readonly {\n dynamicCandidates: readonly string[];\n }[];\n },\n>(session: NativeProjectSession, compile: () => Output, rounds: number): Promise<Output> {\n const binding = sessions.get(session);\n if (!binding) {\n return compile();\n }\n /** Reloads the session with the runtime's current definitions. */\n const sync = () => {\n const loader = binding.runtime.replay(session, true);\n session.reload(loader);\n binding.generation = binding.runtime.generation;\n binding.loader = loader;\n };\n if (binding.generation < binding.runtime.generation) {\n sync();\n }\n let output = compile();\n for (let round = 0; round < rounds; round++) {\n const candidates = output.modules.flatMap((module) => module.dynamicCandidates);\n if (!(await binding.runtime.resolve(candidates))) {\n break;\n }\n sync();\n output = compile();\n }\n return output;\n}\n\n/**\n * Returns the loader whose design system a session uses after plugin definitions were added.\n *\n * @param session - Native session.\n * @returns The loader of the last reload with definitions, or undefined when the session still\n * uses the loader that it was created or attached with.\n */\nexport function pluginLoader(session: NativeProjectSession): NativeDesignSystemLoader | undefined {\n return sessions.get(session)?.loader;\n}\n\n/**\n * Finds plugin candidates across source texts before individual modules are compiled.\n *\n * @param session - Session attached to the project's plugin runtime.\n * @param loader - Initial loader of the same session.\n * @param texts - Original source documents, including templates and embedded scripts.\n * @returns Completion of candidate resolution and any required CSS reload, without publishing modules.\n * @throws If a plugin or CSS reload fails. Discard this runtime before retrying individual modules.\n */\nexport async function prepareSourcePlugins(\n session: NativeProjectSession,\n loader: NativeDesignSystemLoader,\n texts: readonly string[],\n): Promise<void> {\n if (!sessions.has(session)) {\n return;\n }\n await compileWithPlugins(\n session,\n () => {\n const query = (pluginLoader(session) ?? loader).editorQuery();\n return {\n modules: [\n {\n dynamicCandidates: [...new Set(texts.flatMap((text) => query.dynamicCandidates(text)))],\n },\n ],\n };\n },\n 1,\n );\n}\n","import type { PreparedSource, ProjectInput } from \"@stillwind/projection\";\n\nimport type { ModuleDescriptor } from \"./module-source.ts\";\n\n/**\n * Source metadata, dependency resolution, reads, watches, and warnings supplied to\n * module compilation. Hosts must preserve a stable correspondence between resolver and\n * compiler module identities.\n */\nexport interface CompilerHost {\n /** Requests checker import resolutions. A non-null host resolve result still takes precedence. */\n typeFactsResolution?: boolean;\n /**\n * Loads source before or after preparation, including its original document and projection.\n *\n * @param id - Full resolver identity. The returned resolverId must equal this value.\n * @returns Original input for preparation or a prepared source. Omission uses describe and read.\n * @throws If loading or preparation fails.\n */\n load?(id: string): Promise<ProjectInput | PreparedSource>;\n /**\n * Determines whether a resolved dependency supplies source that Stillwind can analyze.\n *\n * @param id - Full resolved identity, including query suffixes.\n * @returns Whether source traversal can continue. Omission checks for supported JS/TS and SFC extensions.\n */\n supports?(id: string): boolean;\n /**\n * Describes one resolved source before it is scanned or compiled.\n *\n * @param id - Full resolver identity of the source, including any query suffix.\n * @returns Compiler and checker identities, parser metadata, and original document metadata.\n */\n describe(id: string): ModuleDescriptor;\n /**\n * Resolves a semantic dependency relative to its importing source.\n *\n * @param specifier - Authored module request text.\n * @param importer - Full resolver identity of the importing source.\n * @param options - Optional resolver policy. Compilation passes `skipSelf: true`.\n * @returns A promise for a resolved identity and optional external status, or null when\n * unresolved. Unresolved and external modules are skipped by semantic dependency traversal.\n */\n resolve(\n specifier: string,\n importer: string,\n options?: {\n /** Requests resolution without calling the initiating plugin again. */\n skipSelf: boolean;\n },\n ): Promise<{\n /** Full host identity used to load the resolved source. */\n id: string;\n /** Truthy values mark a dependency that the host does not load as source. */\n external?: boolean | string;\n } | null>;\n /**\n * Reads one resolved dependency before source preparation.\n *\n * @param id - Full resolver identity, including any query selecting transformed source.\n * @returns A promise for source text. Read failures reject the compilation.\n */\n read(id: string): Promise<string>;\n /**\n * Records the identity correspondence before a source is prepared.\n *\n * This callback can run before preparation fails. Callers must not treat it as proof of a\n * successful compilation.\n *\n * @param moduleId - Stable identity used by the compiler and checker results.\n * @param resolverId - Full host identity used to resolve and read this source.\n */\n onModule?(moduleId: string, resolverId: string): void;\n /**\n * Registers a resolved semantic dependency for change tracking.\n *\n * @param id - Full dependency identity selected by the host resolver.\n */\n watch(id: string): void;\n /**\n * Reports a lint warning or a rejected generated name through the host.\n *\n * @param message - Formatted warning text. No structured diagnostic location is implied.\n */\n warn(message: string): void;\n}\n\n/**\n * Loads original or prepared source through the host, reading its descriptor once.\n *\n * @param host - Host whose current buffers supply this source.\n * @param id - Full resolver identity. The host must preserve this identity in its answer.\n * @returns Prepared source from load, or an original input assembled from describe and read.\n * @throws If loading, describing, or reading the source fails.\n */\nexport async function loadSource(\n host: CompilerHost,\n id: string,\n): Promise<ProjectInput | PreparedSource> {\n if (host.load) {\n return host.load(id);\n }\n\n const descriptor = host.describe(id);\n return {\n resolverId: id,\n ...descriptor,\n document: {\n ...descriptor.document,\n code: await host.read(id),\n },\n };\n}\n","import type {\n NativeAssetRecord,\n NativeCheckerBinding,\n NativeSourceIssue,\n NativeTypeFact,\n} from \"@stillwind/native\";\nimport type { CheckerBuffer, PreparedSource } from \"@stillwind/projection\";\n\n/**\n * Failure to map, validate, or recover declaration identities for one source. The compiler turns\n * this error into a source report using its original-coordinate range.\n */\nexport class TypeFactsError extends Error {\n /** Compiler module identity used to locate the original prepared source. */\n readonly moduleId: string;\n /**\n * Inclusive original UTF-8 byte offset when the checker can identify it. Omission permits a\n * document-scoped report.\n */\n readonly start?: number;\n /**\n * Exclusive original UTF-8 byte offset when known. The compiler uses a source range only when\n * both endpoints are present.\n */\n readonly end?: number;\n /** Issue category and detail passed to native source-failure reporting. */\n readonly issue: NativeSourceIssue;\n\n /**\n * Records a checker contract failure in original source coordinates.\n *\n * @param moduleId - Compiler identity of the affected source.\n * @param start - Optional inclusive original UTF-8 byte offset.\n * @param end - Optional exclusive original UTF-8 byte offset.\n * @param kind - Native issue category, such as checker mapping, assignment, or identity\n * resolution.\n * @param detail - Error message also stored as the issue detail.\n */\n constructor(\n moduleId: string,\n start: number | undefined,\n end: number | undefined,\n kind: NativeSourceIssue[\"kind\"],\n detail: string,\n ) {\n super(detail);\n this.moduleId = moduleId;\n this.start = start;\n this.end = end;\n this.issue = {\n kind,\n detail,\n };\n }\n}\n\n/** Original UTF-8 expression range and its validated projected UTF-16 range. */\nexport interface CheckerSpan {\n /** Correspondence role matched when mapping a producer, expression, or module specifier. */\n role: string;\n /** Inclusive UTF-8 byte offset in the original document. */\n start: number;\n /** Exclusive UTF-8 byte offset in the original document, at or after `start`. */\n end: number;\n /** Inclusive UTF-16 offset in the unedited projected parser buffer. */\n projectedStart: number;\n /** Exclusive UTF-16 offset in the projected buffer, at or after `projectedStart`. */\n projectedEnd: number;\n}\n\n/** Original-coordinate requests for one module and its optional parser projection. */\nexport type TypeFactSource = PreparedSource & {\n /**\n * Original expressions queried for lowering or optional macro recognition. Every probe must\n * match an expression in a checker AST.\n */\n probes: readonly {\n /** Inclusive UTF-8 byte offset of the original expression. */\n start: number;\n /** Exclusive UTF-8 byte offset of the original expression. */\n end: number;\n /**\n * True makes unresolved identities optional for macro recognition. Otherwise missing or\n * unresolved types and nonfinite Stillwind candidates are errors.\n */\n recognitionOnly?: boolean;\n }[];\n /** Validated original-byte to projected-UTF-16 correspondences from the frontend. */\n checkerSpans?: readonly CheckerSpan[];\n /** Validated generated references that must use their global helper declarations. */\n checkerBindings?: readonly NativeCheckerBinding[];\n /** Alternative checker buffers, including independent Astro client modules. */\n checkerBuffers?: readonly CheckerBuffer[];\n /** Absolute framework declaration files included in the checker project. */\n checkerTypes?: readonly string[];\n /** Import resolutions used to rewrite checker module paths. */\n resolutions?: readonly {\n /**\n * Full resolved source identity. The checker rewrites this to the matching checker filename\n * when one is supplied.\n */\n id: string;\n /** Inclusive UTF-8 byte offset of the original module string literal, including its quotes. */\n start: number;\n /** Exclusive UTF-8 byte offset of the original module string literal. */\n end: number;\n }[];\n};\n\n/** An original UTF-8 range whose dependency or checker information could not be verified. */\nexport interface UnverifiedRange {\n /** Compiler module identity of the original document. */\n moduleId: string;\n /** Inclusive original UTF-8 byte offset. Omission identifies unavailable information for the module. */\n start?: number;\n /** Exclusive original UTF-8 byte offset when a specific expression range is known. */\n end?: number;\n /** Explanation of the missing dependency, checker result, or source correspondence. */\n reason: string;\n}\n\n/** Captured declarations and source buffers supplied to a semantic backend. */\nexport interface SemanticInputs {\n /** Captured original text keyed by absolute checker file path. Entries override filesystem reads. */\n overlayFiles?: ReadonlyMap<string, string>;\n /** Ambient declaration text keyed by absolute checker file path, supplied without writing to disk. */\n ambientDeclarations?: ReadonlyMap<string, string>;\n}\n\n/** Available facts remain usable when other expressions cannot be verified. */\nexport interface AvailableFacts {\n /** Available native facts grouped by compiler module identity. */\n facts: Map<string, NativeTypeFact[]>;\n /** Ranges for queries that could not be verified. Facts for other queries remain usable. */\n unverified: UnverifiedRange[];\n}\n\n/** Semantic queries implemented by a Node checker or an embedding application's checker worker. */\nexport interface TypeFactsBackend {\n /**\n * Sets the sources available to later checker queries. Each query still selects its own probes.\n * Call again after changing these inputs. Without this method, each query prepares its own sources.\n *\n * @param sources - All prepared sources for this project, in a stable order.\n * @param assets - Declarations grouped by compiler module ID for those sources.\n * @param inputs - File overlays and ambient declarations. Omission supplies no extra files.\n * The backend may retain these objects. Do not mutate them while they are installed.\n * Replacing the inputs clears the backend's prepared checker buffers.\n */\n setProjectSources?(\n sources: readonly TypeFactSource[],\n assets: ReadonlyMap<string, readonly NativeAssetRecord[]>,\n inputs?: SemanticInputs,\n ): void;\n /**\n * Resolves imports using the checker environment before source-provider fallback resolution.\n *\n * @param sources - Prepared sources with original probes and checker correspondences.\n * @param assets - Compiler declaration metadata grouped by module identity.\n * @param inputs - Captured overlays and ambient declarations for the same analysis.\n * @returns Import request to resolved identity maps, grouped by source resolver identity.\n * @throws If checker setup or resolution cannot complete.\n */\n resolveModules(\n sources: readonly TypeFactSource[],\n assets: ReadonlyMap<string, readonly NativeAssetRecord[]>,\n inputs?: SemanticInputs,\n ):\n | ReadonlyMap<string, ReadonlyMap<string, string>>\n | Promise<ReadonlyMap<string, ReadonlyMap<string, string>>>;\n /**\n * Collects semantic facts and validates declaration contracts for required probes.\n *\n * @param sources - Prepared sources with original UTF-8 probe ranges.\n * @param assets - Compiler declarations grouped by module identity.\n * @param inputs - Captured overlays and declarations. Omission permits backend reads.\n * @returns Native facts grouped by compiler module identity.\n * @throws If a required type, declaration identity, or source correspondence cannot be verified.\n */\n collect(\n sources: readonly TypeFactSource[],\n assets: ReadonlyMap<string, readonly NativeAssetRecord[]>,\n inputs?: SemanticInputs,\n ): Map<string, NativeTypeFact[]> | Promise<Map<string, NativeTypeFact[]>>;\n /**\n * Keeps verified facts while recording unavailable queries.\n *\n * @param sources - Prepared sources with original UTF-8 probe ranges.\n * @param assets - Compiler declarations grouped by module identity.\n * @param inputs - Captured overlays and declarations for this analysis.\n * @returns Facts for successful queries and original ranges with explanations for other queries.\n * @throws If backend setup or transport fails, or checker results conflict for one original range.\n */\n collectAvailable(\n sources: readonly TypeFactSource[],\n assets: ReadonlyMap<string, readonly NativeAssetRecord[]>,\n inputs?: SemanticInputs,\n ): AvailableFacts | Promise<AvailableFacts>;\n /**\n * Discards cached filesystem state before subsequent queries. Call between analysis transactions.\n *\n * @returns Nothing, or a promise that resolves after invalidation.\n */\n invalidate(): void | Promise<void>;\n /**\n * Releases checker resources after pending queries complete.\n *\n * @returns Nothing, or a promise that resolves after cleanup.\n * @throws If checker cleanup fails.\n */\n close(): void | Promise<void>;\n}\n","import type { ProjectInput, ScriptSyntax, SourceDocument } from \"@stillwind/projection\";\n\nconst formatsByExtension: Partial<Record<string, SourceDocument[\"format\"]>> = {\n \".jsx\": \"jsx\",\n \".tsx\": \"jsx\",\n \".astro\": \"astro\",\n \".svelte\": \"svelte\",\n \".vue\": \"vue\",\n};\n\nconst languagesByExtension: Partial<Record<string, ScriptSyntax[\"language\"]>> = {\n \".ts\": \"ts\",\n \".cts\": \"ts\",\n \".mts\": \"ts\",\n \".tsx\": \"tsx\",\n \".jsx\": \"jsx\",\n};\n\n/** Source identities and parser metadata supplied by a host before preparation or compilation. */\nexport type ModuleDescriptor = Pick<\n ProjectInput,\n \"moduleId\" | \"checkerFileName\" | \"projectionFileName\" | \"syntax\" | \"framework\"\n> & {\n /** Original document identity and format. The compiler obtains its text through the host. */\n document: Omit<SourceDocument, \"code\">;\n};\n\n/**\n * Infers the source format and parser language from a module path.\n *\n * @param id - Source identity whose query or fragment is removed before case-insensitive extension\n * matching.\n * @returns Parser settings with unambiguous module kind and the inferred source format. TypeScript\n * and JSX extensions choose their parser languages. Declaration files use `dts`, and SFC\n * extensions select projected formats. Unrecognized extensions default to JavaScript script input.\n */\nexport function fileSourceKind(id: string): {\n /** Parser language and module kind inferred from the cleaned extension. */\n syntax: ScriptSyntax;\n /** Original document format used to select direct input or framework projection. */\n format: SourceDocument[\"format\"];\n} {\n const name = cleanModuleId(id).toLowerCase();\n const extension = /\\.[^.]+$/.exec(name)?.[0];\n const format = formatsByExtension[extension ?? \"\"] ?? \"script\";\n const language = /\\.d\\.[cm]?ts$/.test(name)\n ? \"dts\"\n : (languagesByExtension[extension ?? \"\"] ?? \"js\");\n return {\n syntax: {\n language,\n moduleKind: \"unambiguous\",\n },\n format,\n };\n}\n\n/**\n * Removes a filesystem identity's query or fragment before a disk operation.\n *\n * @param id - Resolver identity, including any query or fragment suffix.\n * @returns The identity up to its first `?` or `#`. IDs beginning with NUL or `virtual:` are\n * returned unchanged.\n */\nexport function cleanModuleId(id: string): string {\n if (id.startsWith(\"\\0\") || id.startsWith(\"virtual:\")) {\n return id;\n }\n return id.split(/[?#]/, 1)[0];\n}\n\n/**\n * Converts an original UTF-8 byte boundary to a UTF-16 offset for slicing JavaScript text.\n *\n * @param text - Original document text.\n * @param offset - Integer byte offset from zero through the UTF-8 byte length, at a character\n * boundary.\n * @returns Length of the text before that boundary in UTF-16 code units.\n * @throws If the offset is negative, exceeds the byte length, or points into a UTF-8 continuation\n * byte.\n */\nexport function byteToUtf16(text: string, offset: number): number {\n const bytes = new TextEncoder().encode(text);\n if (\n offset < 0 ||\n offset > bytes.length ||\n (offset < bytes.length && (bytes[offset] & 0xc0) === 0x80)\n ) {\n throw new Error(\"Invalid original UTF-8 boundary\");\n }\n return new TextDecoder().decode(bytes.subarray(0, offset)).length;\n}\n","import type {\n BindingReport,\n NativeDiagnosticBatch,\n NativeModuleSummary,\n NativeProjectSession,\n NativeTypeFact,\n} from \"@stillwind/native\";\nimport {\n checkerEnvironment,\n PreparationError,\n prepareSource,\n type PreparedSource,\n type ProjectInput,\n} from \"@stillwind/projection\";\n\nimport {\n TypeFactsError,\n type TypeFactsBackend,\n type TypeFactSource,\n} from \"../semantics/backend.ts\";\nimport { loadSource, type CompilerHost } from \"./host.ts\";\nimport { byteToUtf16, cleanModuleId } from \"./module-source.ts\";\nimport type { CompilationProject } from \"./project.ts\";\nimport type { ModuleAnalysis, ModuleCompileOptions, SemanticDependency } from \"./request.ts\";\n\n/**\n * Compilation failure carrying diagnostic batches for the same report format used by collect mode.\n * Its message renders those reports with source locations.\n */\nexport class CompilationFailure extends Error {\n /**\n * Report batches grouped by compiler module identity. The supplied array is retained without\n * copying.\n */\n readonly batches: readonly NativeDiagnosticBatch[];\n\n /**\n * Builds an error message from the supplied reports and preserves an optional cause.\n *\n * @param batches - Reports to retain, in message order.\n * @param cause - Optional preparation or checker failure that produced these reports.\n */\n constructor(batches: readonly NativeDiagnosticBatch[], cause?: unknown) {\n super(\n batches\n .flatMap((batch) => batch.reports)\n .map(formatReport)\n .join(\"\\n\"),\n { cause },\n );\n this.batches = batches;\n }\n}\n\n/**\n * Formats a compiler report for an Error message or terminal output.\n *\n * @param report - Structured report with a primary label, related labels, and notes.\n * @returns Text with one-based line and column ranges for source labels, followed by related labels\n * and notes. Document-scoped primary labels use only the URI.\n */\nfunction formatReport(report: BindingReport) {\n const { location, scope } = report.primary;\n const at =\n scope === \"document\"\n ? location.uri\n : `${location.uri}:${location.startLine + 1}:${location.startColumn + 1}-${location.endLine + 1}:${location.endColumn + 1}`;\n const related = report.related.map((label) => {\n const loc = label.location;\n const at =\n label.scope === \"document\"\n ? loc.uri\n : `${loc.uri}:${loc.startLine + 1}:${loc.startColumn + 1}`;\n return ` ${at}${label.message ? `: ${label.message}` : \"\"}`;\n });\n return [\n `${at}: ${report.code}: ${report.message}`,\n ...related,\n ...report.notes.map((note) => ` ${note}`),\n ].join(\"\\n\");\n}\n\n/** Collects prepared sources and semantic facts for one entry's demanded dependency graph. */\nexport class ModuleGraph {\n /** Prepared sources keyed by compiler identity, including sources that later fail scanning. */\n readonly #attempted = new Map<string, PreparedSource>();\n /** Successful scanner summaries keyed by compiler identity. */\n readonly #summaries = new Map<string, NativeModuleSummary>();\n /** Sources retained for compilation, keyed by full host identity. */\n readonly #sources = new Map<string, PreparedSource>();\n /** Correspondence from compiler identities to full host resolver identities. */\n readonly #resolverIds = new Map<string, string>();\n /** Observed import resolutions keyed by importing resolver identity and authored specifier. */\n readonly #resolutions = new Map<string, Map<string, string>>();\n /** Whether entry probes require semantic traversal and checker collection. */\n #needsTypeFacts = false;\n /** Only this project revision may store scan results or install shared checker inputs. */\n readonly #projectRevision?: number;\n\n /**\n * Uses a caller-owned session, host, and lazy semantic backend for one entry.\n * Supplying `analysis` retains unavailable dependencies and partial facts in that result.\n * Omitting it keeps checker and dependency failures strict.\n *\n * @param session - Initialized native session. The caller retains ownership.\n * @param factsService - Lazy backend for checker queries, or undefined when unavailable.\n * @param host - Stable source descriptors, loading, and resolver operations for this graph.\n * @param options - Diagnostic policy and captured checker inputs for one compilation.\n * @param analysis - Optional result object to populate with observed sources, dependencies,\n * reports, and unavailable ranges.\n * @param project - Optional prepared inputs shared across scoped graphs of the same project.\n */\n constructor(\n readonly session: NativeProjectSession,\n readonly factsService: () => TypeFactsBackend | undefined,\n readonly host: CompilerHost,\n readonly options: ModuleCompileOptions,\n readonly analysis?: ModuleAnalysis,\n readonly project?: CompilationProject,\n ) {\n this.#projectRevision = project?.revision;\n }\n\n /**\n * Prepares source and retains it for report mapping, even if a later scan fails.\n *\n * @param input - Original or already prepared source. Preparation must preserve resolverId.\n * @returns Prepared source. onModule runs before preparation and does not imply success.\n * @throws If preparation fails or changes the resolver identity. PreparationError becomes CompilationFailure.\n */\n async prepare(input: ProjectInput | PreparedSource): Promise<PreparedSource> {\n this.host.onModule?.(input.moduleId, input.resolverId);\n try {\n const source =\n this.project?.source(input.resolverId) ??\n (\"kind\" in input ? input : await prepareSource(input));\n if (source.resolverId !== input.resolverId) {\n throw new Error(`Host changed resolver identity for ${input.resolverId}`);\n }\n this.#attempted.set(source.moduleId, source);\n this.analysis?.sources.push(source);\n return source;\n } catch (error) {\n if (error instanceof PreparationError) {\n throw this.#preparationFailure(input, error);\n }\n throw error;\n }\n }\n\n /**\n * Scans a prepared source without registering it in dependency traversal.\n *\n * @param source - Source with validated original document and projection correspondences.\n * @returns Native summary of imports, declarations, and semantic probes.\n * @throws CompilationFailure when scanning returns source diagnostics.\n */\n scan(source: PreparedSource): NativeModuleSummary {\n const cached = this.project?.summary(source);\n if (cached) {\n return cached;\n }\n const result = this.session.scanSource(source);\n if (result.kind === \"failed\") {\n throw new CompilationFailure([result.batch]);\n }\n this.project?.retain(source, result.summary, this.#projectRevision);\n return result.summary;\n }\n\n /**\n * Looks up a summary retained during dependency traversal.\n *\n * @param moduleId - Compiler identity of the source.\n * @returns Its cached summary, or undefined when traversal did not retain one.\n */\n summary(moduleId: string): NativeModuleSummary | undefined {\n return this.#summaries.get(moduleId);\n }\n\n /**\n * Finds the host identity registered for a compiler module.\n *\n * @param moduleId - Compiler identity registered by dependency collection.\n * @returns Full resolver identity, including any query suffix.\n * @throws If the compiler refers to an unregistered module.\n */\n resolverId(moduleId: string): string {\n const id = this.#resolverIds.get(moduleId);\n if (id === undefined) {\n throw new Error(`Stillwind returned an unknown module: ${moduleId}`);\n }\n return id;\n }\n\n /**\n * Registers the entry and loads dependencies demanded by its semantic probes.\n *\n * @param entry - Prepared entry source.\n * @param entrySummary - Successful scan of that entry, with the same module identity.\n * @returns A promise that resolves after traversal. Analysis mode retains unresolved and\n * unsupported dependencies rather than failing the whole graph.\n * @throws If strict traversal fails or source identities conflict.\n */\n async collectDependencies(\n entry: PreparedSource,\n entrySummary: NativeModuleSummary,\n ): Promise<void> {\n this.#needsTypeFacts = entrySummary.typeProbes.length > 0;\n this.#register(entry);\n const visited = new Map<string, Set<string | null>>();\n const pending: {\n /** Registered source whose exported value or entry probes remain to be traversed. */\n source: PreparedSource;\n /** Null for entry probes, * for namespace demand, or a demanded export name. */\n requested: string | null;\n }[] = [\n {\n source: entry,\n requested: null,\n },\n ];\n while (pending.length > 0) {\n const { source, requested } = pending.pop()!;\n const demands = visited.get(source.resolverId) ?? new Set<string | null>();\n if (demands.has(requested)) {\n continue;\n }\n demands.add(requested);\n visited.set(source.resolverId, demands);\n const summary = this.#dependencySummary(source, entry, entrySummary);\n if (!summary || !this.#needsTypeFacts) {\n continue;\n }\n const semanticResolutions = await this.#semanticResolutions(source);\n for (const dependency of semanticDependencies(summary, requested)) {\n const next = await this.#followDependency(\n source,\n dependency.source,\n semanticResolutions?.get(dependency.source),\n );\n if (next) {\n pending.push({\n source: next,\n requested: dependency.imported,\n });\n }\n }\n }\n }\n\n /**\n * Attaches semantic facts and CSS value imports to the retained graph sources.\n *\n * @param entry - Registered entry whose transport imports remain unchanged.\n * @returns Copies of retained sources with native type facts. Analysis mode records unavailable\n * queries, while strict compilation requires a backend when facts are needed.\n * @throws If strict checker collection or a checker source contract fails.\n */\n async collectTypedSources(entry: PreparedSource) {\n const facts = await this.#collectFacts();\n return [...this.#sources.values()].map((source) => ({\n ...source,\n moduleCssImport:\n source.resolverId === entry.resolverId ? source.moduleCssImport : \"stillwind/module-css\",\n typeFacts: facts.get(source.moduleId) ?? [],\n }));\n }\n\n /**\n * Converts a known checker failure to a report in original source coordinates.\n *\n * @param error - Failure caught during compilation.\n * @returns CompilationFailure for TypeFactsError whose source was prepared, otherwise the input.\n */\n failure(error: unknown): unknown {\n if (!(error instanceof TypeFactsError)) {\n return error;\n }\n const source = this.#attempted.get(error.moduleId);\n if (!source) {\n return error;\n }\n const range =\n error.start !== undefined && error.end !== undefined\n ? {\n start: byteToUtf16(source.document.code, error.start),\n end: byteToUtf16(source.document.code, error.end),\n }\n : undefined;\n const batch = this.session.reportSourceFailure({\n moduleId: source.moduleId,\n document: source.document,\n issue: error.issue,\n range,\n converter: source.kind === \"projected\" ? source.projection.converter : undefined,\n });\n return new CompilationFailure([batch], error);\n }\n\n /**\n * Registers the source and enforces one-to-one host and compiler identities within the graph.\n *\n * @param source - Prepared source to retain for traversal and compilation.\n * @throws If a compiler identity is shared or a host identity changes its compiler identity.\n */\n #register(source: PreparedSource): void {\n const previous = this.#resolverIds.get(source.moduleId);\n if (previous !== undefined && previous !== source.resolverId) {\n throw new Error(\n `Module identity ${source.moduleId} is shared by ${previous} and ${source.resolverId}`,\n );\n }\n const existing = this.#sources.get(source.resolverId);\n if (existing !== undefined && existing.moduleId !== source.moduleId) {\n throw new Error(`Resolver identity ${source.resolverId} changed module identity`);\n }\n this.#resolverIds.set(source.moduleId, source.resolverId);\n this.#sources.set(source.resolverId, source);\n }\n\n /**\n * Converts a preparation error into an original-document diagnostic batch.\n *\n * @param input - Source whose document metadata identifies the failing preparation.\n * @param error - Preparation issue with optional original UTF-16 range and converter identity.\n * @returns A compilation failure retaining the preparation error as its cause.\n */\n #preparationFailure(\n input: ProjectInput | PreparedSource,\n error: PreparationError,\n ): CompilationFailure {\n return new CompilationFailure(\n [\n this.session.reportSourceFailure({\n moduleId: input.moduleId,\n document: input.document,\n issue: error.issue,\n converter: error.converter,\n range: error.range,\n }),\n ],\n error,\n );\n }\n\n /**\n * Reuses or scans a source summary and records dependency syntax failures in analysis mode.\n *\n * @param source - Registered dependency or entry source.\n * @param entry - Entry source whose initial scan is already available.\n * @param entrySummary - Summary with the entry's compiler identity.\n * @returns A retained summary, or undefined after an analysis-mode scan failure removes the source.\n * @throws If scanning fails in strict mode or a summary changes the source's compiler identity.\n */\n #dependencySummary(\n source: PreparedSource,\n entry: PreparedSource,\n entrySummary: NativeModuleSummary,\n ): NativeModuleSummary | undefined {\n let summary: NativeModuleSummary;\n try {\n summary =\n this.#summaries.get(source.moduleId) ??\n (source.resolverId === entry.resolverId ? entrySummary : this.scan(source));\n } catch (error) {\n if (!this.analysis || !(error instanceof CompilationFailure)) {\n throw error;\n }\n this.analysis.batches.push(...error.batches);\n this.#sources.delete(source.resolverId);\n for (const dependency of this.analysis.dependencies) {\n if (dependency.id === source.resolverId) {\n dependency.status = \"unsupported\";\n }\n }\n return undefined;\n }\n if (summary.moduleId !== source.moduleId) {\n throw new Error(`Scanner changed module identity for ${source.resolverId}`);\n }\n this.#summaries.set(source.moduleId, summary);\n return summary;\n }\n\n /**\n * Attaches checker environments, scanner probes, and observed resolutions to retained sources.\n *\n * @returns Checker inputs in source registration order. Missing summaries are scanned and cached.\n * @throws If scanning or checker preparation fails.\n */\n #checkerSources(): TypeFactSource[] {\n return [...this.#sources.values()].map((source) => {\n const summary = this.#summaries.get(source.moduleId) ?? this.scan(source);\n this.#summaries.set(source.moduleId, summary);\n let environment;\n try {\n environment = checkerEnvironment(source);\n } catch (error) {\n if (error instanceof PreparationError) {\n throw this.#preparationFailure(source, error);\n }\n throw error;\n }\n return {\n ...source,\n ...environment,\n checkerSpans: summary.checkerSpans,\n checkerBindings: summary.checkerBindings,\n probes: summary.typeProbes,\n resolutions: summary.moduleSpecifiers.flatMap((specifier) => {\n const id = this.#resolutions.get(source.resolverId)?.get(specifier.source);\n return id\n ? [\n {\n id,\n start: specifier.start,\n end: specifier.end,\n },\n ]\n : [];\n }),\n };\n });\n }\n\n /**\n * Collects declared assets for checker interpretation.\n *\n * @returns A new map from compiler identity to the corresponding scanner asset array.\n */\n #assets() {\n return new Map([...this.#summaries].map(([id, summary]) => [id, summary.assets]));\n }\n\n /**\n * Adds an unverified range for each retained probe when analysis mode has no usable facts.\n *\n * @param source - Source whose scanner probes use original UTF-8 byte coordinates.\n * @param reason - Explanation included in every added range. Strict mode has no analysis to update.\n */\n #unavailable(source: PreparedSource, reason: string): void {\n this.analysis?.unverified.push(\n ...(this.#summaries.get(source.moduleId)?.typeProbes ?? []).map((probe) => ({\n moduleId: source.moduleId,\n start: probe.start,\n end: probe.end,\n reason,\n })),\n );\n }\n\n /**\n * Requests checker resolutions when the host enables them, recording failures as unverified probes.\n *\n * @param source - Importing source whose resolver identity selects the returned map.\n * @returns Authored specifiers mapped to host identities, or undefined when disabled or unavailable.\n * @throws If resolution fails outside analysis mode.\n */\n async #semanticResolutions(\n source: PreparedSource,\n ): Promise<ReadonlyMap<string, string> | undefined> {\n if (!this.host.typeFactsResolution) {\n return undefined;\n }\n try {\n const backend = this.factsService();\n if (backend && this.project && this.project.revision === this.#projectRevision) {\n return (\n await this.project.resolve(backend, this.#checkerSources(), this.options.typeFactsInputs)\n ).get(source.resolverId);\n }\n return (\n await backend?.resolveModules(\n this.#checkerSources(),\n this.#assets(),\n this.options.typeFactsInputs,\n )\n )?.get(source.resolverId);\n } catch (error) {\n if (!this.analysis) {\n throw error;\n }\n this.#unavailable(source, String(error));\n }\n return undefined;\n }\n\n /**\n * Resolves a demanded dependency, records its status, and loads supported source for traversal.\n *\n * @param source - Registered importing source.\n * @param specifier - Authored module request.\n * @param semanticId - Optional checker fallback used when the host returns no resolution.\n * @returns Registered dependency source, or undefined for external, unresolved, or unsupported requests.\n * @throws If strict loading fails. Analysis mode records loading failures and available diagnostics.\n */\n async #followDependency(\n source: PreparedSource,\n specifier: string,\n semanticId?: string,\n ): Promise<PreparedSource | undefined> {\n const resolved = await this.#resolveDependency(source, specifier, semanticId);\n const observed: SemanticDependency = {\n importer: source.resolverId,\n specifier,\n id: resolved?.id,\n status: !resolved ? \"unresolved\" : resolved.external ? \"external\" : \"resolved\",\n };\n this.analysis?.dependencies.push(observed);\n if (!resolved || resolved.external) {\n return undefined;\n }\n const id = this.project?.source(resolved.id)?.resolverId ?? resolved.id;\n observed.id = id;\n if (!this.#canLoadDependency(id, observed)) {\n return undefined;\n }\n let resolutions = this.#resolutions.get(source.resolverId);\n if (!resolutions) {\n this.#resolutions.set(source.resolverId, (resolutions = new Map()));\n }\n resolutions.set(specifier, id);\n this.host.watch(id);\n try {\n let dependency = this.#sources.get(id);\n if (!dependency) {\n dependency = await this.prepare(await this.#load(id));\n this.#register(dependency);\n }\n return dependency;\n } catch (error) {\n if (!this.analysis) {\n throw error;\n }\n observed.status = \"unsupported\";\n this.analysis.unverified.push({ moduleId: source.moduleId, reason: String(error) });\n if (error instanceof CompilationFailure) {\n this.analysis.batches.push(...error.batches);\n }\n }\n return undefined;\n }\n\n /**\n * Uses host resolution first and a checker identity only when the host returns null.\n *\n * @param source - Importer whose full resolver identity is passed to the host.\n * @param specifier - Authored module request.\n * @param semanticId - Optional identity supplied by checker resolution.\n * @returns A resolution, or null when unavailable. Analysis mode converts host exceptions to null.\n * @throws If host resolution fails in strict mode.\n */\n async #resolveDependency(source: PreparedSource, specifier: string, semanticId?: string) {\n try {\n return (\n (await this.host.resolve(specifier, source.resolverId, { skipSelf: true })) ??\n (semanticId ? { id: semanticId } : null)\n );\n } catch (error) {\n if (!this.analysis) {\n throw error;\n }\n return null;\n }\n }\n\n /**\n * Distinguishes traversable sources from checker declarations and unsupported dependencies.\n *\n * @param id - Full resolved host identity.\n * @param observed - Mutable dependency record whose status becomes types or unsupported when skipped.\n * @returns Whether the dependency should be loaded as source.\n */\n #canLoadDependency(id: string, observed: SemanticDependency): boolean {\n const name = cleanModuleId(id);\n // Build hosts can resolve runtime exports without identifying declaration files.\n // The checker supplies those package types.\n if (\n /\\.d\\.[cm]?ts$/.test(name) ||\n (!this.host.typeFactsResolution && /(?:^|[\\\\/])node_modules[\\\\/]/.test(name))\n ) {\n observed.status = \"types\";\n return false;\n }\n if (!(this.host.supports?.(id) ?? /\\.(?:[cm]?[jt]sx?|astro|svelte|vue)$/.test(name))) {\n observed.status = \"unsupported\";\n return false;\n }\n return true;\n }\n\n /**\n * Reuses a prepared project source or loads new input through the host.\n *\n * @param id - Full resolved dependency identity.\n * @returns A shared prepared source or new input from the host. Do not mutate cached sources.\n * @throws If host loading, description, or reading fails.\n */\n async #load(id: string): Promise<ProjectInput | PreparedSource> {\n const cached = this.project?.source(id);\n if (cached) {\n return cached;\n }\n return loadSource(this.host, id);\n }\n\n /**\n * Collects available facts for retained sources when entry probes require semantic information.\n *\n * @returns Facts keyed by compiler identity. Analysis mode records unavailable queries and may return partial facts.\n * @throws If strict checker collection fails or a compilation failure occurs while preparing checker sources.\n */\n async #collectFacts(): Promise<Map<string, NativeTypeFact[]>> {\n if (!this.#needsTypeFacts) {\n return new Map();\n }\n try {\n const backend = this.factsService();\n if (!backend) {\n if (!this.analysis) {\n throw new Error(\"Type facts required for this compilation are unavailable\");\n }\n for (const source of this.#sources.values()) {\n this.#unavailable(source, \"Semantic queries are disabled\");\n }\n return new Map();\n }\n if (this.analysis) {\n const sources =\n (this.project?.revision === this.#projectRevision\n ? this.project?.install(backend, this.#checkerSources(), this.options.typeFactsInputs)\n : undefined) ?? this.#checkerSources();\n const available = await backend.collectAvailable(\n sources,\n this.#assets(),\n this.options.typeFactsInputs,\n );\n this.analysis.unverified.push(...available.unverified);\n return available.facts;\n }\n return await backend.collect(\n this.#checkerSources(),\n this.#assets(),\n this.options.typeFactsInputs,\n );\n } catch (error) {\n if (!this.analysis || error instanceof CompilationFailure) {\n throw error;\n }\n for (const source of this.#sources.values()) {\n this.#unavailable(source, String(error));\n }\n return new Map();\n }\n }\n}\n\n/**\n * Selects imports needed to answer the current semantic demand.\n *\n * @param summary - Scanner summary for the source being traversed.\n * @param requested - Null for entry probes, `*` for a namespace demand, or a specific exported\n * name.\n * @returns Probe imports, imports for a matched export, or matching re-export demands. Unmatched\n * and namespace demands conservatively retain all imports and re-exports.\n */\nfunction semanticDependencies(summary: NativeModuleSummary, requested: string | null) {\n if (requested === null) {\n return summary.probeImports;\n }\n const selected = summary.exportImports.find((entry) => entry.name === requested);\n if (requested !== \"*\" && selected) {\n return selected.imports;\n }\n const reExports = summary.reExports.filter(\n (entry) => requested === \"*\" || entry.exported === requested || entry.exported === \"*\",\n );\n if (requested !== \"*\" && reExports.length > 0) {\n return reExports.map((entry) => ({\n source: entry.source,\n imported: entry.exported === \"*\" ? requested : entry.imported,\n }));\n }\n // Namespace imports and exports without a declaration slice remain conservative.\n return [...summary.imports, ...summary.reExports];\n}\n","import type { BindingEdit, NativeDiagnosticBatch, ProjectModuleOutput } from \"@stillwind/native\";\nimport type { PreparedSource } from \"@stillwind/projection\";\n\nimport type { TypeFactsInputs, UnverifiedRange } from \"../semantics/index.ts\";\n\n/**\n * Current reports and sources for the semantic graph demanded by one entry.\n */\nexport interface ModuleAnalysis {\n /** Compiler identity of the entry after loading its descriptor. */\n entry: string;\n /** Traversal covers dependencies demanded by semantic probes, rather than all application imports. */\n coverage: \"observed\";\n /** Outputs produced by native project compilation, including diagnostic-only outputs. */\n modules: ProjectModuleOutput[];\n /** Structured diagnostic batches keyed by compiler module identity. */\n batches: NativeDiagnosticBatch[];\n /** Nonempty first fix actions in report order, excluding editor sorting actions. */\n fixes: BindingEdit[][];\n /** Prepared original sources retained for mapping reports, including sources that later fail scanning. */\n sources: PreparedSource[];\n /** Import requests and their resolution or support status observed during traversal. */\n dependencies: SemanticDependency[];\n /** Original UTF-8 ranges that lack information needed for semantic checks or code generation. */\n unverified: UnverifiedRange[];\n /** Blocked when compiler errors or missing facts needed for lowering prevent reliable code generation. */\n generation: \"complete\" | \"blocked\";\n}\n\n/**\n * One semantic import observed while answering an entry's type probes.\n */\nexport interface SemanticDependency {\n /** Full resolver identity of the importing source. */\n importer: string;\n /** Authored import request text. */\n specifier: string;\n /** Resolved identity, when resolution succeeded. */\n id?: string;\n /**\n * Resolved means analyzable source. External modules and dependencies handled through checker\n * declarations (`types`) are not traversed. Unresolved or unsupported dependencies leave analysis incomplete.\n */\n status: \"resolved\" | \"external\" | \"unresolved\" | \"unsupported\" | \"types\";\n}\n\n/**\n * Diagnostics, captured checker inputs, and generated imports for one module compilation.\n */\nexport interface ModuleCompileOptions {\n /** Files captured for this compilation's semantic queries. Omission uses disk dependencies. */\n typeFactsInputs?: TypeFactsInputs;\n /**\n * Whether compiler and checker diagnostics reject compilation or are returned in reports.\n * Defaults to `throw`. Host I/O and malformed transport failures still reject in `collect` mode.\n */\n diagnostics?: \"throw\" | \"collect\";\n /** Module specifiers injected into the entry source to activate its styles, in import order. */\n stylesheetImports?: string[];\n /**\n * JavaScript module exporting CSS for an explicit `stillwind/module-css` import in the entry.\n * Omission produces a compiler diagnostic when the entry contains that import.\n */\n moduleCssImport?: string;\n}\n\n/**\n * Creates an empty observed graph before loading its semantic dependencies.\n *\n * @param entry - Compiler module ID of the loaded entry source.\n * @returns A mutable graph with no reports or dependencies and generation initially allowed.\n */\nexport function createModuleAnalysis(entry: string): ModuleAnalysis {\n return {\n entry: entry,\n coverage: \"observed\",\n modules: [],\n batches: [],\n fixes: [],\n sources: [],\n dependencies: [],\n unverified: [],\n generation: \"complete\",\n };\n}\n","import type {\n BindingDiagnostic,\n BindingRejectedIdentifier,\n BindingReport,\n NativeDiagnosticBatch,\n NativeModuleSummary,\n NativePreparedSource,\n NativeProjectSession,\n ProjectModuleOutput,\n} from \"@stillwind/native\";\nimport type { PreparedSource, ProjectInput } from \"@stillwind/projection\";\n\nimport { compileWithPlugins } from \"../css/plugins/session.ts\";\nimport type { TypeFactsBackend, TypeFactsInputs, UnverifiedRange } from \"../semantics/index.ts\";\nimport { loadSource, type CompilerHost } from \"./host.ts\";\nimport { CompilationFailure, ModuleGraph } from \"./module-graph.ts\";\nimport type { CompilationProject } from \"./project.ts\";\nimport { createModuleAnalysis, type ModuleAnalysis, type ModuleCompileOptions } from \"./request.ts\";\n\n/** Most reloads with new plugin definitions during one compilation of a graph. */\nconst PLUGIN_ROUNDS = 3;\n\n/**\n * Analyzes an entry and its semantic dependencies without requiring stylesheet delivery IDs.\n * Source failures return diagnostic batches. Unavailable semantic information records unverified\n * ranges. Entry I/O and native transport failures reject.\n * The caller owns the initialized session and the lazy checker service.\n *\n * @param session - Native project session with an initialized design system.\n * @param factsService - Supplies a checker configured for the host's TypeScript environment,\n * or undefined when semantic facts are unavailable.\n * @param id - Full resolver identity of the entry, including query suffixes.\n * @param host - Source loading, resolution, metadata, and dependency tracking operations.\n * @param typeFactsInputs - Captured overlays and ambient declarations for this analysis.\n * @param project - Optional sources prepared by earlier analyses of this project.\n * The caller must invalidate changed sources before analysis starts.\n * @returns Reports and sources for the semantic dependencies demanded by the entry.\n * @throws If entry I/O fails, a host changes resolver identity, or native transport operations fail.\n */\nexport async function analyzeModule(\n session: NativeProjectSession,\n factsService: () => TypeFactsBackend | undefined,\n id: string,\n host: CompilerHost,\n typeFactsInputs?: TypeFactsInputs,\n project?: CompilationProject,\n): Promise<ModuleAnalysis> {\n const revision = project?.revision;\n const captured = project?.source(id);\n const input = captured ?? (await loadSource(host, id));\n if (project?.revision !== revision) {\n project = undefined;\n }\n const analysis: ModuleAnalysis = createModuleAnalysis(input.moduleId);\n if (!captured && input.resolverId !== id) {\n throw new Error(`Host changed resolver identity for ${id}`);\n }\n await compileGraph(\n session,\n factsService,\n input.document.code,\n input.resolverId,\n host,\n {\n diagnostics: \"collect\",\n moduleCssImport: \"stillwind/module-css\",\n typeFactsInputs,\n },\n analysis,\n input,\n project,\n );\n for (const batch of analysis.batches) {\n for (const report of batch.reports) {\n const edits = report.actions[0]?.edits;\n if (edits?.length && report.code !== \"prefer-sorted-utilities\") {\n analysis.fixes.push(edits);\n }\n }\n }\n return analysis;\n}\n\n/**\n * Compiles an entry buffer and its demanded semantic dependencies into a project session.\n * The host descriptor supplies the module identity and parser metadata for each source.\n * Type facts are requested lazily for original-coordinate probes in JS/TS or SFC inputs.\n *\n * Collect mode retains compiler and checker reports, including known syntax and projection\n * failures. The default throw mode rejects compiler diagnostics. Lint findings only produce warnings.\n * Host I/O, checker process, and malformed native transport failures propagate in both modes.\n * Failed compilation can still update the session, register watches, and send warnings.\n *\n * @param session - Native project session with an initialized design system.\n * @param factsService - Supplies the type-facts service when the source graph needs semantic facts.\n * @param code - Entry source before Stillwind transformation.\n * @param id - Full resolver identity of the entry source, including its query suffix.\n * @param host - Source metadata, resolution, reading, dependency tracking, and warning operations.\n * @param options - Diagnostic behavior, captured checker inputs, and generated imports for the entry.\n * @returns A promise for the entry output and composition metadata, or undefined when normal mode\n * produces no entry code.\n * @throws If compilation rejects diagnostics, source preparation fails, or host or checker operations fail.\n */\nexport async function compileModule(\n session: NativeProjectSession,\n factsService: () => TypeFactsBackend | undefined,\n code: string,\n id: string,\n host: CompilerHost,\n options: ModuleCompileOptions = {},\n) {\n return compileGraph(session, factsService, code, id, host, options);\n}\n\n/**\n * Prepares the demanded graph, compiles it into the session, and derives the entry output.\n *\n * @param session - Initialized native session that retains successful module artifacts.\n * @param factsService - Lazy checker backend for semantic probes.\n * @param code - Original entry text used when entryInput is absent.\n * @param id - Full host identity of the entry.\n * @param host - Stable source metadata, resolution, and notification operations.\n * @param options - Diagnostic policy, captured checker inputs, and entry transport imports.\n * @param analysis - Optional object populated with sources, dependencies, reports, and generation status.\n * @param entryInput - Optional loaded entry, which takes precedence over code and host.describe.\n * @param project - Optional prepared sources shared with other analyses of this project.\n * @returns Entry output, a diagnostic-only output after a collected failure, or undefined when no code is emitted.\n * @throws If strict compilation fails or a host or transport failure cannot be collected.\n */\nasync function compileGraph(\n session: NativeProjectSession,\n factsService: () => TypeFactsBackend | undefined,\n code: string,\n id: string,\n host: CompilerHost,\n options: ModuleCompileOptions,\n analysis?: ModuleAnalysis,\n entryInput?: ProjectInput | PreparedSource,\n project?: CompilationProject,\n) {\n const graph = new ModuleGraph(session, factsService, host, options, analysis, project);\n let hasModuleCssImport = false;\n try {\n const descriptor = entryInput ?? {\n resolverId: id,\n ...host.describe(id),\n document: {\n ...host.describe(id).document,\n code,\n },\n };\n const entrySource = await graph.prepare(descriptor);\n const entrySummary = graph.scan(entrySource);\n hasModuleCssImport = entrySummary.moduleCssImports > 0;\n if (entrySummary.macroImports > 0) {\n entrySource.stylesheetImports = options.stylesheetImports;\n }\n if (hasModuleCssImport) {\n entrySource.moduleCssImport = options.moduleCssImport;\n }\n await graph.collectDependencies(entrySource, entrySummary);\n const typedSources = await graph.collectTypedSources(entrySource);\n const producer = analysis ? undefined : entrySource.moduleId;\n const projectOutput = await compileWithPlugins(\n session,\n () => session.compile(typedSources, producer),\n PLUGIN_ROUNDS,\n );\n if (analysis) {\n recordAnalysis(analysis, projectOutput.modules, session, typedSources, graph);\n }\n reportOutputDiagnostics(projectOutput.modules, graph, host, options);\n return entryOutput(projectOutput.modules, entrySource.moduleId, hasModuleCssImport, options);\n } catch (error) {\n const failure = graph.failure(error);\n if (failure instanceof CompilationFailure && options.diagnostics === \"collect\") {\n if (analysis) {\n analysis.batches = [...failure.batches];\n analysis.generation = \"blocked\";\n }\n return failedOutput(\n entryInput?.moduleId ?? host.describe(id).moduleId,\n failure.batches,\n hasModuleCssImport,\n );\n }\n throw failure;\n }\n}\n\n/**\n * Selects the entry and computes its composition dependency identities and topology fingerprint.\n *\n * @param modules - Native outputs in compiler order.\n * @param entryModuleId - Compiler identity of the requested entry.\n * @param hasModuleCssImport - Whether the entry requested an explicit CSS value.\n * @param options - Diagnostic policy controlling whether reports from all modules are attached.\n * @returns Enriched entry output. Throw mode omits entries without nonempty code, and collect mode retains them.\n */\nfunction entryOutput(\n modules: ProjectModuleOutput[],\n entryModuleId: string,\n hasModuleCssImport: boolean,\n options: ModuleCompileOptions,\n) {\n const output = modules.find((candidate) => candidate.moduleId === entryModuleId);\n const composition = output?.composition ?? [];\n const compositionModules = [...new Set(composition.map(({ base }) => base.moduleId))].filter(\n (module) => module !== entryModuleId,\n );\n const compositionTopology = JSON.stringify(\n composition\n .map(({ derived, base }) => [\n `${derived.moduleId}:${derived.start}`,\n `${base.moduleId}:${base.start}`,\n ])\n .sort((a, b) => a[0].localeCompare(b[0]) || a[1].localeCompare(b[1])),\n );\n if (options.diagnostics === \"collect\" && output) {\n return {\n ...output,\n hasModuleCssImport,\n compositionModules,\n compositionTopology,\n diagnostics: modules.flatMap((module) => module.diagnostics),\n reports: modules.flatMap((module) => module.reports),\n };\n }\n if (!output?.code) {\n return undefined;\n }\n return {\n ...output,\n hasModuleCssImport,\n compositionModules,\n compositionTopology,\n };\n}\n\n/**\n * Populates analysis batches and removes artifacts when missing semantic facts block lowering.\n *\n * @param analysis - Mutable result whose unverified ranges are deduplicated and generation status updated.\n * @param modules - Mutable native outputs whose reports are filtered and artifacts may be cleared.\n * @param session - Session used to diagnose sources independently when facts are unavailable.\n * @param typedSources - Prepared sources from the same compilation, with available type facts attached.\n * @param graph - Graph retaining scanner summaries for the compiled modules.\n */\nfunction recordAnalysis(\n analysis: ModuleAnalysis,\n modules: ProjectModuleOutput[],\n session: NativeProjectSession,\n typedSources: NativePreparedSource[],\n graph: ModuleGraph,\n): void {\n analysis.modules = modules;\n analysis.unverified = [\n ...new Map(analysis.unverified.map((range) => [JSON.stringify(range), range])).values(),\n ];\n const localReports = analysis.unverified.length ? session.diagnose(typedSources) : [];\n for (const module of modules) {\n module.reports =\n localReports.find((batch) => batch.module === module.moduleId)?.reports ?? module.reports;\n const ranges = analysis.unverified.filter((range) => range.moduleId === module.moduleId);\n const generationUnverified = generationNeedsFacts(graph.summary(module.moduleId), ranges);\n module.reports = verifiedReports(module.reports, ranges);\n if (generationUnverified || module.diagnostics.length) {\n analysis.generation = \"blocked\";\n }\n if (generationUnverified) {\n clearArtifacts(module);\n }\n analysis.batches.push({\n module: module.moduleId,\n reports: module.reports,\n });\n }\n}\n\n/**\n * Checks whether unavailable semantic information affects a probe required for lowering.\n *\n * @param summary - Scanner summary for the module, or undefined if unavailable.\n * @param ranges - Unverified ranges in original UTF-8 bytes. Missing bounds cover the whole module.\n * @returns Whether an unbounded range exists or a bounded range overlaps a probe beyond recognition.\n */\nfunction generationNeedsFacts(\n summary: NativeModuleSummary | undefined,\n ranges: UnverifiedRange[],\n): boolean {\n return ranges.some((range) => {\n if (range.start === undefined || range.end === undefined) {\n return true;\n }\n return summary?.typeProbes.some(\n (probe) => !probe.recognitionOnly && overlaps(range, probe.start, probe.end),\n );\n });\n}\n\n/**\n * Keeps source failures while omitting missing checker facts errors in unverified ranges.\n *\n * @param reports - Reports with original UTF-8 locations.\n * @param ranges - Unverified original UTF-8 ranges for the same module.\n * @returns A filtered array in report order. Other diagnostic codes remain unchanged.\n */\nfunction verifiedReports(reports: BindingReport[], ranges: UnverifiedRange[]): BindingReport[] {\n return reports.filter((report) => {\n if (report.code !== checkerFactsRequiredCode) {\n return true;\n }\n const { start, end } = report.primary.location;\n return !ranges.some((range) => overlaps(range, start, end));\n });\n}\n\n/** `CompileDiagnostic::CheckerFactsRequired`, which unverified semantic ranges can cause. */\nconst checkerFactsRequiredCode = \"SW30001\";\n\n/**\n * Tests whether a diagnostic or probe overlaps an unavailable semantic range.\n *\n * @param range - Half-open original UTF-8 range. Missing bounds cover the entire module.\n * @param start - Inclusive original UTF-8 byte offset.\n * @param end - Exclusive original UTF-8 byte offset.\n * @returns Whether the ranges intersect, treating an unbounded range as intersecting everything.\n */\nfunction overlaps(range: UnverifiedRange, start: number, end: number): boolean {\n if (range.start === undefined || range.end === undefined) {\n return true;\n }\n return start < range.end && end > range.start;\n}\n\n/**\n * Removes generated artifacts while keeping reports and composition metadata for analysis.\n *\n * @param module - Mutable output whose missing facts make its generated artifacts unreliable.\n */\nfunction clearArtifacts(module: ProjectModuleOutput): void {\n module.code = null;\n module.css = \"\";\n module.resources = [];\n module.classes = [];\n module.symbols = [];\n module.mappings = [];\n}\n\n/**\n * Checks output identities, reports lint and rejected-name warnings, and enforces diagnostic policy.\n *\n * @param modules - Native outputs with identities registered in graph.\n * @param graph - Source graph used to verify each output's host identity.\n * @param host - Warning receiver, which may receive messages before a later failure.\n * @param options - Collect mode retains compiler reports instead of throwing.\n * @throws If an output identity is unknown or throw mode encounters compiler errors.\n */\nfunction reportOutputDiagnostics(\n modules: ProjectModuleOutput[],\n graph: ModuleGraph,\n host: CompilerHost,\n options: ModuleCompileOptions,\n): void {\n for (const output of modules) {\n graph.resolverId(output.moduleId);\n if (output.diagnostics.length > 0 && options.diagnostics !== \"collect\") {\n throw new CompilationFailure(\n modules\n .filter((module) => module.diagnostics.length > 0)\n .map((module) => ({\n module: module.moduleId,\n reports: module.reports,\n })),\n );\n }\n reportLintWarnings(output, host);\n warnRejectedNames(output.rejectedNames ?? [], (message) => host.warn(message));\n }\n}\n\n/**\n * Reports naming fallbacks through the host warning channel without a source location.\n *\n * @param rejected - Generator rejections in request order.\n * @param warn - Receives the family, input hash, and rejection reason for each fallback.\n */\nexport function warnRejectedNames(\n rejected: readonly BindingRejectedIdentifier[],\n warn: (message: string) => void,\n): void {\n for (const entry of rejected) {\n warn(`stillwind: the ${entry.kind} name for ${entry.hash} was rejected: ${entry.reason}`);\n }\n}\n\n/**\n * Sends enabled lint findings through the host without changing their report severity.\n *\n * @param output - Findings and per-rule lint levels. Missing settings default to off.\n * @param host - Receiver for warning text with original source positions.\n */\nfunction reportLintWarnings(output: ProjectModuleOutput, host: CompilerHost): void {\n for (const finding of output.lintFindings ?? []) {\n const level = output.lintSettings?.[finding.rule] ?? \"off\";\n if (level === \"off\") {\n continue;\n }\n host.warn(`${finding.rule}: ${finding.message} (${finding.uri}:${finding.start})`);\n }\n}\n\n/**\n * Projects a report's primary label into the diagnostic shape returned by compilation.\n *\n * @param report - Structured compiler report.\n * @returns Primary location and scope, diagnostic code and class, message, and notes. Related\n * labels and severity remain in the report.\n */\nfunction reportDiagnostic(report: BindingReport): BindingDiagnostic {\n return {\n ...report.primary.location,\n scope: report.primary.scope,\n code: report.code,\n ...(report.class && { class: report.class }),\n message: report.message,\n notes: report.notes,\n };\n}\n\n/**\n * Builds a collect-mode entry output when preparation, scanning, or checking failed.\n *\n * @param moduleId - Compiler identity of the entry module.\n * @param batches - Failure reports from the attempted compilation.\n * @param hasModuleCssImport - Whether scanning found an explicit CSS value import in the entry.\n * @returns An output with null code, empty generated artifacts, all reports, and diagnostics\n * derived only from error reports.\n */\nfunction failedOutput(\n moduleId: string,\n batches: readonly NativeDiagnosticBatch[],\n hasModuleCssImport: boolean,\n) {\n const reports = batches.flatMap((batch) => batch.reports);\n\n return {\n moduleId,\n code: null,\n css: \"\",\n resources: [],\n mappings: [],\n classes: [],\n symbols: [],\n diagnostics: reports.filter((report) => report.severity === \"error\").map(reportDiagnostic),\n reports,\n rejectedNames: [],\n dynamicCandidates: [],\n lintFindings: [],\n lintSettings: {} as Record<string, \"off\" | \"warn\" | \"deny\">,\n composition: [],\n hasModuleCssImport,\n compositionModules: [],\n compositionTopology: \"[]\",\n };\n}\n","/**\n * Formats notices as the prefix of a published stylesheet.\n *\n * @param banners - Notices in published order without duplicates, as a native plan or part lists\n * them. Callers that combine lists must order them again with `cssBanners` from `stillwind/css`.\n * @returns The notices in the given order, each followed by a newline.\n */\nexport function cssBannerPrefix(banners: readonly string[]): string {\n return banners.map((banner) => `${banner}\\n`).join(\"\");\n}\n\n/**\n * Adds notices before a CSS body without changing the body.\n *\n * @param output - CSS body and the notices that it requires, in the form that\n * {@link cssBannerPrefix} accepts.\n * @returns The published stylesheet text, or an empty string when the body is blank.\n */\nexport function finalizeCss(output: { css: string; banners?: readonly string[] }): string {\n return output.css.trim() ? cssBannerPrefix(output.banners ?? []) + output.css : \"\";\n}\n","import type { PluginDirectoryEntry, StillwindPlugin, TailwindConfig } from \"@stillwind/config\";\nimport type { NativeCssRequest } from \"@stillwind/native\";\n\nimport type { PluginPathHost } from \"./paths.ts\";\n\n/**\n * A plugin written against Tailwind CSS v4's JavaScript plugin API: a handler, `{ handler,\n * config }`, or a factory from `plugin.withOptions`. The host loads its adapter, and with it the\n * `tailwindcss` package, only when a `@plugin` statement selects such a plugin.\n */\nexport type TailwindPlugin =\n | ((...args: never[]) => unknown)\n | {\n /** Handler that receives Tailwind's plugin API. */\n handler: (...args: never[]) => unknown;\n /** v3-style config, such as `theme.extend`. */\n config?: object;\n };\n\n/**\n * Project settings that the Tailwind plugin adapter applies to the whole CSS graph.\n */\nexport interface TailwindSettings {\n /** Tailwind configuration, or a promise for one, which replaces Tailwind's `@config`. */\n tailwind?: TailwindConfig | Promise<TailwindConfig>;\n /** Value of Tailwind's `important` configuration key. */\n important?: true | string;\n}\n\n/**\n * Matches an import or `@plugin` specifier that names a file by a relative or absolute path or\n * a `file:` URL, rather than a package.\n */\nexport const PATH_SPECIFIER = /^(?:\\.{1,2}[\\\\/]|[\\\\/]|[a-z]:[\\\\/]|file:)/i;\n\n/**\n * A native Stillwind plugin or a plugin using Tailwind v4's JavaScript API.\n */\nexport type LoadedPlugin = StillwindPlugin | TailwindPlugin;\n\n/**\n * Recognizes Tailwind's plugin export forms without executing a factory.\n *\n * @param value - Default export of a plugin module.\n * @returns Whether `value` is a function or an object with a `handler` function.\n */\nfunction isTailwindPlugin(value: unknown): value is TailwindPlugin {\n return (\n typeof value === \"function\" ||\n (typeof value === \"object\" &&\n value !== null &&\n typeof (\n value as {\n handler?: unknown;\n }\n ).handler === \"function\")\n );\n}\n\n/**\n * Whether a loaded plugin uses the Stillwind plugin contract.\n *\n * @param plugin - Configured or loaded plugin.\n * @returns Whether `plugin` has a `css` function, which Tailwind plugins lack.\n */\nexport function nativePlugin(plugin: LoadedPlugin): plugin is StillwindPlugin {\n return (\n typeof plugin === \"object\" &&\n plugin !== null &&\n \"css\" in plugin &&\n typeof plugin.css === \"function\"\n );\n}\n\n/**\n * Host operations for plugin packages and the files that plugins read. Paths are absolute host\n * identities, which the host's `read` accepts.\n */\nexport interface PluginHost extends PluginPathHost {\n /**\n * Loads the plugin package that an `@plugin` statement names when no configured plugin has\n * that name.\n *\n * @param specifier - Package specifier or path from the statement.\n * @param importer - Resolved identity of the stylesheet that contains the statement.\n * @param watch - Registers each file whose change must load the plugin again. A host that\n * returns the same plugin for unchanged files still registers them on every call.\n * @returns The plugin that the module exports by default, as {@link defaultPluginExport} checks.\n * @throws If resolution or evaluation fails, or the default export is not a plugin.\n */\n load(specifier: string, importer: string, watch: (path: string) => void): Promise<LoadedPlugin>;\n\n /**\n * Reads a text file requested by a plugin.\n *\n * @param path - Absolute file path.\n * @returns The file's text.\n * @throws If the file does not exist or cannot be read.\n */\n read(path: string): Promise<string>;\n\n /**\n * Lists a directory requested by a plugin. Omission makes plugin directory reads fail.\n *\n * @param path - Absolute directory path.\n * @returns The directory's own entries.\n * @throws If the directory does not exist or cannot be read.\n */\n list?(path: string): Promise<readonly PluginDirectoryEntry[]>;\n}\n\n/**\n * Selects the plugin that a module exports by default.\n *\n * @param module - Evaluated module namespace.\n * @param specifier - Request that loaded the module, used in the error message.\n * @returns The default export.\n * @throws If the default export is neither a Stillwind plugin object nor a Tailwind v4 plugin.\n */\nexport function defaultPluginExport(module: unknown, specifier: string): LoadedPlugin {\n const plugin = (module as { default?: unknown } | null)?.default;\n if (isTailwindPlugin(plugin)) {\n return plugin;\n }\n if (\n typeof plugin !== \"object\" ||\n plugin === null ||\n typeof (plugin as StillwindPlugin).name !== \"string\" ||\n typeof (plugin as StillwindPlugin).css !== \"function\"\n ) {\n throw new Error(\n `Stillwind plugin ${specifier} must export a plugin object by default, or a Tailwind v4 handler`,\n );\n }\n return plugin as StillwindPlugin;\n}\n\n/**\n * Returns the utility text before the cursor for plugin catalog lookup.\n *\n * @param text - Text before the cursor. The candidate ends at the cursor and starts after the\n * last whitespace, quote, backtick, `;`, `{`, or `}`.\n * @returns The candidate without its variants, such as `icon-mdi--cl` for `hover:icon-mdi--cl`.\n */\nexport function catalogInput(text: string): string {\n const candidate = /[^\\s\"'`;{}]*$/.exec(text)![0];\n let depth = 0;\n for (let index = candidate.length - 1; index >= 0; index--) {\n const character = candidate[index];\n if (character === \"]\" || character === \")\") {\n depth++;\n } else if ((character === \"[\" || character === \"(\") && depth > 0) {\n depth--;\n } else if (character === \":\" && depth === 0) {\n return candidate.slice(index + 1);\n }\n }\n return candidate;\n}\n\n/**\n * Identifies one `@plugin` statement independently of its request ID.\n *\n * @param request - Plugin request.\n * @returns Importer, specifier, and JSON options joined by NUL characters.\n */\nexport function instanceKey(request: NativeCssRequest): string {\n return `${request.importer}\\0${request.specifier}\\0${JSON.stringify(request.pluginOptions ?? [])}`;\n}\n\n/**\n * Identifies one request independently of its ID, which changes between loads.\n *\n * @param request - Loader request.\n * @returns Importer, specifier, and JSON plugin options joined by NUL characters. An `@import`\n * has no options part.\n */\nexport function answerKey(request: NativeCssRequest): string {\n return `${request.importer}\\0${request.specifier}\\0${JSON.stringify(request.pluginOptions) ?? \"\"}`;\n}\n","import type {\n PluginContext,\n PluginWatchKind,\n StillwindPlugin,\n TailwindConfig,\n} from \"@stillwind/config\";\nimport {\n NativeDesignSystemLoader,\n type NativeCompilerOptions,\n type NativeCssFileInput,\n type NativeCssLoadStep,\n type NativeCssRequest,\n type NativeEditorQuery,\n type NativeProjectSession,\n} from \"@stillwind/native\";\n\nimport {\n PATH_SPECIFIER,\n answerKey,\n instanceKey,\n nativePlugin,\n type LoadedPlugin,\n type PluginHost,\n type TailwindSettings,\n} from \"./host.ts\";\nimport type { configurePlugin } from \"./tailwind/configuration.ts\";\nimport type { TailwindRuntime } from \"./tailwind/plugin.ts\";\n\n/**\n * Specifier of the `@plugin` request that the native loader adds after the root stylesheet for\n * the Tailwind settings. Decoded CSS never contains NUL, so no authored statement has it.\n */\nconst SETTINGS = \"\\0stillwind-tailwind-settings\";\n\n/**\n * Number of nonempty editor inputs whose catalogs a runtime keeps.\n */\nconst CATALOG_INPUTS = 16;\n\n/**\n * Matches `@stillwind-dynamic <prefix>*;` or `<prefix>[*];` and captures the prefix.\n */\nconst DYNAMIC = /@stillwind-dynamic\\s+([^\\s;*[\\]]+)(?:\\[\\*\\]|\\*)\\s*;/g;\n\n/**\n * One `@plugin` statement with its plugin, options, and the CSS answered for it.\n */\ninterface PluginInstance {\n /** Plugin that the statement selected. */\n plugin: LoadedPlugin;\n /** Configured Tailwind handler, evaluated after the complete CSS theme is available. */\n tailwind?: ReturnType<typeof configurePlugin>;\n /** Options and host operations passed to every plugin call. */\n context: PluginContext;\n /** CSS that {@link StillwindPlugin.css} returned. */\n css: string;\n /** Prefixes of the dynamic families that `css` declares. */\n prefixes: string[];\n /** Candidates passed to {@link StillwindPlugin.resolve}, including ones it left undefined. */\n candidates: string[];\n /** CSS returned by {@link StillwindPlugin.resolve}, in the order of its calls. */\n definitions: string[];\n /** Origin of the definitions in the statement's answer. */\n origin: NonNullable<NativeCssFileInput[\"origin\"]>;\n}\n\n/**\n * A recorded answer to one loader request, keyed by importer, specifier, and options.\n */\ntype RecordedAnswer = Omit<NativeCssFileInput, \"id\">;\n\n/**\n * Runs the plugins of one CSS graph and defines candidates of their dynamic families on demand.\n *\n * The runtime records every answer of the graph's load, so {@link PluginRuntime.replay} loads the\n * same graph again without host I/O, with the definitions that plugins have added since. A\n * candidate that a plugin leaves undefined is not requested again for the runtime's lifetime.\n *\n * Tailwind plugins of the graph share one adapter runtime, which {@link PluginRuntime.initialize}\n * creates after the first load because their handlers read the complete CSS theme.\n */\nexport class PluginRuntime {\n /** Plugin statements keyed by importer, specifier, and options text. */\n readonly #instances = new Map<string, PluginInstance>();\n\n /** Recorded answers keyed by {@link answerKey}. */\n readonly #answers = new Map<string, RecordedAnswer>();\n\n /** Requests of the load by importer and request ID, which order the plugin statements. */\n readonly #requests = new Map<string, Map<number, NativeCssRequest>>();\n\n /** Root answer, recorded by {@link PluginRuntime.recordRoot}. */\n #root?: RecordedAnswer;\n\n /** Candidates already passed to a plugin, including ones it left undefined. */\n readonly #requested = new Set<string>();\n\n /** Editor catalogs keyed by input, oldest first. The empty input is never evicted. */\n readonly #catalogs = new Map<string, Promise<readonly string[]>>();\n\n /**\n * Number of {@link PluginRuntime.resolve} calls that added CSS. The loader of the original\n * load contains the definitions of generation zero.\n */\n #generation = 0;\n\n /** Runtime of every Tailwind plugin of the graph, which share one config and theme. */\n #tailwind?: TailwindRuntime;\n\n /** Loader of the original load, whose source IDs replays share without a session. */\n #loader?: NativeDesignSystemLoader;\n\n /** Loader for the last queried definition generation. Source usage remains in separate sessions. */\n #snapshot?: {\n /** Definition generation represented by loader. */\n generation: number;\n /** Shared loader used for editor queries. Callers must not add CSS to it. */\n loader: NativeDesignSystemLoader;\n };\n\n /** Tailwind statements in stylesheet order; an index is the statement's owner index. */\n #tailwindInstances: PluginInstance[] = [];\n\n /** Answer to the {@link SETTINGS} request, which the Tailwind runtime generates. */\n #settingsCss = \"\";\n\n /**\n * Creates a runtime for one load.\n *\n * @param options - Compiler options of the load, reused by {@link PluginRuntime.replay}.\n * @param plugins - Plugins configured for the project, which take precedence over packages.\n * @param root - Absolute project directory passed to plugins.\n * @param host - Loads plugin packages and plugin files, or undefined when the host can only use\n * configured plugins.\n * @param watch - Registers files and directories that plugins read.\n * @param previous - Runtime of an earlier load of the same project. A statement with the same\n * specifier, options, and plugin resolves the earlier load's candidates of its families again.\n * @param settings - Project's Tailwind settings. Either field makes the graph use the Tailwind\n * plugin adapter, as a Tailwind `@plugin` statement does.\n */\n constructor(\n readonly options: NativeCompilerOptions,\n readonly plugins: readonly StillwindPlugin[],\n readonly root: string,\n readonly host: PluginHost | undefined,\n readonly watch: (path: string, kind?: PluginWatchKind) => void,\n readonly previous?: PluginRuntime,\n readonly settings?: TailwindSettings,\n ) {}\n\n /** Number of definition batches added after the original load. */\n get generation(): number {\n return this.#generation;\n }\n\n /** Whether project settings or a loaded plugin require the Tailwind adapter. */\n get tailwind(): boolean {\n return (\n this.settings?.tailwind !== undefined ||\n this.settings?.important !== undefined ||\n [...this.#instances.values()].some((instance) => instance.tailwind)\n );\n }\n\n /** Whether any loaded plugin declares a dynamic family. */\n get dynamic(): boolean {\n return (\n !!this.#tailwind ||\n [...this.#instances.values()].some((instance) => instance.prefixes.length > 0)\n );\n }\n\n /**\n * Records the root answer of the load.\n *\n * @param answer - Root input without its request ID.\n */\n recordRoot(answer: RecordedAnswer): void {\n this.#root = answer;\n }\n\n /**\n * Records the answer to an `@import` request so that a replay can repeat it.\n *\n * @param request - Loader request.\n * @param answer - File input supplied for it, without its request ID.\n */\n recordImport(request: NativeCssRequest, answer: RecordedAnswer): void {\n this.#recordRequest(request);\n this.#answers.set(answerKey(request), answer);\n }\n\n /**\n * Runs the plugin of an `@plugin` request and returns the answer for it.\n *\n * The answer's definitions are the user's own when the host loads the plugin from a\n * relative or absolute path and `own` is true. Otherwise, they belong to the plugin that the\n * specifier names, including a plugin configured for the project.\n *\n * @param request - Loader request whose `pluginOptions` is set.\n * @param own - Whether the stylesheet that contains the statement is the user's own CSS.\n * @returns File input without its request ID. Its name identifies the specifier and options.\n * @throws If no plugin has the specifier's name and the host cannot load it, or the plugin fails.\n */\n async answerPlugin(request: NativeCssRequest, own = false): Promise<RecordedAnswer> {\n this.#recordRequest(request);\n const key = instanceKey(request);\n let instance = this.#instances.get(key);\n if (!instance) {\n const configured = this.plugins.find((candidate) => candidate.name === request.specifier);\n const plugin =\n configured ?? (await this.host?.load(request.specifier, request.importer, this.watch));\n if (!plugin) {\n throw new Error(\n `Stillwind plugin ${request.specifier} is not configured, and this host cannot load packages`,\n );\n }\n const context: PluginContext = {\n options: Object.fromEntries(\n (request.pluginOptions ?? []).map((option) => [option.name, option.value]),\n ),\n root: this.root,\n watch: this.watch,\n resolve: async (specifier) => this.host?.resolve(specifier, request.importer),\n read: async (path) => {\n if (!this.host) {\n throw new Error(`This host cannot read plugin files: ${path}`);\n }\n return this.host.read(path);\n },\n list: async (path) => {\n if (!this.host?.list) {\n throw new Error(`This host cannot list plugin directories: ${path}`);\n }\n return this.host.list(path);\n },\n };\n const css = nativePlugin(plugin) ? await plugin.css(context) : \"\";\n const prefixes = [...css.matchAll(DYNAMIC)].map((match) => match[1]);\n const previous = this.previous ? this.previous.#instances.get(key) : undefined;\n // Resolving again, instead of copying the earlier definitions, reads files that changed\n // since the earlier load, such as an edited icon set.\n const candidates =\n previous?.plugin === plugin && nativePlugin(plugin) && plugin.resolve\n ? previous.candidates.filter((candidate) =>\n prefixes.some((prefix) => candidate.startsWith(prefix)),\n )\n : [];\n const resolved =\n candidates.length && nativePlugin(plugin) ? await plugin.resolve!(candidates, context) : \"\";\n for (const candidate of candidates) {\n this.#requested.add(candidate);\n }\n instance = {\n plugin,\n context,\n css,\n prefixes,\n candidates,\n definitions: resolved.trim() ? [resolved] : [],\n origin:\n !configured && own && PATH_SPECIFIER.test(request.specifier)\n ? { kind: \"own\" }\n : { kind: \"plugin\", name: request.specifier },\n tailwind: nativePlugin(plugin)\n ? undefined\n : (await import(\"./tailwind/configuration.ts\")).configurePlugin(\n plugin,\n request.pluginOptions ?? [],\n ),\n };\n this.#instances.set(key, instance);\n }\n const answer = this.#pluginAnswer(key, instance);\n this.#answers.set(answerKey(request), answer);\n return answer;\n }\n\n /**\n * Evaluates Tailwind handlers with the complete CSS theme, then resolves the candidates of\n * dynamic families that the graph's CSS applies with `@apply` and `@variant`.\n *\n * Tailwind handlers run after the first load because their `theme()` calls read the complete\n * CSS theme. Their output then needs one more load of the recorded graph. Dynamic candidates in\n * the graph's CSS need one more load when a plugin defines any of them, with or without\n * Tailwind. Canonical queries prepare spelling indexes on demand.\n *\n * Each later load requests the Tailwind settings after the root stylesheet, as\n * {@link TailwindRuntime.settingsCss} describes.\n *\n * @param loader - Loader of the completed original load. With Tailwind plugins or settings, it\n * can skip its canonical spelling index, as {@link PluginRuntime.tailwind} allows.\n * @returns `loader` when no plugin adds CSS, and otherwise a loader with the added CSS.\n * @throws If the Tailwind configuration is rejected or invalid, a plugin, a handler, or a\n * callback fails, or the native loader rejects the generated CSS.\n */\n async initialize(loader: NativeDesignSystemLoader): Promise<NativeDesignSystemLoader> {\n this.#loader = loader;\n const instances = this.#orderedInstances().filter((instance) => instance.tailwind);\n const project = await this.#projectConfig();\n let current = loader;\n if (instances.length || project) {\n this.#tailwindInstances = instances;\n const { TailwindRuntime } = await import(\"./tailwind/plugin.ts\");\n const editor = loader.editorQuery();\n this.#tailwind = new TailwindRuntime(\n instances.map((instance) => instance.tailwind!),\n editor.themeTokens(),\n editor.legacyThemeKeys(),\n project,\n );\n if (this.previous) {\n await this.resolve(this.previous.#requested);\n }\n this.#updateTailwindCss();\n current = this.replay(undefined, true);\n }\n if (!this.dynamic) {\n this.#snapshot = {\n generation: this.#generation,\n loader: current,\n };\n return current;\n }\n // Only `@apply` and `@variant` uses count. A scan of the whole text would also report the\n // names in definition headers and registry metadata, such as `@stillwind-utility duration-*`,\n // so every graph that imports Stillwind would load once more.\n const query = current.editorQuery();\n const sources = [\n this.#root?.content ?? \"\",\n ...[...this.#answers.values()].map((a) => a.content),\n ];\n if (await this.resolve(sources.flatMap((css) => query.stylesheetDynamicCandidates(css)))) {\n current = this.replay(undefined, true);\n }\n this.#snapshot = {\n generation: this.#generation,\n loader: current,\n };\n return current;\n }\n\n /**\n * Loads the runtime's current CSS definitions once per definition generation.\n *\n * @returns The shared loader for editor queries. Do not add CSS or session usage to it.\n * @throws If the native loader rejects the plugin definitions.\n */\n snapshot(): NativeDesignSystemLoader {\n if (this.#snapshot?.generation !== this.#generation) {\n this.#snapshot = {\n generation: this.#generation,\n loader: this.replay(undefined, true),\n };\n }\n return this.#snapshot.loader;\n }\n\n /**\n * Resolves one editor candidate in a separate loader without changing a session's used CSS.\n *\n * @param candidate - Candidate as an editor offers it, such as `probe-4` or `state-open:`.\n * @returns Queries over the shared loader containing the candidate's definitions.\n * @throws If a plugin fails or the native loader rejects the generated CSS.\n */\n async query(candidate: string): Promise<NativeEditorQuery> {\n const query = this.snapshot().editorQuery();\n return (await this.resolve(query.dynamicCandidates(candidate)))\n ? this.snapshot().editorQuery()\n : query;\n }\n\n /**\n * Passes new candidates to the plugins that declare their families.\n *\n * @param candidates - Compiler requests for native utility names, complete Tailwind utility\n * keys, or variant names with an `@variant ` prefix. Previously requested keys are skipped.\n * @returns Whether any plugin returned CSS, so that the design system must be loaded again.\n * @throws If a plugin fails.\n */\n async resolve(candidates: Iterable<string>): Promise<boolean> {\n const pending = new Map<PluginInstance, string[]>();\n const tailwind: string[] = [];\n for (const candidate of candidates) {\n if (this.#requested.has(candidate)) {\n continue;\n }\n this.#requested.add(candidate);\n if (this.#tailwind?.accepts(candidate)) {\n tailwind.push(candidate);\n }\n for (const instance of this.#instances.values()) {\n if (\n nativePlugin(instance.plugin) &&\n instance.plugin.resolve &&\n instance.prefixes.some((prefix) => candidate.startsWith(prefix))\n ) {\n pending.set(instance, [...(pending.get(instance) ?? []), candidate]);\n break;\n }\n }\n }\n let changed = this.#tailwind?.resolve(tailwind) ?? false;\n if (changed) {\n this.#updateTailwindCss();\n }\n for (const [instance, names] of pending) {\n instance.candidates.push(...names);\n const css = nativePlugin(instance.plugin)\n ? await instance.plugin.resolve!(names, instance.context)\n : \"\";\n if (css.trim()) {\n instance.definitions.push(css);\n changed = true;\n }\n }\n if (changed) {\n this.#generation++;\n }\n return changed;\n }\n\n /**\n * Lists the candidates that editors complete for the loaded dynamic families.\n *\n * @param input - Utility text before an editor's cursor, without variants, or an empty string\n * for the candidates that editors always offer.\n * @returns Candidate names that start with `input`, from every plugin with a catalog, sorted\n * and deduplicated. Names that end with `-` are incomplete. The runtime keeps the answers for\n * the empty input and for the {@link CATALOG_INPUTS} most recent other inputs.\n */\n catalog(input = \"\"): Promise<readonly string[]> {\n let names = this.#catalogs.get(input);\n if (names) {\n // Moves the input to the end, so eviction removes the least recently used input.\n this.#catalogs.delete(input);\n } else {\n names = Promise.all(\n [...this.#instances.values()].map(async (instance): Promise<readonly string[]> =>\n nativePlugin(instance.plugin) && instance.plugin.catalog\n ? await instance.plugin.catalog(instance.context, input)\n : [],\n ),\n ).then((lists) =>\n [...new Set([...lists.flat(), ...(this.#tailwind?.catalog() ?? [])])]\n .filter((name) => name.startsWith(input))\n .sort(),\n );\n }\n this.#catalogs.set(input, names);\n for (const key of this.#catalogs.keys()) {\n if (this.#catalogs.size <= CATALOG_INPUTS + 1) {\n break;\n }\n if (key) {\n this.#catalogs.delete(key);\n }\n }\n return names;\n }\n\n /**\n * Loads the recorded graph again into a loader of `session`, with the current definitions.\n *\n * @param session - Session whose source IDs the new loader shares. Omission shares the\n * original loader's source IDs.\n * @param intermediate - Skips preparing the canonical spelling index for a loader that only\n * serves a later load or a short query. Canonical queries still prepare it on first use.\n * @returns A complete loader with the load's compiler options, for\n * {@link NativeProjectSession.reload}.\n * @throws If the recorded graph is incomplete or the native loader rejects it.\n */\n replay(session?: NativeProjectSession, intermediate = false): NativeDesignSystemLoader {\n if (!this.#root) {\n throw new Error(\"Stillwind plugin runtime has no recorded CSS graph\");\n }\n const loader = session\n ? session.newLoader(this.options)\n : (this.#loader?.newLoader(this.options) ?? new NativeDesignSystemLoader(this.options));\n if (intermediate) {\n loader.deferCanonicalIndex();\n }\n if (this.#tailwind) {\n loader.requestTrailingPlugin(SETTINGS);\n }\n let step: NativeCssLoadStep = loader.provide(\n 0,\n this.#root.name,\n this.#root.content,\n this.#root.uri,\n this.#root.sourceMapSource,\n this.#root.lint,\n );\n while (step.kind !== \"complete\") {\n step = loader.provideMany(\n step.requests.map((request) => {\n if (\n this.#tailwind &&\n request.specifier === SETTINGS &&\n request.pluginOptions !== undefined\n ) {\n return {\n id: request.id,\n name: `stillwind-plugin:${SETTINGS.slice(1)}#${this.#generation}`,\n content: this.#settingsCss,\n };\n }\n const instance =\n request.pluginOptions !== undefined\n ? this.#instances.get(instanceKey(request))\n : undefined;\n const answer = instance\n ? this.#pluginAnswer(instanceKey(request), instance)\n : this.#answers.get(answerKey(request));\n if (!answer) {\n throw new Error(`Stillwind plugin runtime has no answer for ${request.specifier}`);\n }\n return {\n id: request.id,\n ...answer,\n };\n }),\n );\n }\n return loader;\n }\n\n /**\n * Returns the answer to a plugin request with the instance's current definitions.\n *\n * @param key - Importer, specifier, and options text of the instance.\n * @param instance - Loaded plugin statement.\n * @returns An internal buffer whose name changes with its content.\n */\n #pluginAnswer(key: string, instance: PluginInstance): RecordedAnswer {\n return {\n name: `stillwind-plugin:${key.replaceAll(\"\\0\", \"#\")}#${this.#generation}#${instance.definitions.length}`,\n content: [instance.css, ...instance.definitions].join(\"\\n\"),\n origin: instance.origin,\n };\n }\n\n /**\n * Stores the generated CSS of each Tailwind statement and of the settings as their answers.\n */\n #updateTailwindCss(): void {\n for (const [owner, instance] of this.#tailwindInstances.entries()) {\n instance.css = this.#tailwind!.css(owner);\n }\n this.#settingsCss = this.#tailwind!.settingsCss();\n }\n\n /**\n * Awaits the project's Tailwind configuration and applies its `important` field.\n *\n * @returns The configuration with `important` applied, or undefined without settings.\n * @throws If the configuration promise rejects, its value is not an object, or both the field\n * and the configuration set `important`.\n */\n async #projectConfig(): Promise<TailwindConfig | undefined> {\n const { important } = this.settings ?? {};\n const tailwind: unknown = await this.settings?.tailwind;\n if (tailwind === undefined) {\n return important === undefined\n ? undefined\n : {\n important,\n };\n }\n if (typeof tailwind !== \"object\" || tailwind === null || Array.isArray(tailwind)) {\n throw new Error(\"Stillwind config tailwind must resolve to a Tailwind configuration object\");\n }\n const config = tailwind as TailwindConfig;\n if (important === undefined) {\n return config;\n }\n if (config.important !== undefined) {\n throw new Error(\n \"Stillwind config important must not be set together with tailwind.important\",\n );\n }\n return {\n ...config,\n important,\n };\n }\n\n /**\n * Records a request of the load, which orders the plugin statements.\n *\n * @param request - Import or plugin request.\n */\n #recordRequest(request: NativeCssRequest): void {\n let requests = this.#requests.get(request.importer);\n if (!requests) {\n this.#requests.set(request.importer, (requests = new Map()));\n }\n requests.set(request.id, request);\n }\n\n /**\n * Orders the plugin statements as the import-expanded stylesheet does.\n *\n * @returns Each statement once, depth first from the root in request order.\n */\n #orderedInstances(): PluginInstance[] {\n const result = new Set<PluginInstance>();\n const visited = new Set<string>();\n /**\n * Adds the statements of one stylesheet and of the stylesheets it imports.\n *\n * @param name - Recorded identity of the stylesheet.\n */\n const visit = (name: string) => {\n if (visited.has(name)) {\n return;\n }\n visited.add(name);\n for (const request of [...(this.#requests.get(name)?.values() ?? [])].sort(\n (a, b) => a.id - b.id,\n )) {\n const instance = this.#instances.get(instanceKey(request));\n if (request.pluginOptions !== undefined && instance) {\n result.add(instance);\n } else {\n const answer = this.#answers.get(answerKey(request));\n if (answer) {\n visit(answer.name);\n }\n }\n }\n };\n if (this.#root) {\n visit(this.#root.name);\n }\n return [...result];\n }\n}\n","import type { StillwindPlugin } from \"@stillwind/config\";\nimport {\n editorCssSource,\n NativeDesignSystemLoader,\n type NativeCompilerOptions,\n type NativeCssFileInput,\n type NativeCssLoadStep,\n type NativeCssResource,\n type NativeSkippedCss,\n} from \"@stillwind/native\";\n\nimport { PATH_SPECIFIER, type PluginHost, type TailwindSettings } from \"./plugins/host.ts\";\nimport { PluginRuntime } from \"./plugins/runtime.ts\";\n\n/**\n * Checks whether an identity names a stylesheet.\n *\n * @param id - Resolver identity or file path.\n * @returns Whether the complete identity ends in `.css`, ignoring case. The check includes any\n * query suffix.\n */\nexport function isStylesheet(id: string): boolean {\n return /\\.css$/i.test(id);\n}\n\n/**\n * A CSS graph for interactive queries. Recovered text must never supply lint fixes or builds.\n */\nexport interface EditorCssGraph extends Omit<LoadedCssGraph, \"skipped\"> {\n /** Whether incomplete sources were replaced with recovered definitions. */\n recovered: boolean;\n}\n\n/**\n * Loads original CSS, then retries with recovered definitions if that load fails.\n *\n * @param root - Resolved CSS entrypoint.\n * @param options - Compiler policies used by semantic queries.\n * @param host - Resolver and reads of the captured original buffers.\n * @param pluginInputs - Plugins for `@plugin` statements, as {@link loadCssGraph} describes.\n * @returns A query graph and whether its sources were recovered. Original buffers remain unchanged.\n * The recovered graph must only supply editor queries, because its text omits authored rules.\n * @throws If both loads fail, including unresolved imports or unreadable files.\n */\nexport async function loadEditorCssGraph(\n root: string,\n options: NativeCompilerOptions,\n host: CssHost,\n pluginInputs?: CssPluginInputs,\n): Promise<EditorCssGraph> {\n try {\n return {\n ...(await loadCssGraph(root, options, host, undefined, undefined, pluginInputs)),\n recovered: false,\n };\n } catch {\n return {\n ...(await loadCssGraph(\n root,\n options,\n {\n ...host,\n read: async (id) => editorCssSource(await host.read(id)),\n },\n undefined,\n undefined,\n pluginInputs,\n )),\n recovered: true,\n };\n }\n}\n\n/**\n * Host operations that load the CSS graph and preserve document and source-map identities. Resolved\n * IDs must be accepted by the reader, identity functions, and watcher.\n */\nexport interface CssHost {\n /**\n * Resolves an import from one CSS file.\n *\n * @param specifier - Import request text from the stylesheet.\n * @param importer - Resolved identity of the importing stylesheet.\n * @returns A promise for a file identity accepted by the other host operations. Resolution\n * failures reject.\n */\n resolve(specifier: string, importer: string): Promise<string>;\n /**\n * Reads the text of a resolved CSS file.\n *\n * @param id - Identity returned by the resolver, or the resolved root identity.\n * @returns A promise for stylesheet text. Read failures reject.\n */\n read(id: string): Promise<string>;\n /**\n * Assigns the document identity used by compiler diagnostics.\n *\n * @param id - Resolved CSS file identity.\n * @returns A stable document URI for this file.\n */\n documentUri(id: string): string;\n /**\n * Assigns the source name recorded in CSS source maps.\n *\n * @param id - Resolved CSS file identity.\n * @returns The source identity used for mapping emitted CSS back to this file.\n */\n sourceMapSource(id: string): string;\n /**\n * Registers a resolved CSS file for dependency tracking.\n *\n * @param id - Root or dependency identity accepted by the host reader.\n */\n watch(id: string): void;\n /**\n * Registers a directory that a plugin lists, so that adding, removing, or renaming an entry\n * reloads the graph. Omission ignores directory registrations, which suits a host that loads\n * the graph once or reloads it after every file addition or removal.\n *\n * @param id - Absolute directory path.\n */\n watchDirectory?(id: string): void;\n /**\n * Decides whether stylesheet lint checks a file. Omission selects {@link lintsStylesheet}.\n *\n * @param id - Resolved CSS file identity.\n * @param importer - Identity of the importing file and whether lint checks it, or undefined for\n * the root.\n * @param specifier - Import request text, or undefined for the root.\n * @returns Whether to mark the file for stylesheet lint. Lint never changes compiled output.\n */\n lint?(\n id: string,\n importer?: {\n /** Resolved identity of the importing file. */\n id: string;\n /** Whether lint checks the importing file. */\n lint: boolean;\n },\n specifier?: string,\n ): boolean;\n /**\n * Loads plugin packages and the files that plugins read. Omission limits the graph to\n * configured plugins, whose `resolve` finds nothing and whose `read` fails.\n */\n plugins?: PluginHost;\n}\n\n/**\n * Plugins, Tailwind settings, and project inputs for the `@plugin` statements of one CSS graph.\n */\nexport interface CssPluginInputs extends TailwindSettings {\n /** Plugins configured for the project. */\n plugins?: readonly StillwindPlugin[];\n /** Absolute project directory passed to plugins. */\n root: string;\n /** Runtime of an earlier load of the same project, whose candidates are resolved again. */\n previous?: PluginRuntime;\n}\n\n/**\n * Selects the user's own CSS for stylesheet lint. The root is linted unless it lies under\n * `node_modules`. An import is linted when lint checks its importer, its specifier is a relative\n * or absolute path, and its file does not lie under `node_modules`. A package specifier such as\n * `stillwind` or `tailwindcss` therefore excludes the package and everything it imports, even when\n * the package resolves outside `node_modules`.\n *\n * @param id - Resolved CSS file identity.\n * @param importer - Importing file and its lint mark, or undefined for the root.\n * @param specifier - Import request text, or undefined for the root.\n * @returns Whether stylesheet lint checks the file.\n */\nexport function lintsStylesheet(\n id: string,\n importer?: {\n /** Resolved identity of the importing file. */\n id: string;\n /** Whether lint checks the importing file. */\n lint: boolean;\n },\n specifier?: string,\n): boolean {\n if (/[\\\\/]node_modules[\\\\/]/.test(id)) {\n return false;\n }\n return !importer || (importer.lint && specifier !== undefined && PATH_SPECIFIER.test(specifier));\n}\n\n/**\n * Names the package that supplies an imported stylesheet that is not the user's own CSS.\n *\n * A package specifier, such as `stillwind` or `@scope/name/theme.css`, names its package. A path\n * specifier keeps the package of its importer, so a package's relative imports stay in the\n * package. Otherwise, the last `node_modules` directory in `id` names the package.\n *\n * @param id - Resolved CSS file identity.\n * @param specifier - Import request text.\n * @param importerPackage - Package of the importing file, or undefined when it has none.\n * @returns The package name, or undefined when none of these rules names one.\n */\nexport function stylesheetPackage(\n id: string,\n specifier: string,\n importerPackage: string | undefined,\n): string | undefined {\n if (!PATH_SPECIFIER.test(specifier)) {\n const [first, second] = specifier.split(\"/\");\n return first.startsWith(\"@\") && second !== undefined ? `${first}/${second}` : first;\n }\n if (importerPackage !== undefined) {\n return importerPackage;\n }\n const directories = [...id.matchAll(/[\\\\/]node_modules[\\\\/]((?:@[^\\\\/]+[\\\\/])?[^\\\\/]+)/g)];\n return directories.at(-1)?.[1].replace(\"\\\\\", \"/\");\n}\n\n/**\n * Completed design-system loader and resource references discovered in its CSS graph.\n */\nexport interface LoadedCssGraph {\n /** Native loader whose complete CSS graph is ready for compilation. */\n loader: NativeDesignSystemLoader;\n /** Authored resource references that the adapter must resolve and replace in emitted CSS. */\n resources: NativeCssResource[];\n /** Identities of the files marked for stylesheet lint, in the order the loader accepted them. */\n lintSources: string[];\n /**\n * Statements that loading skipped instead of failing, such as an import that cannot be resolved,\n * ordered by source and position. Hosts that do not run stylesheet lint report them as warnings.\n */\n skipped: NativeSkippedCss[];\n /**\n * Plugins of the graph's `@plugin` statements and the definitions that they have added. Absent\n * for a graph that a host assembled without loading plugins.\n */\n plugins?: PluginRuntime;\n}\n\n/**\n * Loads a CSS graph and returns the completed native loader and its resource references.\n * `root` must already be resolved and accepted by the host's read and watch methods.\n * `options` configures a new loader. If `suppliedLoader` is given, it must not have\n * received any input yet, and this function uses its existing configuration.\n * `rootContent` skips reading the root file. The function still watches that file\n * and all resolved dependencies. Each file is marked for stylesheet lint as `host.lint` decides,\n * or as {@link lintsStylesheet} decides when the host omits it.\n * Canonical queries build their indexes on first use.\n *\n * Reads run concurrently, and each request ID is read only once. Responses ready\n * in the same event-loop turn are sent together to reduce native calls. Faster reads\n * can reveal more imports without waiting for slower reads.\n * Resolution, read, and native loading errors reject the promise. Reads already\n * started continue, and files already registered with the watcher stay registered.\n *\n * @param root - Resolved CSS entrypoint accepted by the host's read and watch operations.\n * @param options - Compiler settings used when creating a new loader.\n * @param host - CSS resolver, reader, source identity operations, and dependency watcher.\n * @param rootContent - Optional entrypoint text that replaces the initial filesystem read.\n * @param suppliedLoader - Optional configured loader that has not received any CSS input.\n * @param pluginInputs - Plugins for `@plugin` statements. Omission uses no configured plugins,\n * the root's directory as the project directory, and the host's plugin operations.\n * @returns A promise for the completed native loader and its authored resource references.\n * @throws If resolving, reading, or loading the CSS graph fails.\n */\nexport async function loadCssGraph(\n root: string,\n options: NativeCompilerOptions,\n host: CssHost,\n rootContent?: string,\n suppliedLoader?: NativeDesignSystemLoader,\n pluginInputs?: CssPluginInputs,\n): Promise<LoadedCssGraph> {\n const loader = suppliedLoader ?? new NativeDesignSystemLoader(options);\n loader.deferCanonicalIndex();\n\n const plugins = new PluginRuntime(\n options,\n pluginInputs?.plugins ?? [],\n pluginInputs?.root ?? root.replace(/[\\\\/][^\\\\/]*$/, \"\"),\n host.plugins,\n (path, kind): void => {\n if (kind === \"directory\") {\n host.watchDirectory?.(path);\n } else {\n host.watch(path);\n }\n },\n pluginInputs?.previous,\n pluginInputs && {\n tailwind: pluginInputs.tailwind,\n important: pluginInputs.important,\n },\n );\n\n host.watch(root);\n\n const lints = new Map<string, boolean>();\n // Package of each stylesheet that is not the user's own CSS, as `stylesheetPackage` names it.\n const packages = new Map<string, string | undefined>();\n const lint: typeof lintsStylesheet = (id, importer, specifier) =>\n host.lint ? host.lint(id, importer, specifier) : lintsStylesheet(id, importer, specifier);\n lints.set(root, lint(root));\n const rootAnswer = {\n name: root,\n content: rootContent ?? (await host.read(root)),\n uri: host.documentUri(root),\n sourceMapSource: host.sourceMapSource(root),\n lint: lints.get(root),\n };\n plugins.recordRoot(rootAnswer);\n const initial = loader.provide(\n 0,\n rootAnswer.name,\n rootAnswer.content,\n rootAnswer.uri,\n rootAnswer.sourceMapSource,\n rootAnswer.lint,\n );\n\n let completion:\n | Extract<\n NativeCssLoadStep,\n {\n /** Native loading-step discriminator whose resources are available after graph completion. */\n kind: \"complete\";\n }\n >\n | undefined;\n await new Promise<void>((resolveLoad, rejectLoad) => {\n const started = new Set<number>();\n let stopped = false;\n let queued = false;\n let ready: NativeCssFileInput[] = [];\n /**\n * Stops graph advancement and rejects the pending load.\n * @param error - Resolution, reading, or native loading failure passed to the caller.\n */\n const fail = (error: unknown) => {\n stopped = true;\n rejectLoad(error);\n };\n /**\n * Completes the graph or starts reads for requests that have not already started.\n * @param step - Native loading step. Completion stores resources and resolves the load.\n */\n const advance = (step: NativeCssLoadStep) => {\n if (step.kind === \"complete\") {\n completion = step;\n stopped = true;\n resolveLoad();\n return;\n }\n for (const request of step.requests) {\n // NeedFile repeats outstanding IDs, including reads already in flight.\n if (started.has(request.id)) {\n continue;\n }\n started.add(request.id);\n /**\n * Resolves, watches, and reads this request, then schedules a batch of ready responses.\n * An import that the host cannot resolve or read is answered as unresolved.\n * @returns A promise that resolves after queuing the response, or after observing a stopped load.\n * @throws If a plugin fails to load. The attached rejection handler stops the load.\n */\n const read = async () => {\n if (request.pluginOptions !== undefined) {\n const answer = await plugins.answerPlugin(\n request,\n lints.get(request.importer) ?? false,\n );\n if (plugins.tailwind) {\n // `PluginRuntime.initialize` loads the graph again, so this load only provides its\n // theme and recorded answers.\n loader.deferCanonicalIndex();\n }\n if (!stopped) {\n ready.push({\n id: request.id,\n ...answer,\n });\n schedule();\n }\n return;\n }\n /**\n * Answers the request as unresolved, so the loader skips the import and stylesheet lint\n * reports it.\n */\n const unresolved = () => {\n if (stopped) {\n return;\n }\n const answer = {\n name: request.specifier,\n content: \"\",\n lint: false,\n unresolved: true,\n };\n plugins.recordImport(request, answer);\n ready.push({ id: request.id, ...answer });\n schedule();\n };\n let name: string;\n try {\n name = await host.resolve(request.specifier, request.importer);\n } catch {\n unresolved();\n return;\n }\n if (stopped) {\n return;\n }\n host.watch(name);\n let content: string;\n try {\n content = await host.read(name);\n } catch {\n unresolved();\n return;\n }\n if (stopped) {\n return;\n }\n const marked = lint(\n name,\n {\n id: request.importer,\n lint: lints.get(request.importer) ?? false,\n },\n request.specifier,\n );\n lints.set(name, (lints.get(name) ?? false) || marked);\n const library = marked\n ? undefined\n : stylesheetPackage(name, request.specifier, packages.get(request.importer));\n if (!marked && !packages.has(name)) {\n packages.set(name, library);\n }\n const answer = {\n name,\n content,\n uri: host.documentUri(name),\n sourceMapSource: host.sourceMapSource(name),\n lint: marked,\n ...(marked\n ? {}\n : {\n origin: {\n kind: \"library\",\n name: library,\n },\n }),\n };\n plugins.recordImport(request, answer);\n ready.push({ id: request.id, ...answer });\n schedule();\n };\n // Handle every rejection, including reads finishing after another read failed.\n void read().catch(fail);\n }\n };\n /** Sends the responses that are ready in the current event-loop turn together. */\n const schedule = () => {\n if (!queued) {\n queued = true;\n setTimeout(() => {\n queued = false;\n const responses = ready;\n ready = [];\n if (stopped) {\n return;\n }\n try {\n advance(loader.provideMany(responses));\n } catch (error) {\n fail(error);\n }\n });\n }\n };\n advance(initial);\n });\n\n return {\n loader: await plugins.initialize(loader),\n resources: completion?.resources ?? [],\n lintSources: completion?.lintSources ?? [],\n skipped: completion?.skipped ?? [],\n plugins,\n };\n}\n","import {\n completionDetail,\n type NativeAddedMarker,\n type NativeCandidateColor,\n type NativeCandidateCompletion,\n type NativeCandidateContext,\n type NativeEditorQuery,\n} from \"@stillwind/native\";\n\n/**\n * Shares previews, batch ordering, completion catalogs, and summaries for one captured design system.\n */\nexport class CandidateQueries {\n /** Native query pinned to the design system used for candidate validation and previews. */\n readonly #query: NativeEditorQuery;\n /** Successful and failed CSS previews keyed by preview kind, input role, and decoded candidate. */\n readonly #previews = new Map<string, string | null>();\n /** Shared completion arrays keyed by input role, decoded prefix, and snippet support. */\n readonly #completions = new Map<string, readonly NativeCandidateCompletion[]>();\n /** Added marker classes and null results keyed by input role and decoded candidate. */\n readonly #markers = new Map<string, NativeAddedMarker | null>();\n /** Summaries and empty results keyed by the full generated CSS, including preview annotations. */\n readonly #details = new Map<string, string | undefined>();\n\n /**\n * Creates empty caches for one captured design system.\n *\n * @param query - Native query whose theme, utility definitions, and compiler settings supply\n * all results. A different design system requires a new instance.\n */\n constructor(query: NativeEditorQuery) {\n this.#query = query;\n }\n\n /**\n * Caches standalone CSS for one candidate and its input role, including failed resolution.\n * Ordinary utilities use `&` as their subject. Previews omit enclosing source conditions.\n *\n * @param candidate - Decoded candidate text, including any variants supplied by the caller.\n * Option roles also accept the option text supported by their registry.\n * @param context - Input role used for validation and emission. Defaults to ordinary utilities.\n * @returns CSS for valid input, or null when the native query cannot emit it.\n * @throws If a matching ordinary utility definition has a malformed requirement.\n */\n preview(candidate: string, context: NativeCandidateContext = \"utility\"): string | null {\n const key = `${context}\\0${candidate}`;\n if (!this.#previews.has(key)) {\n this.#previews.set(key, this.#query.previewCandidate(candidate, context));\n }\n return this.#previews.get(key)!;\n }\n\n /**\n * Caches the marker class that one candidate adds to the element as written.\n *\n * @param candidate - Decoded candidate text, including enclosing variants.\n * @param context - Input role of the candidate. Only ordinary utilities add marker classes.\n * @returns The class and its origins, or null when the candidate adds no marker class.\n * Ref conditions of an enclosing style object are not checked.\n */\n marker(candidate: string, context: NativeCandidateContext = \"utility\"): NativeAddedMarker | null {\n const key = `${context}\\0${candidate}`;\n if (!this.#markers.has(key)) {\n this.#markers.set(key, this.#query.addedMarker(candidate, context));\n }\n return this.#markers.get(key)!;\n }\n\n /**\n * Caches the selectors, at-rule conditions, and declarations of a variant chain.\n *\n * @param candidate - Decoded variant chain, with or without a trailing colon.\n * @param context - Original input role whose constraints must allow the entire chain.\n * @returns CSS introduced by the variants, or null when the chain or role is unsupported.\n * Utility output and surrounding source conditions are omitted.\n */\n variant(candidate: string, context: NativeCandidateContext): string | null {\n const key = `variant\\0${context}\\0${candidate}`;\n if (!this.#previews.has(key)) {\n this.#previews.set(key, this.#query.previewVariant(candidate, context));\n }\n return this.#previews.get(key)!;\n }\n\n /**\n * Compares two ordinary utility candidates using the compiler's variant and utility order.\n *\n * @param left - Full decoded candidate spelling, including its variants.\n * @param right - Full decoded candidate spelling, including its variants.\n * @returns -1, 0, or 1, or null when either candidate cannot resolve.\n * @throws If a matching utility definition has a malformed requirement.\n */\n compare(left: string, right: string): number | null {\n return this.#query.compareCandidates(left, right);\n }\n\n /**\n * Prepares all spellings in `values` with one native request.\n * Repeated spellings are resolved once. The input array remains unchanged.\n *\n * @param values - Full decoded ordinary utility candidates, including their variants.\n * @returns A comparator whose numeric rank differences belong only to this batch.\n * It returns null for unresolved candidates or spellings absent from `values`.\n * An empty batch returns a comparator that always returns null.\n * @throws If a matching utility requirement is malformed or a native rank exceeds uint32.\n */\n order(values: readonly string[]): (left: string, right: string) => number | null {\n const unique = [...new Set(values)];\n if (unique.length === 0) {\n return () => null;\n }\n const ranks = this.#query.candidateRanks(unique);\n const positions = new Map(unique.map((value, index) => [value, ranks[index]]));\n return (left, right) => {\n const a = positions.get(left);\n const b = positions.get(right);\n return a == null || b == null ? null : a - b;\n };\n }\n\n /**\n * Caches unique labels in lexical order for one decoded partial candidate and its role.\n * Existing variant prefixes remain present, and variant labels end in `:`.\n * Suggestions do not append a variant already present in the prefix. An ordinary utility\n * prefix without variants, `!`, or `-` also receives marker class names, which may have no\n * preview.\n *\n * @param prefix - Decoded partial candidate, including any enclosing variants.\n * @param context - Input role that selects the candidate registry and permitted variants.\n * Defaults to ordinary utilities.\n * @param snippets - Whether to include empty brackets for arbitrary variant values and `name/`\n * labels for modifiable markers. Defaults to false.\n * @returns A shared readonly array of matching labels.\n * @throws If a matching ordinary utility definition has a malformed requirement.\n */\n complete(\n prefix: string,\n context: NativeCandidateContext = \"utility\",\n snippets = false,\n ): readonly NativeCandidateCompletion[] {\n const key = `${context}\\0${prefix}\\0${snippets}`;\n if (!this.#completions.has(key)) {\n this.#completions.set(key, this.#query.completeCandidate(prefix, context, snippets));\n }\n return this.#completions.get(key)!;\n }\n\n /**\n * Caches a short declaration or rule summary for selected completion CSS.\n *\n * @param css - Generated CSS to summarize, including optional preview annotations.\n * @returns A summary of at most 160 Unicode code points, or undefined when the CSS has\n * no declarations or descriptive rule wrappers.\n */\n detail(css: string): string | undefined {\n if (!this.#details.has(css)) {\n this.#details.set(css, completionDetail(css) ?? undefined);\n }\n return this.#details.get(css);\n }\n\n /**\n * Resolves a color utility's concrete color against this query's theme.\n *\n * @param candidate - Full decoded ordinary utility candidate, including variants and modifiers.\n * @returns sRGB red, green, blue, and effective alpha components in 0..1, or undefined when\n * the candidate is not a color utility or has no unambiguous concrete color.\n * @throws If a matching utility definition has a malformed requirement.\n */\n color(candidate: string): number[] | undefined {\n return this.#query.candidateColor(candidate) ?? undefined;\n }\n\n /**\n * Resolves a color utility's concrete colors in both color schemes against this query's theme.\n *\n * @param candidate - Full decoded ordinary utility candidate, including variants and modifiers.\n * @returns One color without a scheme, a light color followed by a dark color when\n * `light-dark()` selects different colors, or an empty array when the candidate is not a color\n * utility or has no unambiguous concrete color in either scheme.\n * @throws If a matching utility definition has a malformed requirement.\n */\n colors(candidate: string): NativeCandidateColor[] {\n return this.#query.candidateColors(candidate);\n }\n}\n\n/**\n * Splits at delimiters outside brackets, parentheses, single or double quotes, and escapes.\n * The operation preserves source spelling and does not validate nesting syntax.\n *\n * @param text - Candidate text whose backslashes escape the following UTF-16 code unit.\n * @param delimiter - One UTF-16 code unit, such as `:` or `/`, that is not a bracket,\n * parenthesis, quote, or backslash.\n * @returns Segments in their original order, including empty segments. Nothing is trimmed\n * or unescaped, and an empty input returns one empty segment.\n */\nexport function segments(text: string, delimiter: string): string[] {\n const result: string[] = [];\n let start = 0;\n let depth = 0;\n let quote = \"\";\n let escaped = false;\n for (let index = 0; index < text.length; index++) {\n const character = text[index];\n if (escaped) {\n escaped = false;\n continue;\n }\n if (character === \"\\\\\") {\n escaped = true;\n continue;\n }\n if (quote) {\n if (character === quote) {\n quote = \"\";\n }\n continue;\n }\n if (character === \"'\" || character === '\"') {\n quote = character;\n } else if (character === \"[\" || character === \"(\") {\n depth++;\n } else if (character === \"]\" || character === \")\") {\n depth--;\n } else if (character === delimiter && depth === 0) {\n result.push(text.slice(start, index));\n start = index + 1;\n }\n }\n result.push(text.slice(start));\n return result;\n}\n\n/**\n * Describes an added marker class and the definitions that make it a marker.\n *\n * @param marker - Marker class returned by {@link CandidateQueries.marker}.\n * @returns Markdown with the class name first, followed by one line for each kind of origin.\n */\nexport function markerDocumentation(marker: NativeAddedMarker): string {\n const code = (text: string) => {\n const ticks = \"`\".repeat(\n Math.max(0, ...[...text.matchAll(/`+/g)].map((match) => match[0].length)) + 1,\n );\n return `${ticks}${text.startsWith(\"`\") || text.endsWith(\"`\") ? ` ${text} ` : text}${ticks}`;\n };\n const definitions = marker.origins.flatMap((origin) =>\n origin.kind === \"utility\" || origin.kind === \"variant\"\n ? [`the ${code(origin.name!)} ${origin.kind}`]\n : [],\n );\n const kinds = new Set(marker.origins.map((origin) => origin.kind));\n return [\n `Adds the marker class ${code(marker.class)} to the element as written.`,\n kinds.has(\"declared\") ? \"A `@stillwind-marker` statement declares this class.\" : undefined,\n definitions.length ? `Selectors in ${list(definitions)} select this class.` : undefined,\n kinds.has(\"source\") ? \"Selectors in plugin CSS select this class.\" : undefined,\n ]\n .filter(Boolean)\n .join(\"\\n\\n\");\n}\n\n/**\n * Joins phrases into an English list.\n *\n * @param items - At least one phrase, in display order.\n * @returns The phrases separated by commas, with \"and\" before the last one.\n */\nfunction list(items: readonly string[]): string {\n return items.length < 3\n ? items.join(\" and \")\n : `${items.slice(0, -1).join(\", \")}, and ${items.at(-1)}`;\n}\n","import type { NativeEditorQuery } from \"@stillwind/native\";\n\nimport type { PluginRuntime } from \"../css/plugins/runtime.ts\";\nimport { CandidateQueries, segments } from \"./candidates.ts\";\n\n/**\n * A question about one project's design system, independent of any source file.\n */\nexport type DesignSystemRequest =\n | {\n /** Requests theme tokens. */\n kind: \"theme\";\n /** Token names without or with the leading `--`, where `*` matches any text. */\n targets: readonly string[];\n /** Keeps tokens with this origin. Omission keeps every token. */\n source?: DesignTokenSource;\n }\n | {\n /** Requests utilities, or variants, by exact candidate or pattern. */\n kind: \"utilities\" | \"variants\";\n /** Decoded candidates. A `*` outside brackets and parentheses makes a pattern. */\n targets: readonly string[];\n };\n\n/**\n * Origin of a token: the project's `@theme`, or a default that `@theme` can override.\n */\nexport type DesignTokenSource = \"project\" | \"default\";\n\n/**\n * An active theme token.\n */\nexport interface DesignToken {\n /** Complete custom property name, including the leading `--`. */\n name: string;\n /** CSS value as written, including references to other tokens. */\n value: string;\n /** Origin of the active definition. */\n source: DesignTokenSource;\n /** Whether utilities write the value of the token instead of a reference to it. */\n inline: boolean;\n}\n\n/**\n * One utility, variant, or marker class, with its CSS.\n */\nexport interface DesignCandidate {\n /** Decoded candidate. Variant names have no trailing colon. */\n name: string;\n /** Kind of input that the name selects. */\n kind: \"utility\" | \"variant\" | \"marker\";\n /** Whether the name resolves in this design system. */\n valid: boolean;\n /** Formatted CSS. It is empty for an invalid name and for a marker without CSS. */\n css: string;\n /** Closest valid spelling of an invalid name. Absent when no spelling is close enough. */\n suggestion?: string;\n /**\n * Canonical spelling of a valid exact candidate. Absent for a canonical name, for a name without\n * a replacement that produces the same CSS, and for a pattern match.\n */\n canonical?: string;\n}\n\n/**\n * The answer to one design-system request.\n */\nexport interface DesignSystemResult {\n /** Matching tokens in name order. */\n tokens: DesignToken[];\n /** Exact candidates in target order, then pattern matches in name order. */\n candidates: DesignCandidate[];\n /** Targets without a match. Exact candidates stay in candidates as invalid entries. */\n unmatched: string[];\n}\n\n/**\n * Everything a request reads from one loaded design system.\n */\nexport interface DesignSystemContext {\n /** Query over the loaded design system. */\n query: NativeEditorQuery;\n /** Plugins that add dynamic candidates. */\n plugins?: PluginRuntime;\n /** Preview comment settings. */\n annotations: Parameters<NativeEditorQuery[\"formatCss\"]>[1];\n}\n\n/**\n * Tests whether a target contains a wildcard outside brackets and parentheses.\n *\n * @param target - Decoded target text.\n * @returns Whether the target is a pattern.\n */\nfunction isPattern(target: string): boolean {\n return segments(target, \"*\").length > 1;\n}\n\n/**\n * Compiles a target whose `*` matches any text, including `/` and `:`.\n *\n * @param target - Decoded pattern.\n * @returns An anchored expression.\n */\nfunction patternExpression(target: string): RegExp {\n const parts = segments(target, \"*\").map((part) => part.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\"));\n return new RegExp(`^${parts.join(\".*\")}$`, \"s\");\n}\n\n/**\n * Answers a theme request.\n *\n * @param context - Loaded design system.\n * @param request - Theme request.\n * @returns Tokens that match, or every token for an empty target list, and unmatched targets.\n */\nfunction theme(\n context: DesignSystemContext,\n request: Extract<DesignSystemRequest, { kind: \"theme\" }>,\n): DesignSystemResult {\n const tokens = context.query\n .themeTokens()\n .map(({ name, value, fallback, inline }): DesignToken => ({\n name,\n value,\n source: fallback ? \"default\" : \"project\",\n inline,\n }))\n .filter(({ source }) => !request.source || source === request.source);\n const targets = request.targets.map((target) => ({\n target,\n expression: patternExpression(`--${target.replace(/^--/, \"\")}`),\n }));\n return {\n tokens: targets.length\n ? tokens.filter(({ name }) => targets.some(({ expression }) => expression.test(name)))\n : tokens,\n candidates: [],\n unmatched: targets\n .filter(({ expression }) => !tokens.some(({ name }) => expression.test(name)))\n .map(({ target }) => target),\n };\n}\n\n/**\n * Describes one candidate.\n *\n * @param query - Query that contains the definitions of the plugin candidates in the request.\n * @param candidates - Preview cache over that query.\n * @param annotations - Preview comment settings.\n * @param name - Decoded candidate, or a variant name without its trailing colon.\n * @param kind - Selects utility or variant resolution.\n * @returns The candidate, with a suggestion when it is invalid.\n * @throws If a matching utility definition is malformed.\n */\nfunction describe(\n query: NativeEditorQuery,\n candidates: CandidateQueries,\n annotations: DesignSystemContext[\"annotations\"],\n name: string,\n kind: \"utilities\" | \"variants\",\n): DesignCandidate {\n const css = kind === \"variants\" ? candidates.variant(name, \"utility\") : candidates.preview(name);\n const marker = kind === \"utilities\" ? candidates.marker(name) : null;\n if (css || marker) {\n return {\n name,\n kind: kind === \"variants\" ? \"variant\" : marker ? \"marker\" : \"utility\",\n valid: true,\n css: css ? query.formatCss(css, annotations) : \"\",\n };\n }\n // A variant resolves only with a utility, which a suggestion must not keep.\n const suggestion =\n kind === \"variants\"\n ? query.suggestCandidate(`${name}:flex`)?.replace(/:flex$/, \"\")\n : query.suggestCandidate(name);\n return {\n name,\n kind: kind === \"variants\" ? \"variant\" : \"utility\",\n valid: false,\n css: \"\",\n ...(suggestion ? { suggestion } : {}),\n };\n}\n\n/**\n * Returns the canonical spelling of a valid candidate under the lint options of the project.\n *\n * @param query - Query that contains the definitions of the plugin candidates in the request.\n * @param name - Decoded candidate, or a variant name without its trailing colon.\n * @param kind - Selects utility or variant spelling.\n * @returns The spelling, or undefined when `name` has no different canonical spelling.\n * @throws If a matching utility definition is malformed.\n */\nfunction canonicalSpelling(\n query: NativeEditorQuery,\n name: string,\n kind: \"utilities\" | \"variants\",\n): string | undefined {\n // A variant resolves only with a utility, which the spelling must not keep.\n return kind === \"variants\"\n ? query.canonicalCandidate(`${name}:flex`)?.replace(/:flex$/, \"\")\n : (query.canonicalCandidate(name) ?? undefined);\n}\n\n/**\n * Answers a utility or variant request.\n *\n * @param context - Loaded design system.\n * @param request - Candidate request. An empty target list means every listed name.\n * @returns Exact candidates, then the names that match patterns. Patterns read the completion\n * catalog, so they omit numeric and arbitrary values that exact candidates accept.\n * @throws If a plugin fails or a matching utility definition is malformed.\n */\nasync function candidates(\n context: DesignSystemContext,\n request: Extract<DesignSystemRequest, { kind: \"utilities\" | \"variants\" }>,\n): Promise<DesignSystemResult> {\n const { kind } = request;\n const catalog = new CandidateQueries(context.query);\n const targets = request.targets.length ? request.targets : [\"*\"];\n const exact = targets.filter((target) => !isPattern(target));\n const patterns: {\n target: string;\n names: string[];\n }[] = [];\n for (const target of targets.filter(isPattern)) {\n const expression = patternExpression(target);\n const prefix = segments(target, \"*\")[0];\n const labels = [\n ...catalog.complete(prefix).map(({ label }) => label),\n ...((await context.plugins?.catalog(prefix)) ?? []),\n ];\n const names = labels.flatMap((label) => {\n const variant = label.endsWith(\":\");\n const name = variant ? label.slice(0, -1) : label;\n return variant === (kind === \"variants\") && !name.endsWith(\"-\") && expression.test(name)\n ? [name]\n : [];\n });\n patterns.push({\n target,\n names: [...new Set(names)].sort(),\n });\n }\n\n // Each plugin load rebuilds the design system, so one load covers every name of the request.\n const dynamic = [...exact, ...patterns.flatMap(({ names }) => names)]\n .map((name) => (kind === \"variants\" ? `${name}:` : name))\n .filter((text) => context.query.dynamicCandidates(text).length > 0);\n const query =\n context.plugins && dynamic.length\n ? await context.plugins.query(dynamic.join(\" \"))\n : context.query;\n const queries = query === context.query ? catalog : new CandidateQueries(query);\n\n const seen = new Set(exact);\n const listed: DesignCandidate[] = [];\n const unmatched: string[] = [];\n for (const { target, names } of patterns) {\n let matched = false;\n for (const name of names) {\n if (seen.has(name)) {\n matched = true;\n continue;\n }\n const candidate = describe(query, queries, context.annotations, name, kind);\n if (candidate.valid) {\n matched = true;\n seen.add(name);\n listed.push(candidate);\n }\n }\n if (!matched) {\n unmatched.push(target);\n }\n }\n const named = exact.map((name) => {\n const candidate = describe(query, queries, context.annotations, name, kind);\n const canonical = candidate.valid ? canonicalSpelling(query, name, kind) : undefined;\n return canonical ? { ...candidate, canonical } : candidate;\n });\n return {\n tokens: [],\n candidates: [...named, ...listed],\n unmatched,\n };\n}\n\n/**\n * Answers a question about a loaded design system.\n *\n * @param context - Loaded design system.\n * @param request - Theme, utility, or variant request.\n * @returns The answer. Invalid names and unmatched targets are data.\n * @throws If a plugin fails or a matching utility definition is malformed.\n */\nexport function queryDesignSystem(\n context: DesignSystemContext,\n request: DesignSystemRequest,\n): Promise<DesignSystemResult> {\n return request.kind === \"theme\"\n ? Promise.resolve(theme(context, request))\n : candidates(context, request);\n}\n","import type {\n NativeAssetRecord,\n NativeModuleSummary,\n NativeProjectSession,\n} from \"@stillwind/native\";\nimport { checkerEnvironment, prepareSource, type PreparedSource } from \"@stillwind/projection\";\n\nimport type { SemanticInputs, TypeFactSource, TypeFactsBackend } from \"../semantics/backend.ts\";\nimport { loadSource, type CompilerHost } from \"./host.ts\";\n\n/** A prepared source, its scan results, and the inputs needed by the checker. */\ninterface CapturedSource {\n /** Owned copy of the prepared source. Callers must not mutate it. */\n source: PreparedSource;\n /** Scan results for the same source text. */\n summary: NativeModuleSummary;\n /** Resolved imports whose ranges use original UTF-8 byte offsets. */\n resolutions: NonNullable<TypeFactSource[\"resolutions\"]>;\n /** Whether the host has tried to resolve every import in this source. */\n linked: boolean;\n /** Created on the first semantic query. Framework dependencies may fail to load. */\n checker?: TypeFactSource;\n}\n\n/** Keeps prepared sources and checker inputs between analyses of one project. */\nexport class CompilationProject {\n /** Sources keyed by normalized resolver ID. Windows paths ignore case. */\n readonly #sources = new Map<string, CapturedSource>();\n /** Import answers for the currently installed checker inputs. */\n #resolutions?: ReadonlyMap<string, ReadonlyMap<string, string>>;\n /** Advances on invalidation so pending loads cannot publish old sources. */\n #revision = 0;\n /** Advances when sources or import links change so checker inputs are installed again. */\n #generation = 0;\n /** Last backend and inputs installed by this project. */\n #installed?: {\n backend: TypeFactsBackend;\n generation: number;\n inputs?: SemanticInputs;\n sources: readonly TypeFactSource[];\n };\n\n /** Revision that a pending load must still match before it stores a source. */\n get revision(): number {\n return this.#revision;\n }\n\n /**\n * Finds a source prepared since its last invalidation.\n *\n * @param id - Full resolver ID. Windows path spelling may differ in case or slashes.\n * @returns The shared source, or undefined when it has not been prepared. Do not mutate it.\n */\n source(id: string): PreparedSource | undefined {\n return this.#sources.get(sourceKey(id))?.source;\n }\n\n /** Returns the normalized identities of the prepared sources, as {@link sourceKey} defines them. */\n sourceKeys(): string[] {\n return [...this.#sources.keys()];\n }\n\n /** Returns the prepared documents' original text so plugins can find candidates together. */\n texts(): string[] {\n return [...this.#sources.values()].map((record) => record.source.document.code);\n }\n\n /**\n * Finds the scan results for a prepared source.\n *\n * @param source - Source whose text has not changed since preparation.\n * @returns Shared scan results, or undefined when the source is not retained. Do not mutate them.\n */\n summary(source: PreparedSource): NativeModuleSummary | undefined {\n return this.#sources.get(sourceKey(source.resolverId))?.summary;\n }\n\n /**\n * Stores a source and its successful scan results, copying the source before retaining it.\n *\n * @param source - Source passed to the scanner.\n * @param summary - Successful scan results for that source. Do not mutate them after this call.\n * @param revision - Revision captured before loading. Defaults to the current revision.\n * Old revisions and sources already stored under the same ID have no effect.\n */\n retain(source: PreparedSource, summary: NativeModuleSummary, revision = this.#revision): void {\n if (revision !== this.#revision || this.#sources.has(sourceKey(source.resolverId))) {\n return;\n }\n source = structuredClone(source);\n this.#sources.set(sourceKey(source.resolverId), {\n source,\n summary,\n linked: false,\n resolutions: [],\n });\n this.#changed();\n }\n\n /**\n * Loads and scans targets together, then resolves their imports through the host.\n * Analysis retries failed loads and scans so it can report each target's own error.\n *\n * @param ids - Full resolver IDs of the targets to prepare.\n * @param host - Host used by later analysis of these targets.\n * @param session - Initialized native session that will analyze the prepared sources.\n * @returns Completion of preparation. Invalidation stops old work from storing results.\n * @throws If host import resolution fails. Source loading and scan failures are left for analysis.\n */\n async prepare(\n ids: readonly string[],\n host: CompilerHost,\n session: NativeProjectSession,\n ): Promise<void> {\n const revision = this.#revision;\n await Promise.allSettled(ids.map((id) => this.#load(id, host, session, revision)));\n if (revision !== this.#revision) {\n return;\n }\n for (const record of this.#sources.values()) {\n const { source, summary } = record;\n if (record.linked) {\n continue;\n }\n const resolutions = await Promise.all(\n summary.moduleSpecifiers.map(async (specifier) => {\n const resolved = await host.resolve(specifier.source, source.resolverId, {\n skipSelf: true,\n });\n if (!resolved || resolved.external) {\n return undefined;\n }\n await this.#load(resolved.id, host, session, revision).catch(() => {});\n return {\n id: this.source(resolved.id)?.resolverId ?? resolved.id,\n start: specifier.start,\n end: specifier.end,\n };\n }),\n );\n if (revision !== this.#revision) {\n return;\n }\n record.linked = true;\n this.#setResolutions(\n record,\n resolutions.filter((value) => value !== undefined),\n );\n }\n }\n\n /**\n * Removes changed sources and clears all import links and cached resolution answers.\n *\n * @param ids - One changed resolver ID or several IDs. Omission removes every source.\n * Advances the revision so pending loads cannot restore the removed sources.\n */\n invalidate(ids?: string | Iterable<string>): void {\n this.#revision++;\n if (ids === undefined) {\n this.#sources.clear();\n } else {\n for (const id of typeof ids === \"string\" ? [ids] : ids) {\n this.#sources.delete(sourceKey(id));\n }\n }\n for (const record of this.#sources.values()) {\n record.resolutions = [];\n if (record.checker) {\n record.checker.resolutions = record.resolutions;\n }\n record.linked = false;\n }\n this.#changed();\n }\n\n /**\n * Installs prepared checker inputs when their sources, import links, or supplied files change.\n *\n * @param backend - Backend used by later queries. Receives inputs if it supports setProjectSources.\n * @param sources - Sources requested by the current analysis, with any known import resolutions.\n * @param inputs - File overlays and ambient declarations for these sources.\n * @returns Shared checker sources in the requested order. Do not mutate them.\n * @throws If a requested source's checker environment or backend installation fails.\n * Other sources with unavailable framework dependencies are left out of the installed inputs.\n */\n install(\n backend: TypeFactsBackend,\n sources: readonly TypeFactSource[],\n inputs?: SemanticInputs,\n ): TypeFactSource[] {\n const requested = sources.map((source) => {\n const record = this.#sources.get(sourceKey(source.resolverId));\n if (!record) {\n return source;\n }\n const checker = this.#checkerSource(record);\n if (!record.linked) {\n const resolutions = new Map(\n record.resolutions.map((item) => [`${item.start}:${item.end}`, item]),\n );\n for (const item of source.resolutions ?? []) {\n const target = this.source(item.id);\n if (target) {\n resolutions.set(`${item.start}:${item.end}`, { ...item, id: target.resolverId });\n }\n }\n this.#setResolutions(record, [...resolutions.values()]);\n }\n return checker;\n });\n const all = new Map<string, TypeFactSource>();\n for (const [id, record] of this.#sources) {\n try {\n all.set(id, this.#checkerSource(record));\n } catch {\n // Optional inventory entries must not require a framework checker environment for other targets.\n }\n }\n for (const source of requested) {\n all.set(sourceKey(source.resolverId), source);\n }\n if (\n this.#installed?.backend !== backend ||\n this.#installed.generation !== this.#generation ||\n !sameFiles(this.#installed.inputs?.overlayFiles, inputs?.overlayFiles) ||\n !sameFiles(this.#installed.inputs?.ambientDeclarations, inputs?.ambientDeclarations)\n ) {\n const inventory = [...all.values()].sort((a, b) => {\n const left = sourceKey(a.resolverId);\n const right = sourceKey(b.resolverId);\n return left < right ? -1 : left > right ? 1 : 0;\n });\n backend.setProjectSources?.(inventory, this.assets(), inputs);\n this.#installed = { backend, generation: this.#generation, inputs, sources: inventory };\n this.#resolutions = undefined;\n }\n return requested;\n }\n\n /**\n * @returns Declarations grouped by module ID. The arrays belong to the retained scans.\n */\n assets(): ReadonlyMap<string, readonly NativeAssetRecord[]> {\n return new Map(\n [...this.#sources.values()].map(({ source, summary }) => [source.moduleId, summary.assets]),\n );\n }\n\n /**\n * Resolves imports and caches the answers until checker inputs change.\n *\n * @param backend - Backend that resolves imports. Backends without setProjectSources query only sources.\n * @param sources - Sources requested by the current analysis, with any known import resolutions.\n * @param inputs - File overlays and ambient declarations for this analysis.\n * @returns Shared maps from resolver ID to authored specifier and resolved ID. Do not mutate them.\n * @throws If checker input preparation, installation, or import resolution fails.\n */\n async resolve(\n backend: TypeFactsBackend,\n sources: readonly TypeFactSource[],\n inputs?: SemanticInputs,\n ): Promise<ReadonlyMap<string, ReadonlyMap<string, string>>> {\n if (!backend.setProjectSources) {\n return backend.resolveModules(sources, this.assets(), inputs);\n }\n this.install(backend, sources, inputs);\n if (!this.#resolutions) {\n const generation = this.#generation;\n const resolutions = await backend.resolveModules(\n this.#installed!.sources,\n this.assets(),\n inputs,\n );\n if (generation === this.#generation) {\n this.#resolutions = resolutions;\n }\n return resolutions;\n }\n return this.#resolutions;\n }\n\n /**\n * Loads and scans one supported source unless it is already prepared.\n *\n * @param id - Full resolver ID.\n * @param host - Source loader and format metadata for this project.\n * @param session - Initialized session used to scan the source.\n * @param revision - Revision captured before loading. A newer revision discards this work.\n * @returns Completion of loading and scanning. Failed scans are not stored.\n * @throws If loading, projection, or native transport fails.\n */\n async #load(\n id: string,\n host: CompilerHost,\n session: NativeProjectSession,\n revision: number,\n ): Promise<void> {\n if (revision !== this.#revision || this.source(id) || host.supports?.(id) === false) {\n return;\n }\n const input = await loadSource(host, id);\n const source = \"kind\" in input ? input : await prepareSource(input);\n if (revision !== this.#revision) {\n return;\n }\n const scan = session.scanSource(source);\n if (scan.kind !== \"failed\") {\n this.retain(source, scan.summary, revision);\n }\n }\n\n /**\n * Creates a source's checker inputs once, loading any required framework declarations.\n *\n * @param record - Retained source and scan results to update.\n * @returns Shared checker inputs. Later import updates also update this object.\n * @throws If the framework checker environment cannot be prepared.\n */\n #checkerSource(record: CapturedSource): TypeFactSource {\n return (record.checker ??= {\n ...record.source,\n ...checkerEnvironment(record.source),\n probes: record.summary.typeProbes,\n checkerSpans: record.summary.checkerSpans,\n checkerBindings: record.summary.checkerBindings,\n resolutions: record.resolutions,\n });\n }\n\n /**\n * Replaces import links and clears cached answers when a target or range changes.\n *\n * @param record - Retained source whose links are being replaced.\n * @param resolutions - Resolved targets with original UTF-8 byte ranges.\n */\n #setResolutions(record: CapturedSource, resolutions: CapturedSource[\"resolutions\"]): void {\n if (\n record.resolutions.length === resolutions.length &&\n record.resolutions.every(\n (item, index) =>\n item.id === resolutions[index].id &&\n item.start === resolutions[index].start &&\n item.end === resolutions[index].end,\n )\n ) {\n return;\n }\n record.resolutions = resolutions;\n if (record.checker) {\n record.checker.resolutions = resolutions;\n }\n this.#changed();\n }\n\n /**\n * Clears import answers and marks checker inputs for installation on the next query.\n */\n #changed(): void {\n this.#resolutions = undefined;\n this.#generation++;\n }\n}\n\n/**\n * Normalizes a resolver ID for map lookups.\n *\n * @param id - Resolver ID, with either slash style for Windows paths.\n * @returns Forward slashes and, for absolute Windows paths, lowercase text.\n */\nexport function sourceKey(id: string): string {\n const normalized = id.replaceAll(\"\\\\\", \"/\");\n return /^[a-z]:\\//i.test(normalized) ? normalized.toLowerCase() : normalized;\n}\n\n/**\n * Compares supplied file contents without depending on map order.\n *\n * @param a - First map of filenames to text. Omission means no files.\n * @param b - Second map, interpreted in the same way.\n * @returns Whether both maps contain the same filenames and text.\n */\nfunction sameFiles(a?: ReadonlyMap<string, string>, b?: ReadonlyMap<string, string>): boolean {\n return (\n (a?.size ?? 0) === (b?.size ?? 0) && [...(a ?? [])].every(([id, text]) => b?.get(id) === text)\n );\n}\n","import { fingerprint } from \"@stillwind/native\";\n\n/**\n * A replacement in the original document, using half-open UTF-16 offsets.\n */\nexport interface EditorEdit {\n /** Inclusive UTF-16 offset in the original document. */\n start: number;\n /** Exclusive UTF-16 offset in the original document. */\n end: number;\n /** Source spelling inserted at the range, including escapes required by its source context. */\n newText: string;\n}\n\n/**\n * Completion text replaces the entire candidate at the supplied original range.\n */\nexport interface EditorCompletion extends EditorEdit {\n /** Directive names use the keyword category. Other inputs use candidate categories. */\n keyword?: boolean;\n /** True for a variant, including CSS variant labels without a trailing colon. */\n variant?: boolean;\n /** True for a label that adds a marker class or starts the modifier of a modifiable marker. */\n marker?: boolean;\n /** Static description for a CSS directive or plugin path. CSS summaries load on resolve. */\n detail?: string;\n /** Replacement encoded as an LSP snippet when the requesting client supports snippets. */\n snippet?: string;\n /** Requests another completion after the client inserts this item. */\n retrigger?: boolean;\n /** Completion category for host-resolved plugin names, files, and directories. */\n category?: \"module\" | \"file\" | \"directory\";\n /** Lexical priority key supplied by the semantic catalog. Omission sorts by label. */\n sortText?: string;\n /** Visible completion text; surrounding group variants are omitted. */\n label: string;\n /** Full candidate used for lazy CSS resolution, including surrounding group variants. */\n candidate: string;\n /** Original UTF-16 input identity used for completion resolution. */\n input: number;\n /** Fingerprint of the captured query inputs. Resolve requires this exact value. */\n snapshot: string;\n}\n\n/**\n * A concrete sRGB color at an original candidate range.\n */\nexport interface EditorColor {\n /** Inclusive UTF-16 offset of the authored candidate. */\n start: number;\n /** Exclusive UTF-16 offset of the authored candidate. */\n end: number;\n /** Red component in the inclusive range 0..1. */\n red: number;\n /** Green component in the inclusive range 0..1. */\n green: number;\n /** Blue component in the inclusive range 0..1. */\n blue: number;\n /** Effective opacity after utility modifiers, in the inclusive range 0..1. */\n alpha: number;\n /**\n * Color scheme whose `light-dark()` arguments produce this color. Absent when both schemes\n * produce it. A light color is followed by a dark color with the same range, and neither\n * accepts a color presentation.\n */\n scheme?: \"light\" | \"dark\";\n}\n\n/**\n * Requests address original document UTF-16 offsets, including incomplete candidate text.\n */\nexport type EditorRequest =\n | {\n /** Requests the original definition of a CSS variable or theme reference. */\n kind: \"definition\";\n /** Original UTF-16 cursor offset within the reference. */\n offset: number;\n }\n | {\n /** Requests plugin module links in the original stylesheet. */\n kind: \"links\";\n }\n | {\n /** Requests CSS or documentation for a candidate, expression, or CSS directive. */\n kind: \"hover\";\n /** Original UTF-16 cursor offset at the input to describe. */\n offset: number;\n }\n | {\n /** Requests CSS for every style call, declaration, and use in the source. */\n kind: \"previews\";\n }\n | {\n /** Requests matching candidates and variant prefixes for an insertion point. */\n kind: \"completion\";\n /** Includes CSS registry directives. Defaults to false and does not affect compilation. */\n registryDirectives?: boolean;\n /** Includes placeholders for clients that support completion snippets. */\n snippets?: boolean;\n /** Original UTF-16 insertion point; text before this point determines the prefix. */\n offset: number;\n }\n | {\n /** Requests CSS or documentation for a completion from the same captured snapshot. */\n kind: \"resolve\";\n /** CSS discovery setting used for the original completion. A change makes it stale. */\n registryDirectives?: boolean;\n /** Snippet setting captured when completion was requested. */\n snippets?: boolean;\n /** Full candidate or CSS label returned by completion. */\n candidate: string;\n /** Original UTF-16 boundary returned as `EditorCompletion.input`. */\n input: number;\n /** Captured fingerprint returned by completion; a mismatch omits hover output. */\n snapshot: string;\n }\n | {\n /** Requests concrete colors for recognized utility candidates in the source. */\n kind: \"colors\";\n }\n | {\n /** Requests each report's first fix action for this source revision, with enabled sorting. */\n kind: \"fixes\";\n }\n | {\n /** Requests configured sorting independently of lint severity. */\n kind: \"sort\";\n /** Half-open original UTF-16 ranges that sorting must leave untouched. */\n protectedRanges?: readonly {\n /** Inclusive original UTF-16 offset of the protected text. */\n start: number;\n /** Exclusive original UTF-16 offset of the protected text. */\n end: number;\n }[];\n }\n | {\n /** Requests a replacement candidate for a range returned by the colors query. */\n kind: \"colorPresentation\";\n /** Inclusive original UTF-16 offset returned by the colors query. */\n start: number;\n /** Exclusive original UTF-16 offset returned by the colors query. */\n end: number;\n /** Desired sRGB components and effective opacity, each in 0..1. */\n color: Pick<EditorColor, \"red\" | \"green\" | \"blue\" | \"alpha\">;\n };\n\n/**\n * Editor data belongs to the exact source fingerprint in revision. Absent fields mean no answer.\n */\nexport interface EditorResult {\n /** Original CSS definitions with zero-based line and UTF-16 column coordinates. */\n definitions?: {\n uri: string;\n startLine: number;\n startColumn: number;\n endLine: number;\n endColumn: number;\n }[];\n /** Plugin paths at half-open original UTF-16 ranges. An absent target means unresolved or configured-only. */\n links?: {\n start: number;\n end: number;\n target?: string;\n }[];\n /** Fingerprint of the original source text used to compute every range and edit. */\n revision: string;\n /** Formatted CSS at a half-open original UTF-16 range. Generated element subjects use `&`.\n * Lazy completion resolution uses the sentinel range `[0, 0)`.\n */\n hover?: {\n /** Inclusive original UTF-16 boundary, or zero for completion resolution. */\n start: number;\n /** Exclusive original UTF-16 boundary, or zero for completion resolution. */\n end: number;\n /** Generated CSS or an active theme declaration. Empty for documentation-only hovers. */\n css: string;\n /** Short CSS summary or plugin description for the selected completion. */\n detail?: string;\n /** Markdown for CSS directives, output slots, theme references, plugin paths, or marker classes. */\n documentation?: string;\n /** Authored runtime key expressions, deduplicated in dependency traversal order.\n * Absent when the preview has no runtime key expression to explain.\n */\n runtimeNames?: string[];\n };\n /** Formatted CSS at half-open original UTF-16 ranges, in ascending start order. Literal inputs\n * and occurrences inside another listed occurrence are omitted.\n */\n previews?: {\n /** Inclusive original UTF-16 boundary. */\n start: number;\n /** Exclusive original UTF-16 boundary. */\n end: number;\n /** Generated CSS with the required styles and global definitions. It can be empty. */\n css: string;\n /** False when the occurrence or a style that it requires failed to generate CSS. */\n valid: boolean;\n /** Authored runtime key expressions. Absent when the preview has none to explain. */\n runtimeNames?: string[];\n }[];\n /** Prefix-matching candidates with their full replacement ranges. CSS loads on resolve. */\n completions?: EditorCompletion[];\n /** Concrete colors resolved against the active design system. */\n colors?: EditorColor[];\n /** Nonoverlapping replacements in ascending original offset order. */\n edits?: EditorEdit[];\n}\n\n/**\n * Starts an editor answer tied to the original source text.\n *\n * @param source - Complete original document text.\n * @returns An empty answer with the fingerprint required for its ranges and edits.\n */\nexport function editorResult(source: string): EditorResult {\n return {\n revision: fingerprint(source),\n };\n}\n","import type { NativeAssetRecord } from \"@stillwind/native\";\nimport type { PreparedSource } from \"@stillwind/projection\";\nimport ts from \"typescript-6\";\n\n/** Syntax categories used to group direct style inputs. */\nexport type InputOrder =\n | {\n /** Prevents inputs on either side from exchanging positions. */\n kind: \"barrier\";\n }\n | {\n /** Groups a ref marker with projections of the same declaration. */\n kind: \"ref\";\n /** Opaque declaration identity. Aliases of the same ref must share this value. */\n identity: string;\n /** True for a direct projection call, false for a marker attachment. */\n projection: boolean;\n }\n | {\n /** Identifies composed styles whose relative order must be retained. */\n kind: \"bases\";\n }\n | {\n /** Identifies utility text and named variant groups. */\n kind: \"utilities\";\n }\n | {\n /** Identifies authored custom-property inputs. */\n kind: \"customProperties\";\n };\n\n/** Original source bounds and syntax category of one input. */\nexport interface InputOrderItem {\n /** Inclusive UTF-16 position in the original document. */\n start: number;\n /** Exclusive UTF-16 position in the original document. */\n end: number;\n /** A syntax category, or a barrier that no input can cross. */\n order: InputOrder;\n}\n\n/**\n * Groups `items` by syntax category without crossing barriers.\n *\n * Ref groups retain their first appearance order, and each marker precedes its\n * projections. Bases, utilities, and custom properties follow in that order. Each\n * category retains its input order.\n *\n * @param items - Inputs in their current order, with a distinct object for each occurrence.\n * @param allows - Optional predicate that approves the original range covering each adjacent\n * exchange. Rejected exchanges can prevent the result from reaching the full category order.\n * @returns A new array of the original objects. The input array and its objects remain unchanged.\n */\nexport function orderInputs<T extends InputOrderItem>(\n items: readonly T[],\n allows?: (start: number, end: number) => boolean,\n): T[] {\n const sorted: T[] = [];\n let start = 0;\n for (let end = 0; end <= items.length; end++) {\n if (end === items.length || items[end].order.kind === \"barrier\") {\n sorted.push(...orderRun(items.slice(start, end), allows));\n if (end < items.length) {\n sorted.push(items[end]);\n }\n start = end + 1;\n }\n }\n return sorted;\n}\n\n/**\n * Computes the category order for one run and applies any permitted adjacent exchanges.\n *\n * @param items - A run without barriers, with a distinct object for each occurrence.\n * @param allows - Optional predicate over the original range covering two adjacent inputs.\n * @returns The same input objects in a new array. Neither the input array nor its objects change.\n */\nfunction orderRun<T extends InputOrderItem>(\n items: readonly T[],\n allows?: (start: number, end: number) => boolean,\n): T[] {\n const refs = new Map<\n string,\n {\n /** Marker occurrences in their original relative order. */\n markers: T[];\n /** Projection occurrences in their original relative order. */\n projections: T[];\n }\n >();\n const groups: Record<\"bases\" | \"utilities\" | \"customProperties\", T[]> = {\n bases: [],\n utilities: [],\n customProperties: [],\n };\n for (const item of items) {\n if (item.order.kind === \"ref\") {\n let group = refs.get(item.order.identity);\n if (!group) {\n group = { markers: [], projections: [] };\n refs.set(item.order.identity, group);\n }\n group[item.order.projection ? \"projections\" : \"markers\"].push(item);\n } else if (item.order.kind !== \"barrier\") {\n groups[item.order.kind].push(item);\n }\n }\n const ordered = [\n ...[...refs.values()].flatMap(({ markers, projections }) => [...markers, ...projections]),\n ...groups.bases,\n ...groups.utilities,\n ...groups.customProperties,\n ];\n if (!allows) {\n return ordered;\n }\n const positions = new Map(ordered.map((item, index) => [item, index]));\n const sorted = [...items];\n for (let position = 1; position < sorted.length; position++) {\n for (let cursor = position; cursor > 0; cursor--) {\n const left = sorted[cursor - 1];\n const right = sorted[cursor];\n if (\n positions.get(left)! <= positions.get(right)! ||\n !allows(Math.min(left.start, right.start), Math.max(left.end, right.end))\n ) {\n break;\n }\n [sorted[cursor - 1], sorted[cursor]] = [right, left];\n }\n }\n return sorted;\n}\n\n/**\n * Classifies direct style input syntax and resolved declarations for grouping.\n *\n * @param source - Fixed source whose AST contains node.\n * @param node - Input or property to classify.\n * @param resolveAsset - Resolves native declaration identities and stable aliases for this source graph.\n * @returns An input category, or a barrier when the input cannot move safely.\n */\nexport function classifyInput(\n source: PreparedSource,\n node: ts.Node,\n resolveAsset: (source: PreparedSource, node: ts.Node) => NativeAssetRecord | undefined,\n): InputOrder {\n if (ts.isPropertyAssignment(node) || ts.isShorthandPropertyAssignment(node)) {\n if (ts.isComputedPropertyName(node.name)) {\n return {\n kind: \"barrier\",\n };\n }\n const name = ts.isStringLiteralLike(node.name) ? node.name.text : node.name.getText();\n if (name.startsWith(\"--\")) {\n return {\n kind: \"customProperties\",\n };\n }\n return name === \"\" || name.endsWith(\":\") || name === \"class\"\n ? {\n kind: \"utilities\",\n }\n : {\n kind: \"barrier\",\n };\n }\n if (ts.isStringLiteralLike(node) || ts.isTemplateExpression(node)) {\n return {\n kind: \"utilities\",\n };\n }\n const asset = resolveAsset(source, node);\n if (asset?.identity.kind === \"style\") {\n return {\n kind: \"bases\",\n };\n }\n if (asset?.identity.kind === \"ref\") {\n return {\n kind: \"ref\",\n identity: JSON.stringify(asset.identity),\n projection: false,\n };\n }\n if (\n ts.isCallExpression(node) &&\n ts.isPropertyAccessExpression(node.expression) &&\n [\"asAnchor\", \"asContainer\", \"positionAnchor\"].includes(node.expression.name.text)\n ) {\n const ref = resolveAsset(source, node.expression.expression);\n if (ref?.identity.kind === \"ref\") {\n return {\n kind: \"ref\",\n identity: JSON.stringify(ref.identity),\n projection: true,\n };\n }\n }\n if (\n ts.isParenthesizedExpression(node) ||\n ts.isAsExpression(node) ||\n ts.isSatisfiesExpression(node) ||\n ts.isNonNullExpression(node)\n ) {\n return classifyInput(source, node.expression, resolveAsset);\n }\n if (ts.isArrayLiteralExpression(node) || ts.isObjectLiteralExpression(node)) {\n const elements = ts.isArrayLiteralExpression(node) ? node.elements : node.properties;\n const orders = elements.map((element) => classifyInput(source, element, resolveAsset));\n const first = orders[0];\n if (\n first &&\n first.kind !== \"barrier\" &&\n first.kind !== \"ref\" &&\n orders.every((order) => order.kind === first.kind)\n ) {\n return first;\n }\n }\n return {\n kind: \"barrier\",\n };\n}\n","import type { UtilitySortOptions } from \"@stillwind/config\";\nimport type { PreparedSource } from \"@stillwind/projection\";\nimport ts from \"typescript-6\";\n\nimport type { CandidateQueries } from \"./candidates.ts\";\nimport type { EditorEdit } from \"./request.ts\";\nimport type { SourceIndex } from \"./source/inputs.ts\";\nimport type { UtilityLiteral } from \"./source/literal.ts\";\nimport { orderInputs, type InputOrderItem } from \"./source/order.ts\";\n\n/**\n * Composes existing edits with utility sorting and grouping of direct style inputs.\n * Literal sorting applies only to ordinary utilities. Containers are processed from the\n * smallest to the largest so an outer replacement includes edits to nested inputs.\n * Unknown syntax, ambiguous comments, and text that cannot map exactly delimit grouping.\n *\n * @param source - The same prepared source object stored in `index`, with an unchanged buffer.\n * @param index - Index built from that source graph before any edits are applied.\n * @param candidates - Candidate query for the design system that compiled the source.\n * @param options - Sorting targets. False returns only the seed edits in source order.\n * @param seed - Nonoverlapping replacements in original UTF-16 coordinates. Inside a sortable\n * literal, each edit must replace a complete utility token. Edits inside grouped containers must\n * stay within one input. Replacement text must contain any JS escapes needed at its range.\n * @param allows - Optional predicate that approves a whole literal's content range or the\n * range covering an adjacent input exchange. Every range uses original UTF-16 coordinates.\n * @returns Edits in ascending original offset order. The source and seed array remain unchanged.\n * @throws If a matching utility definition has a malformed requirement or native ranking fails.\n */\nexport function sortSource(\n source: PreparedSource,\n index: SourceIndex,\n candidates: CandidateQueries,\n options: UtilitySortOptions | false,\n seed: readonly EditorEdit[] = [],\n allows?: (start: number, end: number) => boolean,\n): EditorEdit[] {\n if (options === false) {\n return seed.toSorted((a, b) => a.start - b.start);\n }\n\n let edits = [...seed];\n const permits = allows ?? (() => true);\n\n if (options.stringLiterals !== false) {\n const literals = index.literals\n .filter(\n (literal) =>\n literal.source === source &&\n literal.context === \"utility\" &&\n permits(literal.boundaries[0], literal.boundaries.at(-1)!),\n )\n .map((literal) => {\n const matches = [...literal.text.matchAll(/\\S+/gu)];\n const original = matches.map((match) => match[0]);\n const spellings = matches.map((match) => {\n const start = literal.boundaries[match.index];\n const end = literal.boundaries[match.index + match[0].length];\n const edit = seed.find((edit) => edit.start === start && edit.end === end);\n return {\n token: edit ? decodeReplacement(edit.newText, literal) : match[0],\n text: edit?.newText ?? source.document.code.slice(start, end),\n };\n });\n const tokens = spellings.map((spelling) => spelling.token);\n return {\n literal,\n original,\n tokens,\n matches,\n spellings,\n };\n });\n const compare = candidates.order(\n literals.flatMap(({ literal, tokens }) => tokens.map((token) => literal.prefix + token)),\n );\n for (const { literal, original, tokens, matches, spellings } of literals) {\n const start = literal.boundaries[0];\n const end = literal.boundaries.at(-1)!;\n const sorted = sortRuns(tokens, (a, b) => compare(literal.prefix + a, literal.prefix + b));\n if (sorted.every((token, position) => token === original[position])) {\n continue;\n }\n\n let cursor = start;\n let newText = \"\";\n const queues = new Map<\n string,\n {\n /** Authored or seeded spellings of duplicate candidates, in occurrence order. */\n texts: string[];\n /** Zero-based index of the next spelling to consume. */\n position: number;\n }\n >();\n for (const spelling of spellings) {\n let queue = queues.get(spelling.token);\n if (!queue) {\n queue = {\n texts: [],\n position: 0,\n };\n queues.set(spelling.token, queue);\n }\n queue.texts.push(spelling.text);\n }\n for (const [position, match] of matches.entries()) {\n const tokenStart = literal.boundaries[match.index];\n const tokenEnd = literal.boundaries[match.index + match[0].length];\n const queue = queues.get(sorted[position])!;\n newText += source.document.code.slice(cursor, tokenStart) + queue.texts[queue.position++];\n cursor = tokenEnd;\n }\n newText += source.document.code.slice(cursor, end);\n edits = absorb(edits, {\n start,\n end,\n newText,\n });\n }\n }\n\n if (options.arrays !== false) {\n const containers = index.containers\n .filter((container) => container.source === source)\n .sort((a, b) => a.node.end - a.node.pos - (b.node.end - b.node.pos));\n for (const container of containers) {\n const elements = ts.isArrayLiteralExpression(container.node)\n ? container.node.elements\n : ts.isCallExpression(container.node)\n ? container.node.arguments\n : container.node.properties;\n const items = [...elements].map((node) => {\n const range = index.range(source, node);\n const offset = range ? range[0] - node.getStart() : 0;\n const start = node.getFullStart() + offset;\n const end = range?.[1] ?? 0;\n const text = range\n ? applyEdits(\n source.document.code.slice(start, end),\n edits\n .filter((edit) => edit.start >= start && edit.end <= end)\n .map((edit) => ({\n ...edit,\n start: edit.start - start,\n end: edit.end - start,\n })),\n )\n : \"\";\n const order: InputOrderItem[\"order\"] = index.inputOrder(source, node);\n const ambiguousComment = /^[^\\r\\n]*(?:\\/\\/|\\/\\*)/.test(text) && node.pos > elements.pos;\n return {\n node,\n start,\n end,\n text,\n order:\n range &&\n !ambiguousComment &&\n source.document.code.slice(start, end) ===\n node.getSourceFile().text.slice(node.getFullStart(), node.end)\n ? order\n : {\n kind: \"barrier\" as const,\n },\n };\n });\n\n for (let position = 0; position < items.length; position++) {\n const item = items[position];\n const next = items[position + 1];\n const tail = source.document.code.slice(\n item.end,\n next?.start ?? index.range(source, container.node)?.[1] ?? item.end,\n );\n const attachedToPrevious =\n /^[^\\r\\n]*(?:\\/\\/|\\/\\*)/.test(tail) ||\n (next &&\n /^[^\\r\\n]*(?:\\/\\/|\\/\\*)/.test(\n next.text.slice(0, next.text.length - (next.node.end - next.node.getStart())),\n ));\n if (attachedToPrevious) {\n item.order = {\n kind: \"barrier\",\n };\n }\n }\n\n const sorted = orderInputs(items, allows);\n if (sorted.every((item, position) => item === items[position])) {\n continue;\n }\n\n // Replace changed runs independently so unmapped nodes, holes, and spreads remain untouched.\n for (let position = 0; position < items.length;) {\n if (items[position] === sorted[position]) {\n position++;\n continue;\n }\n\n const start = position++;\n while (position < items.length && items[position] !== sorted[position]) {\n position++;\n }\n if (items.slice(start, position).some((item) => item.order.kind === \"barrier\")) {\n continue;\n }\n\n const edit = {\n start: items[start].start,\n end: items[position - 1].end,\n newText: sorted\n .slice(start, position)\n .map((item) => item.text)\n .join(\",\"),\n };\n edits = absorb(edits, edit);\n }\n }\n }\n\n return edits.sort((a, b) => a.start - b.start);\n}\n\n/**\n * Applies replacements from the end of a document so all ranges keep their original meaning.\n *\n * @param source - Original document text, or a slice whose coordinates match `edits`.\n * @param edits - Nonoverlapping half-open UTF-16 ranges within `source`, in any order.\n * The caller must provide valid boundaries because this function does not validate them.\n * @returns The replaced text. The edit array and its objects remain unchanged.\n */\nexport function applyEdits(source: string, edits: readonly EditorEdit[]): string {\n for (const edit of [...edits].sort((a, b) => b.start - a.start)) {\n source = source.slice(0, edit.start) + edit.newText + source.slice(edit.end);\n }\n return source;\n}\n\n/**\n * Escapes replacement content for an existing JS string or template token.\n *\n * @param text - Decoded replacement text without surrounding delimiters.\n * @param literal - Indexed literal whose AST token supplies the quote or backtick delimiter.\n * @returns Content without delimiters, with backslashes, the delimiter, tabs, CR, and LF escaped.\n * Template content also escapes `${` so it cannot introduce an interpolation.\n */\nexport function escapeContent(text: string, literal: UtilityLiteral): string {\n const quote = ts.isTemplateLiteralToken(literal.node) ? \"`\" : literal.node.getText()[0];\n let escaped = text\n .replaceAll(\"\\\\\", \"\\\\\\\\\")\n .replaceAll(quote, `\\\\${quote}`)\n .replaceAll(\"\\t\", \"\\\\t\")\n .replaceAll(\"\\r\", \"\\\\r\")\n .replaceAll(\"\\n\", \"\\\\n\");\n if (quote === \"`\") {\n escaped = escaped.replaceAll(\"${\", \"\\\\${\");\n }\n return escaped;\n}\n\n/**\n * Decodes a seeded replacement using the original literal's delimiter.\n *\n * @param text - Source spelling of replacement content that can be wrapped in that delimiter.\n * @param literal - Indexed literal that supplies the quote or backtick delimiter.\n * @returns TypeScript's decoded string value, or the supplied text when parsing produces a\n * different initializer kind. Parser diagnostics are not checked.\n */\nfunction decodeReplacement(text: string, literal: UtilityLiteral): string {\n const quote = ts.isTemplateLiteralToken(literal.node) ? \"`\" : literal.node.getText()[0];\n const file = ts.createSourceFile(\n \"literal.ts\",\n `const value=${quote}${text}${quote};`,\n ts.ScriptTarget.Latest,\n true,\n );\n const node = (file.statements[0] as ts.VariableStatement).declarationList.declarations[0]\n .initializer;\n return node && ts.isStringLiteralLike(node) ? node.text : text;\n}\n\n/**\n * Replaces edits covered by a larger, already composed replacement.\n *\n * @param edits - Existing edits in original coordinates. Every overlapping edit must be fully\n * contained in `replacement` and already reflected in its text.\n * @param replacement - Replacement whose text includes all contained edits.\n * @returns A new array with overlapping edits removed and the replacement appended.\n * The result is not sorted, and the input edit objects remain unchanged.\n */\nfunction absorb(edits: readonly EditorEdit[], replacement: EditorEdit): EditorEdit[] {\n return [\n ...edits.filter((edit) => edit.end <= replacement.start || edit.start >= replacement.end),\n replacement,\n ];\n}\n\n/**\n * Sorts contiguous runs of resolved utilities while keeping unresolved spellings in place.\n *\n * @param values - Decoded candidates in their original order.\n * @param compare - Compiler comparator prepared for these spellings. A null self-comparison\n * marks a boundary, and a null comparison within a run treats that pair as equal.\n * @returns A new array with stable ordering inside each run. `values` remains unchanged.\n */\nfunction sortRuns(\n values: string[],\n compare: (left: string, right: string) => number | null,\n): string[] {\n const result = [...values];\n let start = 0;\n for (let position = 0; position <= values.length; position++) {\n if (position === values.length || compare(values[position], values[position]) === null) {\n result.splice(\n start,\n position - start,\n ...values.slice(start, position).sort((a, b) => compare(a, b) ?? 0),\n );\n start = position + 1;\n }\n }\n return result;\n}\n","import { TraceMap, decodedMappings } from \"@jridgewell/trace-mapping\";\nimport type { NativeAssetRecord } from \"@stillwind/native\";\nimport type { CheckerBuffer, PreparedSource } from \"@stillwind/projection\";\nimport * as path from \"pathe\";\nimport ts from \"typescript-6\";\n\nimport { byteToUtf16 } from \"../compilation/module-source.ts\";\nimport type { TypeFactSource } from \"./backend.ts\";\n\n/** Checker-only insertion/replacement in input-buffer UTF-16 coordinates. */\ninterface ShadowEdit {\n /** Inclusive UTF-16 offset of the insertion or replacement in the unedited checker buffer. */\n at: number;\n /** Exclusive UTF-16 end in that buffer. Equal to `at` for an insertion. */\n end: number;\n /** Generated checker text that replaces the selected interval. */\n text: string;\n /** Original UTF-8 range that owns generated text in this edit. */\n original: {\n /** Inclusive UTF-8 byte offset used to map diagnostics inside the generated text. */\n start: number;\n /** Exclusive UTF-8 byte offset used when mapping the end of such a diagnostic. */\n end: number;\n };\n}\n\n/**\n * Serializes a declaration identity as a stable checker string-literal key.\n *\n * @param identity - Native declaration identity with original UTF-8 offsets.\n * @returns `stillwind-identity/v1:` followed by base64url JSON of kind, module ID, range, and\n * binding name in a fixed field order.\n */\nexport function identityKey(identity: NativeAssetRecord[\"identity\"]): string {\n const serialized = JSON.stringify({\n kind: identity.kind,\n moduleId: identity.moduleId,\n start: identity.start,\n end: identity.end,\n bindingName: identity.bindingName,\n });\n return `stillwind-identity/v1:${base64url(serialized)}`;\n}\n\n/**\n * Selects the checker filename for a prepared source.\n *\n * @param source - Source with its host checker filename and any projection syntax.\n * @returns The host filename for direct input, or that filename followed by the projection language\n * extension for projected input.\n */\nexport function checkerId(source: PreparedSource): string {\n return source.kind === \"direct\"\n ? source.checkerFileName\n : `${source.checkerFileName}.${source.projection.syntax.language}`;\n}\n\n/**\n * Applies the current query's probes to the project's sources without changing other inputs.\n *\n * @param inventory - Sources currently installed in the checker.\n * @param requested - Sources whose probe ranges or recognitionOnly settings may have changed.\n * Sources outside inventory are ignored.\n * @returns The original array when probes match, or a new array with changed source records.\n * Neither input is mutated. Unchanged source records are shared.\n */\nexport function withRequestedProbes(\n inventory: readonly TypeFactSource[],\n requested: readonly TypeFactSource[],\n): readonly TypeFactSource[] {\n const probesById = new Map(requested.map((source) => [source.resolverId, source.probes]));\n let changed = false;\n const sources = inventory.map((source) => {\n const probes = probesById.get(source.resolverId);\n if (\n !probes ||\n (probes.length === source.probes.length &&\n probes.every(\n (probe, index) =>\n probe.start === source.probes[index].start &&\n probe.end === source.probes[index].end &&\n probe.recognitionOnly === source.probes[index].recognitionOnly,\n ))\n ) {\n return source;\n }\n changed = true;\n return { ...source, probes };\n });\n return changed ? sources : inventory;\n}\n\n/**\n * Checker buffer with declaration identities, resolved import paths, and helper aliases inserted\n * for type queries. Its range maps relate checker AST expressions to original document bytes.\n */\nexport class CheckerSource {\n /** Prepared source and original-coordinate requests that own this checker buffer. */\n readonly source: TypeFactSource;\n /** Unedited input buffer, optionally restricted to one original script region. */\n readonly buffer: CheckerBuffer;\n /**\n * Final checker text after identity arguments, module paths, and helper bindings have been\n * rewritten.\n */\n readonly text: string;\n /**\n * Checker filename, with a distinct client-script suffix when the buffer has an original region.\n */\n readonly id: string;\n /** Serialized identity keys mapped to the native declarations supplied during construction. */\n readonly identities = new Map<string, NativeAssetRecord[\"identity\"]>();\n /** Independent module that supplies helper declarations in the virtual project. */\n readonly helperModule?: {\n /** Virtual TypeScript module filename used by the inserted import. */\n id: string;\n /** Generated helper declarations installed as that module's text. */\n text: string;\n };\n /** Shadow UTF-16 AST ranges keyed to original UTF-8 probe ranges. */\n readonly probes = new Map<\n string,\n {\n /** Inclusive original UTF-8 byte offset. */\n start: number;\n /** Exclusive original UTF-8 byte offset. */\n end: number;\n /** Whether the probe only recognizes an asset family without requiring a declaration identity. */\n recognitionOnly?: boolean;\n }\n >();\n /** Producer call ranges after identity insertion, keyed to their asset families. */\n readonly producers = new Map<string, NativeAssetRecord[\"identity\"][\"kind\"]>();\n /** Authored module specifiers keyed by their rewritten checker UTF-16 ranges. */\n readonly moduleSpecifiers = new Map<string, string>();\n\n /**\n * Ordered, nonoverlapping edits in the input buffer. Their cumulative lengths translate between\n * input and checker offsets.\n */\n readonly #edits: ShadowEdit[] = [];\n /** Original document text used to convert byte ranges and recover diagnostic byte offsets. */\n readonly #original: string;\n /**\n * Projected UTF-16 positions mapped to original UTF-16 positions. Null marks conflicting\n * correspondences. Missing keys have no known mapping.\n */\n readonly #points: Map<number, number | null>;\n\n /**\n * Constructs checker text and range indexes without modifying the source or input buffer.\n *\n * @param source - Prepared source with validated frontend correspondences, probes, resolutions,\n * and helper references.\n * @param buffer - Direct or projected checker text, optionally scoped to an original script\n * region.\n * @param index - Buffer index used to give independent client scripts distinct filenames.\n * @param assets - Native declaration records with original-byte producer call ranges. Repeated\n * records for the same generated call are inserted once.\n * @param ids - Resolved source identities mapped to their main checker filenames for import\n * rewriting.\n * @throws If a byte boundary is invalid, producer identities conflict, a mapped producer does not\n * end with a closing parenthesis, edits overlap, or projection decoding fails.\n */\n constructor(\n source: TypeFactSource,\n buffer: CheckerBuffer,\n index: number,\n assets: readonly NativeAssetRecord[],\n ids: ReadonlyMap<string, string>,\n ) {\n this.source = source;\n this.buffer = buffer;\n this.id = buffer.region\n ? `${source.checkerFileName}.stillwind-client-${index}.ts`\n : checkerId(source);\n this.#original = source.document.code;\n this.#points = projectionPoints(source);\n const producers = new Map<number, string>();\n const producerRanges: {\n /** Inclusive UTF-16 producer call offset before checker edits. */\n start: number;\n /** Exclusive UTF-16 producer call offset before checker edits. */\n end: number;\n /** Asset family used to interpret the producer's result. */\n kind: NativeAssetRecord[\"identity\"][\"kind\"];\n }[] = [];\n for (const asset of assets) {\n const targets = this.targets(asset.callStart, asset.callEnd, \"producer\");\n const key = identityKey(asset.identity);\n this.identities.set(key, asset.identity);\n for (const [start, end] of targets) {\n const previous = producers.get(end);\n if (previous) {\n if (previous !== key) {\n throw new Error(`Conflicting producer identities in ${source.moduleId}`);\n }\n continue;\n }\n producers.set(end, key);\n producerRanges.push({ start, end, kind: asset.identity.kind });\n const call = buffer.source.slice(start, end);\n if (!call.endsWith(\")\")) {\n throw new Error(`Cannot locate producer in ${source.moduleId}`);\n }\n const separator = [...call.matchAll(/[,(]/g)].some(\n (match) => skipTrivia(call, match.index + 1) === call.length - 1,\n )\n ? \"\"\n : \",\";\n const identity = `{readonly __stillwindDeclarationIdentity:${JSON.stringify(key)}}`;\n const syntax = source.kind === \"direct\" ? source.syntax : source.projection.syntax;\n const javascript = syntax.language === \"js\" || syntax.language === \"jsx\";\n const argument = javascript\n ? `/** @type {${identity}} */ (/** @type {unknown} */ (undefined))`\n : `undefined as unknown as ${identity}`;\n this.#edits.push({\n at: end - 1,\n end: end - 1,\n original: {\n start: asset.callStart,\n end: asset.callEnd,\n },\n text: `${separator}${argument}`,\n });\n }\n }\n const specifiers: {\n start: number;\n end: number;\n text: string;\n }[] = [];\n for (const resolution of source.resolutions ?? []) {\n for (const [at, end] of this.targets(resolution.start, resolution.end, \"moduleSpecifier\")) {\n const scanner = ts.createScanner(ts.ScriptTarget.Latest, true);\n scanner.setText(buffer.source.slice(at, end));\n scanner.scan();\n specifiers.push({\n start: at,\n end,\n text: scanner.getTokenValue(),\n });\n this.#edits.push({\n at,\n end,\n original: {\n start: resolution.start,\n end: resolution.end,\n },\n text: JSON.stringify(\n path.resolve(ids.get(resolution.id) ?? resolution.id).replaceAll(\"\\\\\", \"/\"),\n ),\n });\n }\n }\n const bindings = buffer.region ? [] : (source.checkerBindings ?? []);\n if (bindings.length > 0) {\n const names = new Set(\n buffer.source\n .replaceAll(/\\\\u(?:\\{([\\da-fA-F]{1,6})\\}|([\\da-fA-F]{4}))/g, (escape, braced, fixed) => {\n const value = Number.parseInt(braced ?? fixed, 16);\n return value <= 0x10ffff ? String.fromCodePoint(value) : escape;\n })\n .match(/[$_\\p{ID_Start}][$\\u200c\\u200d\\p{ID_Continue}]*/gu),\n );\n const aliases = new Map<string, string>();\n let next = 0;\n for (const binding of bindings) {\n let alias = aliases.get(binding.name);\n if (!alias) {\n do {\n alias = `__stillwindCheckerHelper${next++}`;\n } while (names.has(alias));\n aliases.set(binding.name, alias);\n }\n this.#edits.push({\n at: binding.projectedStart,\n end: binding.projectedEnd,\n text: alias,\n original: { start: 0, end: 0 },\n });\n }\n const id = `${this.id}.stillwind-helpers.ts`;\n this.helperModule = {\n id,\n text: [...aliases.keys()]\n .map((name) => `export declare const ${name}: typeof globalThis.${name};`)\n .join(\"\\n\"),\n };\n // Triple-slash directives must precede module statements.\n this.#edits.push({\n at: buffer.source.length,\n end: buffer.source.length,\n text: `\\nimport {${[...aliases].map(([name, alias]) => `${name} as ${alias}`).join(\",\")}} from ${JSON.stringify(path.resolve(id).replaceAll(\"\\\\\", \"/\"))};\\n`,\n original: {\n start: 0,\n end: 0,\n },\n });\n }\n this.#edits.sort((a, b) => a.at - b.at || a.end - b.end);\n for (let i = 1; i < this.#edits.length; i++) {\n if (\n this.#edits[i].at < this.#edits[i - 1].end ||\n this.#edits[i].at === this.#edits[i - 1].at\n ) {\n throw new Error(`Overlapping checker edits in ${source.moduleId}`);\n }\n }\n for (const probe of source.probes) {\n for (const [start, end] of this.targets(probe.start, probe.end, \"expression\")) {\n this.probes.set(`${this.toShadow(start)}:${this.toShadow(end, true)}`, probe);\n }\n }\n for (const specifier of specifiers) {\n this.moduleSpecifiers.set(\n `${this.toShadow(specifier.start)}:${this.toShadow(specifier.end, true)}`,\n specifier.text,\n );\n }\n for (const producer of producerRanges) {\n this.producers.set(\n `${this.toShadow(producer.start)}:${this.toShadow(producer.end, true)}`,\n producer.kind,\n );\n }\n let text = buffer.source;\n for (const edit of [...this.#edits].reverse()) {\n text = text.slice(0, edit.at) + edit.text + text.slice(edit.end);\n }\n this.text = text;\n }\n\n /**\n * Finds input-buffer intervals corresponding to one original range and role.\n *\n * @param start - Inclusive original UTF-8 byte boundary.\n * @param end - Exclusive original UTF-8 byte boundary.\n * @param role - Frontend correspondence role, matched exactly for projected input.\n * @returns Deduplicated UTF-16 intervals. Independent scripts receive only contained ranges.\n * Their ranges are excluded from the main buffer. Unmapped projected ranges produce an empty\n * list.\n * @throws If either original byte boundary is invalid.\n */\n targets(start: number, end: number, role: string): [number, number][] {\n const a = byteToUtf16(this.#original, start);\n const b = byteToUtf16(this.#original, end);\n if (this.buffer.region) {\n return a >= this.buffer.region.start && b <= this.buffer.region.end\n ? [[a - this.buffer.region.start, b - this.buffer.region.start]]\n : [];\n }\n if (\n this.source.checkerBuffers?.some(\n (buffer) => buffer.region && a >= buffer.region.start && b <= buffer.region.end,\n )\n ) {\n return [];\n }\n if (this.source.kind === \"direct\") {\n return [[a, b]];\n }\n return [\n ...new Map(\n (this.source.checkerSpans ?? [])\n .filter((span) => span.start === start && span.end === end && span.role === role)\n .map((span) => [\n `${span.projectedStart}:${span.projectedEnd}`,\n [span.projectedStart, span.projectedEnd] as [number, number],\n ]),\n ).values(),\n ];\n }\n\n /**\n * Translates an input-buffer boundary after checker edits are applied.\n *\n * @param position - UTF-16 boundary in the unedited checker buffer.\n * @param end - True for an interval end, which stays before an insertion at the same position.\n * False includes such an insertion.\n * @returns The UTF-16 boundary in final checker text. Positions should delimit preserved input\n * intervals rather than lie inside replaced text.\n */\n toShadow(position: number, end = false): number {\n let delta = 0;\n for (const edit of this.#edits) {\n if (edit.at > position || (edit.at === position && (end || edit.end > edit.at))) {\n break;\n }\n delta += edit.text.length - (edit.end - edit.at);\n }\n return position + delta;\n }\n\n /**\n * Maps a checker position back to an original document byte boundary.\n *\n * @param position - UTF-16 position in final checker text.\n * @param end - True selects the owning original range's end for positions inside generated edits.\n * False selects its start.\n * @returns An original UTF-8 byte offset, or null when a projected position has no unique known\n * correspondence.\n */\n originalOffset(position: number, end = false): number | null {\n let delta = 0;\n for (const edit of this.#edits) {\n const start = edit.at + delta;\n if (position < start) {\n break;\n }\n if (position < start + edit.text.length) {\n return end ? edit.original.end : edit.original.start;\n }\n delta += edit.text.length - (edit.end - edit.at);\n }\n const generated = position - delta;\n const original = this.buffer.region\n ? generated + this.buffer.region.start\n : this.source.kind === \"direct\"\n ? generated\n : this.#points.get(generated);\n return original === undefined || original === null\n ? null\n : new TextEncoder().encode(this.#original.slice(0, original)).length;\n }\n}\n\n/**\n * Collects exact projection points for mapping checker diagnostics back to a document.\n *\n * @param source - Prepared source with its original text and any Volar or version 3 projection map.\n * @returns Generated UTF-16 positions mapped to original UTF-16 positions. Conflicting points map\n * to null. Direct sources produce an empty map because their offsets are translated directly.\n * @throws If a version 3 projection map cannot be decoded.\n */\nexport function projectionPoints(source: PreparedSource): Map<number, number | null> {\n const points = new Map<number, number | null>();\n /**\n * Records a projection point and keeps conflicting mappings ambiguous.\n * @param generated - UTF-16 offset in the generated checker source.\n * @param original - Corresponding UTF-16 offset in the original document.\n */\n const add = (generated: number, original: number) => {\n if (points.has(generated) && points.get(generated) !== original) {\n points.set(generated, null);\n } else {\n points.set(generated, original);\n }\n };\n if (source.kind === \"direct\") {\n return points;\n }\n const map = source.projection.map;\n if (map.kind === \"volar\") {\n for (const entry of map.mappings) {\n for (let i = 0; i < entry.sourceOffsets.length; i++) {\n const length = entry.generatedLengths?.[i] ?? entry.lengths[i];\n add(entry.generatedOffsets[i], entry.sourceOffsets[i]);\n if (length === entry.lengths[i]) {\n for (let j = 1; j < length; j++) {\n add(entry.generatedOffsets[i] + j, entry.sourceOffsets[i] + j);\n }\n }\n }\n }\n } else {\n /**\n * Builds line starts for converting source-map columns to offsets.\n * @param text - Original or generated text whose LF characters delimit lines.\n * @returns Ordered UTF-16 offsets, beginning with zero and including the position after every LF.\n */\n const lines = (text: string) => [\n 0,\n ...[...text.matchAll(/\\n/g)].map((match) => match.index + 1),\n ];\n const generated = lines(source.projection.code);\n const original = lines(source.document.code);\n const trace = new TraceMap(map.json);\n const selected = trace.sources.indexOf(map.source);\n for (const [line, segments] of decodedMappings(trace).entries()) {\n for (const segment of segments) {\n if (segment.length >= 4 && segment[1] === selected) {\n add(generated[line] + segment[0], original[segment[2]!] + segment[3]!);\n }\n }\n }\n }\n return points;\n}\n\n/**\n * Encodes identity JSON as an unpadded base64url key.\n * @param text - Serialized identity text encoded as UTF-8 before base64 conversion.\n * @returns Base64 with URL-safe characters and no trailing padding.\n */\nfunction base64url(text: string): string {\n return btoa(String.fromCharCode(...new TextEncoder().encode(text)))\n .replaceAll(\"+\", \"-\")\n .replaceAll(\"/\", \"_\")\n .replace(/=+/, \"\");\n}\n\n/**\n * Finds the next token start after whitespace and comments.\n * @param text - Checker call text to scan.\n * @param offset - UTF-16 position at which scanning starts.\n * @returns UTF-16 start of the next token, or text.length at end of input.\n */\nfunction skipTrivia(text: string, offset: number): number {\n const scanner = ts.createScanner(ts.ScriptTarget.Latest, true);\n scanner.setText(text);\n scanner.resetTokenState(offset);\n scanner.scan();\n return scanner.getTokenStart();\n}\n","import {\n fingerprint,\n type NativeEditorSite,\n type NativeIdentity,\n type NativeModuleEditor,\n type NativeProjectSession,\n} from \"@stillwind/native\";\nimport type { PreparedSource } from \"@stillwind/projection\";\n\nimport { byteToUtf16 } from \"../compilation/module-source.ts\";\nimport type { ModuleAnalysis } from \"../compilation/request.ts\";\nimport { identityKey } from \"../semantics/checker-source.ts\";\n\ntype CapturedEditorSite = Readonly<\n Omit<NativeEditorSite, \"identity\" | \"dependencies\" | \"runtimeNames\">\n> & {\n readonly identity?: Readonly<NativeIdentity>;\n readonly dependencies: readonly Readonly<NativeIdentity>[];\n readonly runtimeNames: readonly string[];\n};\n\n/** A compiler occurrence mapped to the original document's UTF-16 coordinates. */\nexport interface PreviewSite {\n /** Compiler output with original UTF-8 ranges and any literal replacement context. */\n readonly native: CapturedEditorSite;\n /** Inclusive UTF-16 offset in the original document, before projection. */\n readonly start: number;\n /** Exclusive UTF-16 offset in the original document, before projection. */\n readonly end: number;\n}\n\n/** CSS for a captured occurrence and any runtime expressions that supply view-transition names. */\nexport interface GeneratedPreview {\n /** CSS for the occurrence and its required styles and global definitions. */\n css: string;\n /** Authored runtime key expressions, deduplicated in dependency traversal order. */\n runtimeNames: string[];\n}\n\n/** Captures compiler input plans and assembles their required declaration previews. */\nexport class GeneratedPreviews {\n /** Fingerprint of original buffers, capture revisions, and resolved graph dependencies. */\n readonly revision: string;\n\n /** Captures and original UTF-16 sites, keyed by full compiler module identity. */\n readonly #modules = new Map<\n string,\n {\n /** Frozen module plans whose generated names belong to this capture batch. */\n editor: NativeModuleEditor;\n /** Captured occurrences mapped to original UTF-16 offsets, in compiler traversal order. */\n sites: readonly PreviewSite[];\n }\n >();\n /** Declaration and style-call sites keyed by semantic identity, including imported values. */\n readonly #declarations = new Map<string, CapturedEditorSite>();\n\n /**\n * Captures the graph's known modules together so their display names share one table.\n * Unknown modules are skipped.\n * Dependency previews require their declaration modules to be present in the graph.\n *\n * @param graph - Original buffers and dependencies for the source revisions to capture.\n * @param session - Session whose analyses for modules match the supplied buffers. Captures remain\n * usable after later session updates. Published sites are readonly.\n * @param modules - Module IDs successfully compiled from these buffers. Other retained analyses are skipped.\n * @throws If a captured UTF-8 range is invalid for its original buffer.\n */\n constructor(\n graph: Pick<ModuleAnalysis, \"sources\" | \"dependencies\">,\n session: NativeProjectSession,\n modules: readonly string[],\n ) {\n const revisions: string[] = [];\n const captures = new Map(\n session.editorModules([...modules]).map((editor) => [editor.moduleId(), editor]),\n );\n for (const source of graph.sources) {\n const editor = captures.get(source.moduleId);\n revisions.push(source.moduleId, fingerprint(source.document.code), editor?.revision() ?? \"\");\n if (!editor) {\n continue;\n }\n\n const sites: readonly PreviewSite[] = editor.sites().map((native) => ({\n native,\n start: byteToUtf16(source.document.code, native.start),\n end: byteToUtf16(source.document.code, native.end),\n }));\n this.#modules.set(source.moduleId, {\n editor,\n sites,\n });\n for (const { native } of sites) {\n if (native.identity) {\n this.#declarations.set(identityKey(native.identity), native);\n }\n }\n }\n this.revision = fingerprint(JSON.stringify([revisions, graph.dependencies]));\n }\n\n /**\n * Finds the occurrences captured for one compiler module.\n *\n * @param source - Prepared source whose full module identity selects the capture.\n * @returns Occurrences in compiler traversal order, or an empty list for an unknown module.\n * The array and its entries are readonly and shared with this capture.\n */\n sites(source: PreparedSource): readonly PreviewSite[] {\n return this.#modules.get(source.moduleId)?.sites ?? [];\n }\n\n /**\n * Finds a literal at the half-open original UTF-16 range `[start, end)`.\n * The range may address the literal content or include its one-character delimiters.\n *\n * @param source - Prepared source whose full module identity selects the capture.\n * @param start - Inclusive original UTF-16 offset of the content or opening delimiter.\n * @param end - Exclusive original UTF-16 offset of the content or closing delimiter.\n * @returns A shared occurrence with an input context, or undefined when no range matches exactly.\n */\n input(source: PreparedSource, start: number, end: number): PreviewSite | undefined {\n for (const site of this.sites(source)) {\n if (\n site.native.context &&\n ((site.start === start && site.end === end) ||\n (site.start === start + 1 && site.end === end - 1))\n ) {\n return site;\n }\n }\n return undefined;\n }\n\n /**\n * Renders a replacement for the whole captured input while retaining its compiler conditions.\n * The result contains only that plan's CSS. Dependency assembly is handled by `preview`.\n *\n * @param source - Prepared source whose full module identity selects the capture.\n * @param start - Inclusive original UTF-8 byte offset of the captured input, taken from\n * `PreviewSite.native.start`.\n * @param candidate - Decoded replacement text without enclosing group variants.\n * @returns CSS for that plan, or undefined for an unknown module or input, failed emission,\n * or output with no CSS. Captured plans and shared generated names remain unchanged.\n */\n previewInput(source: PreparedSource, start: number, candidate: string): string | undefined {\n return this.#modules.get(source.moduleId)?.editor.previewInput(start, candidate) ?? undefined;\n }\n\n /**\n * Assembles a captured declaration or style call addressed by its semantic identity.\n * Imported aliases reuse that identity.\n *\n * @param identity - Full native declaration identity, including original UTF-8 ranges.\n * @returns The preview assembled by `preview`, or undefined when the identity is absent\n * or its declaration and dependencies cannot supply valid, nonempty CSS.\n */\n previewIdentity(identity: NativeIdentity): GeneratedPreview | undefined {\n const site = this.#declarations.get(identityKey(identity));\n return site ? this.preview(site) : undefined;\n }\n\n /**\n * Assembles `site` and its dependencies from this capture batch. Composed styles precede\n * the site's CSS, and global definitions follow it. Each dependency identity is visited once.\n * Identical CSS parts and runtime expression text are deduplicated in traversal order.\n *\n * @param site - Occurrence from this instance's capture batch. Its generated names must share\n * the declaration captures' name table.\n * @returns CSS and runtime key expressions, or undefined if any required site is missing or\n * invalid, or if the assembled CSS is empty. The site and declaration captures remain unchanged.\n */\n preview(site: CapturedEditorSite): GeneratedPreview | undefined {\n const preview = this.assemble(site);\n return preview?.css ? preview : undefined;\n }\n\n /**\n * Assembles `site` as {@link preview} does and keeps a successful empty result.\n *\n * @param site - Occurrence from this instance's capture batch.\n * @returns CSS and runtime key expressions, with empty CSS when the occurrence contributes none,\n * or undefined if any required site is missing or invalid.\n */\n assemble(site: CapturedEditorSite): GeneratedPreview | undefined {\n const parts: string[] = [];\n const runtimeNames = new Set<string>();\n const seen = new Set<string>();\n /**\n * Appends valid output and dependency expressions to the shared accumulators.\n * A false result can leave partial entries, which the outer query discards on failure.\n *\n * @param site - Occurrence from the same capture batch as its dependency declarations.\n * @returns Whether the occurrence and every newly visited dependency are valid and present.\n */\n const collect = (site: CapturedEditorSite): boolean => {\n if (!site.valid) {\n return false;\n }\n\n const dependencies = site.dependencies.flatMap((identity) => {\n const key = identityKey(identity);\n if (seen.has(key)) {\n return [];\n }\n\n seen.add(key);\n return [\n {\n identity,\n site: this.#declarations.get(key),\n },\n ];\n });\n for (const dependency of dependencies.filter((item) => item.identity.kind === \"style\")) {\n if (!dependency.site || !collect(dependency.site)) {\n return false;\n }\n }\n\n if (site.css) {\n parts.push(site.css);\n }\n for (const name of site.runtimeNames) {\n runtimeNames.add(name);\n }\n\n for (const dependency of dependencies.filter((item) => item.identity.kind !== \"style\")) {\n if (!dependency.site || !collect(dependency.site)) {\n return false;\n }\n }\n return true;\n };\n if (!collect(site)) {\n return undefined;\n }\n return {\n css: [...new Set(parts)].join(\"\\n\"),\n runtimeNames: [...runtimeNames],\n };\n }\n}\n","import type { NativeAssetRecord, NativeLintComment, NativeProjectSession } from \"@stillwind/native\";\nimport type { PreparedSource } from \"@stillwind/projection\";\nimport ts from \"typescript-6\";\n\nimport type { ModuleAnalysis } from \"../../compilation/request.ts\";\nimport { projectionPoints } from \"../../semantics/checker-source.ts\";\n\n/**\n * Resolves declaration identities and original ranges in a fixed source graph.\n */\nexport class SourceBindings {\n /** In-memory files keyed by checker filename with slash separators and preserved casing. */\n readonly files = new Map<\n string,\n {\n /** Prepared source that owns this AST and its projection correspondences. */\n source: PreparedSource;\n /** AST parsed from direct source text or the prepared projection. */\n ast: ts.SourceFile;\n }\n >();\n\n /** Producers keyed first by module identity, then by `start:end` in original UTF-16 coordinates. */\n readonly #assets = new Map<string, Map<string, NativeAssetRecord>>();\n\n /** Comments with `swlint-*` directives keyed by module identity, from each source's scan. */\n readonly #lintComments = new Map<string, NativeLintComment[]>();\n\n /** Resolved producers and cached misses for nodes in the captured checker ASTs. */\n readonly #nodeAssets = new WeakMap<ts.Node, NativeAssetRecord | undefined>();\n\n /** Generated UTF-16 positions mapped to original positions. Null marks conflicting origins. */\n readonly #points = new Map<string, Map<number, number | null>>();\n\n /** Binder over the in-memory files and the graph's resolved import dependencies. */\n readonly #checker: ts.TypeChecker;\n\n /** Symbols found in assignment or increment/decrement targets, excluded from stable aliases. */\n readonly #mutated = new Set<ts.Symbol>();\n\n /**\n * Parses sources, scans declaration records, and binds imports without reading disk.\n *\n * @param graph - Fixed sources and resolved dependencies from one analysis. Do not mutate its sources.\n * @param session - Session used to scan those sources. Capture previews before constructing this binder.\n * @throws If source scanning or projection mapping fails.\n */\n constructor(\n graph: Pick<ModuleAnalysis, \"sources\" | \"dependencies\">,\n session: NativeProjectSession,\n ) {\n for (const source of graph.sources) {\n const text = source.kind === \"direct\" ? source.document.code : source.projection.code;\n const fileName = checkerName(source.checkerFileName);\n const ast = ts.createSourceFile(\n fileName,\n text,\n ts.ScriptTarget.Latest,\n true,\n ts.ScriptKind.TSX,\n );\n this.files.set(fileName, {\n source,\n ast,\n });\n this.#points.set(source.moduleId, projectionPoints(source));\n const scan = session.scanSource(source);\n this.#assets.set(\n source.moduleId,\n assetRanges(source.document.code, scan.kind === \"ready\" ? scan.summary.assets : []),\n );\n this.#lintComments.set(\n source.moduleId,\n scan.kind === \"ready\" ? scan.summary.lintComments : [],\n );\n }\n\n const host: ts.CompilerHost = {\n getSourceFile: (name) => this.files.get(checkerName(name))?.ast,\n getDefaultLibFileName: () => \"lib.d.ts\",\n writeFile: () => {},\n getCurrentDirectory: () => \"/\",\n getDirectories: () => [],\n fileExists: (name) => this.files.has(checkerName(name)),\n readFile: (name) => this.files.get(checkerName(name))?.ast.text,\n getCanonicalFileName: checkerName,\n useCaseSensitiveFileNames: () => true,\n getNewLine: () => \"\\n\",\n resolveModuleNames: (names, containingFile) =>\n names.map((name) => {\n const source = this.files.get(checkerName(containingFile))?.source;\n const dependency = graph.dependencies.find(\n (item) => item.importer === source?.resolverId && item.specifier === name,\n );\n const target = graph.sources.find((item) => item.resolverId === dependency?.id);\n return target\n ? { resolvedFileName: checkerName(target.checkerFileName), extension: ts.Extension.Tsx }\n : undefined;\n }),\n };\n const program = ts.createProgram(\n [...this.files.keys()],\n {\n noLib: true,\n allowJs: true,\n },\n host,\n );\n this.#checker = program.getTypeChecker();\n\n for (const { ast } of this.files.values()) {\n walk(ast, (node) => {\n const target =\n ts.isBinaryExpression(node) &&\n node.operatorToken.kind >= ts.SyntaxKind.FirstAssignment &&\n node.operatorToken.kind <= ts.SyntaxKind.LastAssignment\n ? node.left\n : (ts.isPrefixUnaryExpression(node) || ts.isPostfixUnaryExpression(node)) &&\n [ts.SyntaxKind.PlusPlusToken, ts.SyntaxKind.MinusMinusToken].includes(node.operator)\n ? node.operand\n : undefined;\n if (target) {\n /**\n * Records symbols in assignment targets that can contain identifier bindings.\n * Property accesses do not mark their receiver as a reassigned binding.\n *\n * @param node - Identifier or supported destructuring subtree of the target.\n * Recognized symbols are added to `#mutated`, including nested pattern members.\n */\n const mark = (node: ts.Node): void => {\n if (ts.isIdentifier(node)) {\n const symbol = this.#checker.getSymbolAtLocation(node);\n if (symbol) {\n this.#mutated.add(symbol);\n }\n } else if (\n ts.isArrayLiteralExpression(node) ||\n ts.isObjectLiteralExpression(node) ||\n ts.isPropertyAssignment(node) ||\n ts.isShorthandPropertyAssignment(node) ||\n ts.isSpreadAssignment(node) ||\n ts.isSpreadElement(node) ||\n ts.isParenthesizedExpression(node)\n ) {\n ts.forEachChild(node, mark);\n }\n };\n mark(target);\n }\n });\n }\n }\n\n /**\n * Recognizes a direct method of an imported Stillwind style producer.\n * Other property accesses with the same spelling do not establish producer authority.\n *\n * @param node - Expression in one of this index's checker ASTs.\n * @param name - Exact method spelling, such as `keyframes` or `viewTransition`.\n * @returns Whether the receiver is a supported value import of `style` and the method matches.\n */\n producer(node: ts.Expression, name: string): boolean {\n return (\n ts.isPropertyAccessExpression(node) &&\n node.name.text === name &&\n this.styleImport(node.expression)\n );\n }\n\n /**\n * Checks direct named imports of `style` and namespace accesses to that export.\n *\n * @param node - Expression in this index's checker ASTs. Supported imports come from\n * Stillwind's framework and vanilla entrypoints.\n * @returns Whether a value import establishes that producer. Type-only imports and symbols\n * marked as mutated fail this check.\n */\n styleImport(node: ts.Expression): boolean {\n const namespace = ts.isPropertyAccessExpression(node) && node.name.text === \"style\";\n if (!ts.isIdentifier(node) && !(namespace && ts.isIdentifier(node.expression))) {\n return false;\n }\n\n const symbol = this.#checker.getSymbolAtLocation(namespace ? node.expression : node);\n if (!symbol || this.#mutated.has(symbol)) {\n return false;\n }\n\n return !!symbol.declarations?.some((declaration) => {\n if (\n namespace\n ? !ts.isNamespaceImport(declaration)\n : !ts.isImportSpecifier(declaration) ||\n (declaration.propertyName ?? declaration.name).text !== \"style\" ||\n declaration.isTypeOnly\n ) {\n return false;\n }\n\n const owner = ts.isNamespaceImport(declaration)\n ? declaration.parent.parent\n : declaration.parent.parent.parent;\n return (\n ts.isImportDeclaration(owner) &&\n owner.importClause?.phaseModifier !== ts.SyntaxKind.TypeKeyword &&\n ts.isStringLiteral(owner.moduleSpecifier) &&\n /^stillwind\\/(?:alpine|astro|lit|preact|qwik|react|solid|svelte|vanilla|vue)$/.test(\n owner.moduleSpecifier.text,\n )\n );\n });\n }\n\n /**\n * Maps a checker node to an exact range in its original document.\n * For projections, an anchor is accepted only when the intervening and selected text match\n * the original buffer. A conflicting mapping at the node's start prevents fallback to an anchor.\n *\n * @param source - Prepared source whose checker AST contains `node`.\n * @param node - Node from this index, with leading trivia excluded from its selected range.\n * @returns Inclusive start and exclusive end in original UTF-16 coordinates, or undefined\n * when a projection cannot map the text exactly.\n */\n range(source: PreparedSource, node: ts.Node): [number, number] | undefined {\n const ast = node.getSourceFile();\n const start = node.getStart(ast);\n const end = node.end;\n if (source.kind === \"direct\") {\n return [start, end];\n }\n const points = this.#points.get(source.moduleId)!;\n const exact = points.get(start);\n const anchors =\n exact === undefined\n ? [...points]\n .filter(([position, original]) => position <= start && original !== null)\n .sort((a, b) => b[0] - a[0])\n : [[start, exact] as const];\n for (const [position, original] of anchors) {\n if (original === null || original === undefined) {\n continue;\n }\n const offset = original + start - position;\n if (\n source.document.code.slice(original, offset + end - start) === ast.text.slice(position, end)\n ) {\n return [offset, offset + end - start];\n }\n }\n return undefined;\n }\n\n /**\n * Resolves a native producer or an alias through stable variable initializers and imports.\n * Both successful resolutions and misses are cached for the AST node.\n *\n * @param source - Prepared source whose checker AST contains `node`.\n * @param node - Node from this index. Alias chains may reach another source in the same graph.\n * @returns A shared native record that callers must keep unchanged, or undefined when no\n * producer is found. Mutated bindings and cyclic aliases stop alias resolution.\n */\n asset(source: PreparedSource, node: ts.Node): NativeAssetRecord | undefined {\n if (!this.#nodeAssets.has(node)) {\n this.#nodeAssets.set(node, this.#resolveAsset(source, node, new Set()));\n }\n return this.#nodeAssets.get(node);\n }\n\n /**\n * Returns the comments that contain `swlint-*` directives in `source`'s original buffer.\n *\n * @param source - Prepared source of this index.\n * @returns Comment bodies in original UTF-8 byte offsets, or an empty list when the scan\n * failed. Callers must keep the returned list unchanged.\n */\n lintComments(source: PreparedSource): NativeLintComment[] {\n return this.#lintComments.get(source.moduleId) ?? [];\n }\n\n /**\n * Follows a producer range or a stable alias chain without caching intermediate nodes.\n * Exact native producer records take precedence over checks on alias bindings.\n *\n * @param source - Prepared source whose checker AST contains `node`.\n * @param node - Expression to resolve, including supported TypeScript wrappers.\n * @param seen - Symbols already visited in the current chain. Visited symbols are added\n * even when resolution fails, so a separate chain needs a fresh set.\n * @returns The native record reached by the chain, or undefined for mutated, cyclic,\n * missing, or unsupported bindings.\n */\n #resolveAsset(\n source: PreparedSource,\n node: ts.Node,\n seen: Set<ts.Symbol>,\n ): NativeAssetRecord | undefined {\n const range = this.range(source, node);\n if (range) {\n const found = this.#assets.get(source.moduleId)?.get(`${range[0]}:${range[1]}`);\n if (found) {\n return found;\n }\n }\n if (\n ts.isParenthesizedExpression(node) ||\n ts.isAsExpression(node) ||\n ts.isSatisfiesExpression(node) ||\n ts.isNonNullExpression(node)\n ) {\n return this.#resolveAsset(source, node.expression, seen);\n }\n if (ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression)) {\n const receiver = this.#checker.getSymbolAtLocation(node.expression);\n if (!receiver?.declarations?.some(ts.isNamespaceImport)) {\n return undefined;\n }\n } else if (!ts.isIdentifier(node)) {\n return undefined;\n }\n let symbol = this.#checker.getSymbolAtLocation(node);\n if (!symbol || this.#mutated.has(symbol) || seen.has(symbol)) {\n return undefined;\n }\n seen.add(symbol);\n if (symbol.flags & ts.SymbolFlags.Alias) {\n symbol = this.#checker.getAliasedSymbol(symbol);\n if (this.#mutated.has(symbol) || seen.has(symbol)) {\n return undefined;\n }\n seen.add(symbol);\n }\n const declaration = symbol.valueDeclaration;\n if (declaration && ts.isVariableDeclaration(declaration) && declaration.initializer) {\n const owner = this.files.get(declaration.getSourceFile().fileName)?.source;\n return owner ? this.#resolveAsset(owner, declaration.initializer, seen) : undefined;\n }\n return undefined;\n }\n\n /**\n * Finds the smallest mapped AST node that contains an original document position.\n *\n * @param source - Prepared source whose checker filename selects a file in this index.\n * @param offset - Original UTF-16 cursor offset. Containment uses half-open ranges.\n * @returns The containing node, or undefined when the file is absent or no mapped node\n * contains the position. A position at a node's exclusive end does not select that node.\n */\n nodeAt(source: PreparedSource, offset: number): ts.Node | undefined {\n const file = this.files.get(checkerName(source.checkerFileName));\n let best: ts.Node | undefined;\n if (file) {\n walk(file.ast, (node) => {\n const range = this.range(source, node);\n if (\n range &&\n range[0] <= offset &&\n offset < range[1] &&\n (!best || node.end - node.pos < best.end - best.pos)\n ) {\n best = node;\n }\n });\n }\n return best;\n }\n}\n\n/**\n * Converts native producer call ranges with one traversal of the original source.\n *\n * @param text - Original document text that owns every producer range.\n * @param assets - Native records whose call ranges use original UTF-8 byte offsets.\n * @returns Records keyed by `start:end`, where both offsets use original UTF-16 coordinates.\n * @throws If a call boundary falls inside a UTF-8 sequence or outside the source.\n */\nfunction assetRanges(\n text: string,\n assets: readonly NativeAssetRecord[],\n): Map<string, NativeAssetRecord> {\n const offsets = [...new Set(assets.flatMap((asset) => [asset.callStart, asset.callEnd]))].sort(\n (a, b) => a - b,\n );\n const positions = new Map<number, number>();\n let byte = 0;\n let utf16 = 0;\n for (const offset of offsets) {\n while (byte < offset && utf16 < text.length) {\n const point = text.codePointAt(utf16)!;\n byte += point <= 0x7f ? 1 : point <= 0x7ff ? 2 : point <= 0xffff ? 3 : 4;\n utf16 += point > 0xffff ? 2 : 1;\n }\n if (byte !== offset) {\n throw new Error(\"Invalid original UTF-8 boundary\");\n }\n positions.set(offset, utf16);\n }\n return new Map(\n assets.map((asset) => [\n `${positions.get(asset.callStart)}:${positions.get(asset.callEnd)}`,\n asset,\n ]),\n );\n}\n\n/**\n * Provides the separator spelling used by the in-memory checker file map.\n *\n * @param name - Checker filename with either slash or backslash separators.\n * @returns The filename with slash separators. Casing and path segments remain unchanged.\n */\nfunction checkerName(name: string): string {\n return name.replaceAll(\"\\\\\", \"/\");\n}\n\n/**\n * Visits an AST node before its descendants in TypeScript's child order.\n *\n * @param node - Root of the subtree to traverse.\n * @param visit - Callback for each node. It must preserve the tree during traversal.\n * Returning from the callback does not skip descendants.\n * @throws If the callback throws, traversal stops and propagates that error.\n */\nexport function walk(node: ts.Node, visit: (node: ts.Node) => void): void {\n visit(node);\n ts.forEachChild(node, (child) => walk(child, visit));\n}\n","import type { NativeCandidateContext } from \"@stillwind/native\";\nimport type { PreparedSource } from \"@stillwind/projection\";\nimport ts from \"typescript-6\";\n\nimport type { PreviewSite } from \"../previews.ts\";\n\n/**\n * A literal in a compiler-recognized style input, with decoded-to-source boundaries.\n */\nexport interface UtilityLiteral {\n /** Prepared source whose original buffer owns all recorded boundaries. */\n source: PreparedSource;\n /** Literal token in the source's checker AST, which may use projected text. */\n node: ts.StringLiteralLike | ts.TemplateLiteralToken;\n /** Decoded literal content without delimiters or enclosing group variants. */\n text: string;\n /** Variants supplied by surrounding named style groups, including trailing colons. */\n prefix: string;\n /** Input role that selects completion registries, validation, and permitted variants. */\n context: NativeCandidateContext;\n /**\n * Captured occurrence whose native plan retains original UTF-8 ranges.\n * Syntactically recognized incomplete input can have a context without a site.\n */\n site?: PreviewSite;\n /**\n * Original UTF-16 boundaries for every position in `text`, including its end.\n * The array has `text.length + 1` entries. One escape that emits several code units\n * can give several decoded positions the same source boundary.\n */\n boundaries: readonly number[];\n}\n\n/**\n * Decodes JS literal content while mapping every decoded position to its source spelling.\n * CR and CRLF become LF. Escaped line continuations emit no text and move the preceding\n * boundary past the continuation. The caller must compare the result with the AST's decoded text.\n *\n * @param raw - Literal content without its opening delimiter or closing delimiter/interpolation.\n * @param start - Original UTF-16 offset of the first code unit in `raw`.\n * @returns Decoded text and `text.length + 1` source boundaries, or undefined for a trailing\n * backslash, invalid hex digits, a missing Unicode brace, or a code point above U+10FFFF.\n */\nexport function decodeLiteral(\n raw: string,\n start: number,\n):\n | {\n /** Decoded content. Literal line endings are normalized to LF. */\n text: string;\n /** Original UTF-16 offsets for every decoded position, including the end. */\n boundaries: readonly number[];\n }\n | undefined {\n let text = \"\";\n const boundaries = [start];\n for (let index = 0; index < raw.length;) {\n const begin = index;\n let value = raw[index++];\n if (value === \"\\\\\") {\n const escape = raw[index++];\n if (escape === undefined) {\n return undefined;\n }\n if (escape === \"\\n\" || escape === \"\\r\") {\n if (escape === \"\\r\" && raw[index] === \"\\n\") {\n index++;\n }\n boundaries[boundaries.length - 1] = start + index;\n continue;\n }\n if (escape === \"x\" || escape === \"u\") {\n const brace = escape === \"u\" && raw[index] === \"{\";\n const end = brace ? raw.indexOf(\"}\", index + 1) : index + (escape === \"x\" ? 2 : 4);\n const digits = raw.slice(index + (brace ? 1 : 0), end);\n if (end < index || !/^[\\da-f]+$/i.test(digits)) {\n return undefined;\n }\n const point = Number.parseInt(digits, 16);\n if (point > 0x10ffff) {\n return undefined;\n }\n value = String.fromCodePoint(point);\n index = end + (brace ? 1 : 0);\n } else {\n const escapes: Record<string, string> = {\n n: \"\\n\",\n r: \"\\r\",\n t: \"\\t\",\n b: \"\\b\",\n f: \"\\f\",\n v: \"\\v\",\n \"0\": \"\\0\",\n };\n value = escapes[escape] ?? escape;\n }\n } else if (value === \"\\r\") {\n if (raw[index] === \"\\n\") {\n index++;\n }\n value = \"\\n\";\n }\n text += value;\n for (let unit = 1; unit <= value.length; unit++) {\n boundaries.push(start + (unit === value.length ? index : begin));\n }\n }\n return {\n text,\n boundaries,\n };\n}\n","import type {\n NativeAssetRecord,\n NativeCandidateContext,\n NativeLintComment,\n NativeProjectSession,\n} from \"@stillwind/native\";\nimport type { PreparedSource } from \"@stillwind/projection\";\nimport ts from \"typescript-6\";\n\nimport type { ModuleAnalysis } from \"../../compilation/request.ts\";\nimport { GeneratedPreviews, type PreviewSite } from \"../previews.ts\";\nimport { SourceBindings, walk } from \"./bindings.ts\";\nimport { decodeLiteral, type UtilityLiteral } from \"./literal.ts\";\nimport { classifyInput, type InputOrder } from \"./order.ts\";\n\n/**\n * An array, argument list, or object written directly in a style input.\n */\nexport interface StyleInputContainer {\n /** Prepared source whose original text supplies the inputs to reorder. */\n source: PreparedSource;\n /** Checker AST node. Use `SourceIndex.range` to obtain original document coordinates. */\n node: ts.ArrayLiteralExpression | ts.CallExpression | ts.ObjectLiteralExpression;\n}\n\n/**\n * Indexes utility literals and sortable inputs in a fixed source graph.\n */\nexport class SourceIndex {\n /** Generated occurrences and replacement plans captured from the same source graph. */\n readonly previews: GeneratedPreviews;\n\n /** Indexed literals in discovery order, with fixed source boundaries. */\n readonly literals: readonly Readonly<UtilityLiteral>[];\n\n readonly #literals: UtilityLiteral[] = [];\n\n /** Fixed direct inputs eligible for grouping, including nested containers. */\n readonly containers: readonly Readonly<StyleInputContainer>[];\n\n readonly #containers: StyleInputContainer[] = [];\n\n /** Binder and source ranges shared by all indexed inputs. */\n readonly #bindings: SourceBindings;\n\n /**\n * Captures generated previews, rescans graph sources for producer records, and binds aliases.\n * Checker ASTs use projected text when present. Editor ranges address original buffers.\n * Source scanning updates the session's source registry and can replace reports for a failed scan.\n *\n * @param graph - Original buffers and resolved dependencies for the analyzed source revisions.\n * Its prepared sources must remain unchanged while the index is used.\n * @param session - Session whose analyses for modules match these revisions. Captures are taken\n * before rescanning, and later queries use the captured plans and the in-memory ASTs.\n * @param modules - Module IDs successfully compiled from these buffers. Failed scans have no capture.\n * @throws If source transport, a projection map, or an original UTF-8 boundary is invalid.\n */\n constructor(\n graph: Pick<ModuleAnalysis, \"sources\" | \"dependencies\">,\n session: NativeProjectSession,\n modules: readonly string[],\n ) {\n this.previews = new GeneratedPreviews(graph, session, modules);\n this.#bindings = new SourceBindings(graph, session);\n\n for (const { source, ast } of this.#bindings.files.values()) {\n walk(ast, (node) => {\n if (!ts.isCallExpression(node)) {\n return;\n }\n\n const asset = this.asset(source, node);\n if (asset?.identity.kind === \"style\" || this.#bindings.styleImport(node.expression)) {\n if (node.arguments.length > 1) {\n this.#containers.push({\n source,\n node,\n });\n }\n for (const argument of node.arguments) {\n this.#input(source, argument);\n }\n return;\n }\n if (\n asset?.identity.kind === \"keyframes\" ||\n this.#bindings.producer(node.expression, \"keyframes\")\n ) {\n this.#keyframes(source, node.arguments[0]);\n return;\n }\n if (\n asset?.identity.kind === \"viewTransition\" ||\n this.#bindings.producer(node.expression, \"viewTransition\")\n ) {\n const body = node.arguments[0];\n if (body && ts.isObjectLiteralExpression(body)) {\n for (const property of body.properties) {\n if (!ts.isPropertyAssignment(property) || ts.isComputedPropertyName(property.name)) {\n continue;\n }\n const name = ts.isStringLiteralLike(property.name)\n ? property.name.text\n : property.name.getText();\n if (\n [\"group\", \"old\", \"new\", \"imagePair\"].includes(name) &&\n ts.isStringLiteralLike(property.initializer)\n ) {\n this.#literal(source, property.initializer, \"\", \"viewTransitionUtilities\");\n }\n }\n }\n return;\n }\n if (this.#bindings.producer(node.expression, \"css\")) {\n const inputs = [...node.arguments];\n const options = inputs.at(-1);\n const anchored =\n options !== undefined &&\n isCssOptions(options) &&\n options.properties.some(\n (property) =>\n ts.isPropertyAssignment(property) && propertyName(property) === \"selector\",\n );\n if (options !== undefined && isCssOptions(options)) {\n inputs.pop();\n for (const property of options.properties) {\n if (\n ts.isPropertyAssignment(property) &&\n propertyName(property) === \"template\" &&\n ts.isStringLiteralLike(property.initializer)\n ) {\n this.#literal(source, property.initializer, \"\", \"cssTemplate\");\n }\n }\n }\n for (const input of inputs) {\n this.#cssInput(source, input, \"\", anchored ? \"anchoredDocument\" : \"document\");\n }\n return;\n }\n if (this.#bindings.producer(node.expression, \"media\")) {\n for (const argument of node.arguments) {\n if (ts.isStringLiteralLike(argument)) {\n this.#literal(source, argument, \"\", \"mediaVariants\");\n }\n }\n return;\n }\n if (this.asset(source, node.expression)?.identity.kind === \"keyframes\") {\n const options = node.arguments[0];\n if (options && ts.isStringLiteralLike(options)) {\n this.#literal(source, options, \"\", \"animationOptions\");\n }\n }\n });\n\n walk(ast, (node) => {\n if (!ts.isStringLiteralLike(node) && !ts.isTemplateLiteralToken(node)) {\n return;\n }\n const range = this.range(source, node);\n const site = range && this.previews.input(source, ...range);\n if (site?.native.context) {\n this.#literal(source, node, \"\", site.native.context, site);\n }\n });\n }\n\n this.literals = this.#literals;\n this.containers = this.#containers;\n }\n\n /**\n * Indexes literal frame utilities and quoted condition keys in an authored keyframes body.\n * Nested object bodies retain definition contexts. Computed properties, nonliteral frame\n * values, and missing bodies add no literals.\n *\n * @param source - Prepared source stored in this index.\n * @param node - Body in that source's checker AST, or undefined for a missing argument.\n * Recognized quoted conditions and frame utilities are appended to `literals`.\n */\n #keyframes(source: PreparedSource, node: ts.Node | undefined): void {\n if (!node || !ts.isObjectLiteralExpression(node)) {\n return;\n }\n\n for (const property of node.properties) {\n if (!ts.isPropertyAssignment(property) || ts.isComputedPropertyName(property.name)) {\n continue;\n }\n\n const name = ts.isStringLiteralLike(property.name)\n ? property.name.text\n : property.name.getText();\n if (name.endsWith(\":\") || ts.isObjectLiteralExpression(property.initializer)) {\n if (ts.isStringLiteralLike(property.name)) {\n this.#literal(source, property.name, \"\", \"definitionVariants\");\n }\n this.#keyframes(source, property.initializer);\n } else if (\n /^(?:from|to|(?:\\d+(?:\\.\\d+)?%)(?:\\s*,\\s*\\d+(?:\\.\\d+)?%)*)$/.test(name) &&\n ts.isStringLiteralLike(property.initializer)\n ) {\n this.#literal(source, property.initializer, \"\", \"keyframesFrame\");\n }\n }\n }\n\n /**\n * Classifies direct input syntax and bound identities without reading base bodies or CSS.\n * Arrays and objects receive a category only when all children share one non-ref category.\n *\n * @param source - Prepared source stored in this index.\n * @param node - Input or property in that source's checker AST.\n * @returns The grouping category, or a barrier for unknown, mixed, empty, or computed input.\n * Ref markers and supported projection calls share the declaration's opaque identity.\n */\n inputOrder(source: PreparedSource, node: ts.Node): InputOrder {\n return classifyInput(source, node, (source, node) => this.asset(source, node));\n }\n\n /**\n * Maps a checker node to an exact range in its original document.\n * For projections, an anchor is accepted only when the intervening and selected text match\n * the original buffer. A conflicting mapping at the node's start prevents fallback to an anchor.\n *\n * @param source - Prepared source whose checker AST contains `node`.\n * @param node - Node from this index, with leading trivia excluded from its selected range.\n * @returns Inclusive start and exclusive end in original UTF-16 coordinates, or undefined\n * when a projection cannot map the text exactly.\n */\n range(source: PreparedSource, node: ts.Node): [number, number] | undefined {\n return this.#bindings.range(source, node);\n }\n\n /**\n * Resolves a native producer or an alias through stable variable initializers and imports.\n * Both successful resolutions and misses are cached for the AST node.\n *\n * @param source - Prepared source whose checker AST contains `node`.\n * @param node - Node from this index. Alias chains may reach another source in the same graph.\n * @returns A shared native record that callers must keep unchanged, or undefined when no\n * producer is found. Mutated bindings and cyclic aliases stop alias resolution.\n */\n asset(source: PreparedSource, node: ts.Node): NativeAssetRecord | undefined {\n return this.#bindings.asset(source, node);\n }\n\n /**\n * Returns the comments that contain `swlint-*` directives in `source`'s original buffer.\n *\n * @param source - Prepared source of this index.\n * @returns Comment bodies in original UTF-8 byte offsets, or an empty list when the scan\n * failed. Callers must keep the returned list unchanged.\n */\n lintComments(source: PreparedSource): NativeLintComment[] {\n return this.#bindings.lintComments(source);\n }\n\n /**\n * Finds a captured expression contribution at `node` in `source`'s checker AST.\n * Exact non-input ranges take precedence; calls then try their receiver's use site.\n * Invalid sites remain identifiable.\n *\n * @param source - Prepared source whose checker AST contains `node`.\n * @param node - Expression or call in this index.\n * @returns A shared captured occurrence, or undefined for unmapped or unrecognized expressions.\n * Callers must keep the returned site unchanged.\n */\n previewSite(source: PreparedSource, node: ts.Node): PreviewSite | undefined {\n const range = this.range(source, node);\n if (!range) {\n return undefined;\n }\n\n const sites = this.previews.sites(source);\n const exact = sites.find(\n (site) => site.native.kind !== \"input\" && site.start === range[0] && site.end === range[1],\n );\n if (exact || !ts.isCallExpression(node)) {\n return exact;\n }\n\n const receiver = ts.isPropertyAccessExpression(node.expression)\n ? node.expression.expression\n : node.expression;\n const receiverRange = this.range(source, receiver);\n return receiverRange\n ? sites.find(\n (site) =>\n site.native.kind === \"use\" &&\n site.start === receiverRange[0] &&\n site.end === receiverRange[1],\n )\n : undefined;\n }\n\n /**\n * Finds the smallest mapped AST node that contains an original document position.\n *\n * @param source - Prepared source whose checker filename selects a file in this index.\n * @param offset - Original UTF-16 cursor offset. Containment uses half-open ranges.\n * @returns The containing node, or undefined when the file is absent or no mapped node\n * contains the position. A position at a node's exclusive end does not select that node.\n */\n nodeAt(source: PreparedSource, offset: number): ts.Node | undefined {\n return this.#bindings.nodeAt(source, offset);\n }\n\n /**\n * Indexes the static utility literals of one `style.css()` input with their group keys.\n * Runtime values and computed keys add no literals.\n *\n * @param source - Prepared source stored in this index.\n * @param node - Input in that source's checker AST.\n * @param prefix - Variants of the enclosing groups, each ending in `:`.\n * @param context - Input role of the call: `anchoredDocument` when it has a `selector`\n * option, and `document` otherwise.\n */\n #cssInput(\n source: PreparedSource,\n node: ts.Node,\n prefix: string,\n context: \"document\" | \"anchoredDocument\",\n ): void {\n if (ts.isStringLiteralLike(node)) {\n this.#literal(source, node, prefix, context);\n return;\n }\n if (ts.isArrayLiteralExpression(node)) {\n for (const element of node.elements) {\n this.#cssInput(source, element, prefix, context);\n }\n return;\n }\n if (\n ts.isParenthesizedExpression(node) ||\n ts.isAsExpression(node) ||\n ts.isSatisfiesExpression(node)\n ) {\n this.#cssInput(source, node.expression, prefix, context);\n return;\n }\n if (ts.isObjectLiteralExpression(node)) {\n for (const property of node.properties) {\n if (!ts.isPropertyAssignment(property) || ts.isComputedPropertyName(property.name)) {\n continue;\n }\n const name = propertyName(property);\n if (name === \"\" || name.endsWith(\":\")) {\n this.#cssInput(\n source,\n property.initializer,\n name === \":\" ? prefix : prefix + name,\n context,\n );\n }\n }\n }\n }\n\n /**\n * Records literals and sortable containers in recognized direct style input syntax.\n * Arrays and both conditional branches are traversed. Logical `&&`, `||`, and `??`\n * expressions contribute only their right operand, and unrecognized syntax adds nothing.\n *\n * @param source - Prepared source whose checker AST contains `node`.\n * @param node - Input expression to inspect. Object properties ending in `:` contribute\n * their values under the accumulated group variants. The keys `\"\"` and `\":\"` add no variants.\n * @param prefix - Decoded enclosing variants, including trailing colons. Nested group\n * names are appended before their literals are recorded.\n */\n #input(source: PreparedSource, node: ts.Node, prefix = \"\"): void {\n if (ts.isStringLiteralLike(node)) {\n this.#literal(source, node, prefix);\n return;\n }\n if (ts.isTemplateExpression(node)) {\n this.#literal(source, node.head, prefix);\n for (const span of node.templateSpans) {\n this.#literal(source, span.literal, prefix);\n }\n return;\n }\n if (ts.isArrayLiteralExpression(node)) {\n this.#containers.push({\n source,\n node,\n });\n for (const element of node.elements) {\n this.#input(source, element, prefix);\n }\n return;\n }\n if (ts.isConditionalExpression(node)) {\n this.#input(source, node.whenTrue, prefix);\n this.#input(source, node.whenFalse, prefix);\n return;\n }\n if (\n ts.isBinaryExpression(node) &&\n [\n ts.SyntaxKind.AmpersandAmpersandToken,\n ts.SyntaxKind.BarBarToken,\n ts.SyntaxKind.QuestionQuestionToken,\n ].includes(node.operatorToken.kind)\n ) {\n this.#input(source, node.right, prefix);\n return;\n }\n if (\n ts.isParenthesizedExpression(node) ||\n ts.isAsExpression(node) ||\n ts.isSatisfiesExpression(node)\n ) {\n this.#input(source, node.expression, prefix);\n return;\n }\n if (ts.isElementAccessExpression(node) || ts.isPropertyAccessExpression(node)) {\n this.#table(source, node.expression, prefix);\n return;\n }\n if (ts.isObjectLiteralExpression(node)) {\n this.#containers.push({\n source,\n node,\n });\n for (const property of node.properties) {\n if (!ts.isPropertyAssignment(property) || ts.isComputedPropertyName(property.name)) {\n continue;\n }\n const name = ts.isStringLiteralLike(property.name)\n ? property.name.text\n : property.name.getText();\n if (name !== \"\" && !name.endsWith(\":\")) {\n continue;\n }\n this.#input(source, property.initializer, name === \":\" ? prefix : prefix + name);\n }\n }\n }\n\n /**\n * Records the literal values of an array or object literal that a style input indexes.\n * Literal spreads are traversed, and keys are not utilities. A table is not a sortable\n * container, because reordering its entries would change which entry an index selects.\n *\n * @param source - Prepared source whose checker AST contains `node`.\n * @param node - Receiver of the lookup. Other receivers add nothing.\n * @param prefix - Decoded enclosing group variants, including trailing colons.\n */\n #table(source: PreparedSource, node: ts.Node, prefix: string): void {\n while (\n ts.isParenthesizedExpression(node) ||\n ts.isAsExpression(node) ||\n ts.isSatisfiesExpression(node)\n ) {\n node = node.expression;\n }\n const values: ts.Node[] = ts.isArrayLiteralExpression(node) ? [...node.elements] : [];\n if (ts.isObjectLiteralExpression(node)) {\n for (const property of node.properties) {\n if (ts.isPropertyAssignment(property)) {\n values.push(property.initializer);\n } else if (ts.isSpreadAssignment(property)) {\n this.#table(source, property.expression, prefix);\n }\n }\n }\n for (const value of values) {\n if (ts.isSpreadElement(value)) {\n this.#table(source, value.expression, prefix);\n } else if (ts.isStringLiteralLike(value)) {\n this.#literal(source, value, prefix);\n }\n }\n }\n\n /**\n * Records decoded content and original UTF-16 boundaries for a literal in `source`'s AST.\n * A captured `site` overrides an existing entry's context and plan at the same content start.\n * Unmapped ranges or decoding that disagrees with the AST add nothing.\n *\n * @param source - Prepared source whose checker AST contains `node`.\n * @param node - String or template token whose raw spelling supplies the source boundaries.\n * @param prefix - Decoded enclosing group variants, including trailing colons.\n * @param context - Input role stored with a new entry. Defaults to ordinary utilities.\n * @param site - Optional captured input. An existing entry keeps its prefix and boundaries\n * when this site replaces its context and plan.\n */\n #literal(\n source: PreparedSource,\n node: UtilityLiteral[\"node\"],\n prefix: string,\n context: NativeCandidateContext = \"utility\",\n site?: PreviewSite,\n ): void {\n const range = this.range(source, node);\n if (!range) {\n return;\n }\n\n const raw = source.document.code.slice(...range);\n const suffix =\n ts.isTemplateHead(node) || ts.isTemplateMiddle(node) ? 2 : node.isUnterminated ? 0 : 1;\n const content = raw.slice(1, suffix ? -suffix : undefined);\n const decoded = decodeLiteral(content, range[0] + 1);\n if (decoded?.text === node.text) {\n const previous = this.#literals.find(\n (literal) => literal.source === source && literal.boundaries[0] === decoded.boundaries[0],\n );\n if (previous) {\n if (site) {\n previous.context = context;\n previous.site = site;\n }\n return;\n }\n\n this.#literals.push({\n source,\n node,\n prefix,\n context,\n site,\n ...decoded,\n });\n }\n }\n}\n\n/**\n * Returns the written name of a property with a literal or identifier key.\n *\n * @param property - Property assignment whose key is not computed.\n * @returns The decoded key text.\n */\nfunction propertyName(property: ts.PropertyAssignment): string {\n return ts.isStringLiteralLike(property.name) ? property.name.text : property.name.getText();\n}\n\n/**\n * Recognizes the options object of `style.css()`: an object literal whose properties\n * all have the name `template` or `selector`.\n *\n * @param node - Last argument of a `style.css()` call.\n * @returns Whether the compiler reads the argument as options rather than an input.\n */\nfunction isCssOptions(node: ts.Node): node is ts.ObjectLiteralExpression {\n return (\n ts.isObjectLiteralExpression(node) &&\n node.properties.length > 0 &&\n node.properties.every(\n (property) =>\n ts.isPropertyAssignment(property) &&\n !ts.isComputedPropertyName(property.name) &&\n [\"template\", \"selector\"].includes(propertyName(property)),\n )\n );\n}\n","import { CandidateQueries, segments } from \"./candidates.ts\";\nimport type { EditorColor } from \"./request.ts\";\n\n/**\n * Finds a spelling with an arbitrary color that preserves the candidate's variants, importance,\n * and modifier.\n * Existing opacity modifiers remain present, so their maximum opacity can prevent a replacement.\n * The emitted color must agree with every requested component within 2/255.\n *\n * @param text - Decoded candidate without enclosing group variants. Its current color must resolve.\n * @param outer - Enclosing decoded variants, including trailing colons, used when probing colors.\n * @param color - Finite sRGB components and effective alpha. Values are clamped to 0..1.\n * @param candidates - Query for the snapshot's design system, used to validate each proposed spelling.\n * @returns Decoded replacement text without `outer`, or undefined when the original color cannot\n * resolve or no supported spelling with an arbitrary color reproduces the requested components.\n * @throws If a matching utility definition has a malformed requirement.\n */\nexport function colorReplacement(\n text: string,\n outer: string,\n color: Pick<EditorColor, \"red\" | \"green\" | \"blue\" | \"alpha\">,\n candidates: CandidateQueries,\n): string | undefined {\n if (\n ![color.red, color.green, color.blue, color.alpha].every(Number.isFinite) ||\n !candidates.color(outer + text)\n ) {\n return undefined;\n }\n\n const parts = segments(text, \":\");\n const utility = parts.pop()!;\n const prefix = parts.length ? `${parts.join(\":\")}:` : \"\";\n const importance = utility.startsWith(\"!\") || utility.endsWith(\"!\") ? \"!\" : \"\";\n const [base, modifier] = segments(utility.replace(/^!|!$/g, \"\"), \"/\");\n const spellings: ((value: string) => string)[] = [];\n if (base.startsWith(\"[\") && base.endsWith(\"]\")) {\n const property = base.slice(1).split(\":\", 1)[0];\n spellings.push((value) => `[${property}:${value}]`);\n } else {\n for (let index = base.length - 1; index > 0; index--) {\n if (base[index] === \"-\") {\n const root = base.slice(0, index);\n spellings.push((value) => `${root}-[${value}]`);\n }\n }\n }\n\n const rgba = [color.red, color.green, color.blue, color.alpha].map((value) =>\n Math.min(1, Math.max(0, value)),\n );\n const rgb = rgba.slice(0, 3).map((value) => Math.round(value * 255));\n for (const spelling of spellings) {\n /**\n * Rebuilds a color candidate with its variants, importance, and opacity modifier preserved.\n *\n * @param value - CSS color encoded for an arbitrary utility value.\n * @returns A candidate using the current spelling, without the separately supplied outer variants.\n */\n const build = (value: string) =>\n `${prefix}${importance}${spelling(value)}${modifier ? `/${modifier}` : \"\"}`;\n const probe = candidates.color(outer + build(\"#ffffff\"));\n if (!probe || rgba[3] > probe[3] + 1 / 255) {\n continue;\n }\n\n const alpha = probe[3] ? rgba[3] / probe[3] : 1;\n const value =\n alpha >= 1\n ? `#${rgb.map((value) => value.toString(16).padStart(2, \"0\")).join(\"\")}`\n : `rgb(${rgb.join(\"_\")}_/_${Number(alpha.toFixed(4))})`;\n const candidate = build(value);\n const rendered = candidates.color(outer + candidate);\n if (rendered?.every((component, index) => Math.abs(component - rgba[index]) <= 2 / 255)) {\n return candidate;\n }\n }\n\n return undefined;\n}\n\n/**\n * Serializes a picker color as a CSS literal for one local reference replacement.\n *\n * @param color - Finite sRGB components and effective alpha, clamped to 0..1.\n * @returns A hex or rgb() literal, or undefined for nonfinite components.\n */\nexport function cssColor(\n color: Pick<EditorColor, \"red\" | \"green\" | \"blue\" | \"alpha\">,\n): string | undefined {\n const components = [color.red, color.green, color.blue, color.alpha];\n if (!components.every(Number.isFinite)) {\n return undefined;\n }\n\n const rgba = components.map((value) => Math.min(1, Math.max(0, value)));\n const rgb = rgba.slice(0, 3).map((value) => Math.round(value * 255));\n return rgba[3] === 1\n ? `#${rgb.map((value) => value.toString(16).padStart(2, \"0\")).join(\"\")}`\n : `rgb(${rgb.join(\" \")} / ${Number(rgba[3].toFixed(4))})`;\n}\n","import { segments } from \"./candidates.ts\";\n\n/**\n * Converts one empty arbitrary-value placeholder into an LSP snippet.\n * @param candidate - Decoded replacement text, including enclosing variants.\n * @param source - Encodes decoded text for its source string. CSS uses the unchanged text.\n * @returns A snippet with its first tab stop inside `[]`, or undefined without a placeholder.\n */\nexport function completionSnippet(\n candidate: string,\n source: (text: string) => string = (text) => text,\n): string | undefined {\n const text = candidate.endsWith(\":\") ? candidate.slice(0, -1) : candidate;\n const variant = segments(text, \":\").at(-1)!;\n const placeholder = variant.lastIndexOf(\"[]\");\n if (placeholder < 0) {\n return undefined;\n }\n const index = text.length - variant.length + placeholder;\n return `${escape(source(candidate.slice(0, index + 1)))}\\${1}${escape(source(candidate.slice(index + 1)))}\\${0}`;\n}\n\n/**\n * Converts the start of a modifiable marker's modifier into an LSP snippet.\n * @param label - Decoded marker name followed by `/`.\n * @param source - Encodes decoded text for its source string.\n * @returns A snippet that inserts `label` and selects a `name` placeholder after it.\n */\nexport function markerModifierSnippet(\n label: string,\n source: (text: string) => string = (text) => text,\n): string {\n return `${escape(source(label))}\\${1:name}`;\n}\n\nfunction escape(part: string): string {\n return part.replace(/[\\\\$}]/g, \"\\\\$&\");\n}\n","import type { PreviewOptions } from \"@stillwind/config\";\nimport type { NativeCandidateContext, NativeEditorQuery } from \"@stillwind/native\";\nimport type { PreparedSource } from \"@stillwind/projection\";\nimport ts from \"typescript-6\";\n\nimport type { PluginRuntime } from \"../../css/plugins/runtime.ts\";\nimport { CandidateQueries, markerDocumentation, segments } from \"../candidates.ts\";\nimport { colorReplacement } from \"../colors.ts\";\nimport { completionSnippet, markerModifierSnippet } from \"../completion.ts\";\nimport type { GeneratedPreview } from \"../previews.ts\";\nimport type { EditorRequest, EditorResult } from \"../request.ts\";\nimport { escapeContent } from \"../sort.ts\";\nimport { SourceIndex } from \"./inputs.ts\";\nimport type { UtilityLiteral } from \"./literal.ts\";\n\n/** Most catalog candidates that one completion request adds. */\nconst CATALOG_COMPLETIONS = 200;\n\n/**\n * Answers source completion, hover, and color queries using a captured editor snapshot.\n */\nexport class SourceQueries {\n /** Checker ASTs, stable aliases, and captured emission plans for the graph's sources. */\n readonly #index: SourceIndex;\n\n /** Native design system and effective lint policy captured during construction. */\n readonly #query: NativeEditorQuery;\n\n /** Candidate caches shared by all queries against this snapshot. */\n readonly #candidates: CandidateQueries;\n\n /** Dynamic-family candidates that plugins list for completion, sorted. */\n readonly #catalog: readonly string[];\n\n /** Plugin suggestions for editor inputs that {@link SourceQueries.prepare} loaded, keyed by input. */\n readonly #inputCatalogs = new Map<string, readonly string[]>();\n\n /** Fingerprint of captures, graph dependencies, and configuration used for lazy resolution. */\n readonly #revision: string;\n\n /** Comments added to formatted CSS previews. Omitted fields use native defaults. */\n readonly #annotations: PreviewOptions;\n\n /** Queries that include callback CSS for selected completions in this snapshot. */\n readonly #resolved = new Map<string, CandidateQueries>();\n\n /** Resolves completion CSS separately from the captured compiler session. */\n readonly #plugins: PluginRuntime | undefined;\n\n /**\n * Shares the snapshot's source index and candidate caches for completion, hover, and color queries.\n *\n * @param index - Fixed source graph and captured preview plans.\n * @param query - Native query for the same CSS definitions.\n * @param candidates - Candidate caches also used by sorting.\n * @param revision - Snapshot fingerprint copied into lazy completion requests.\n * @param annotations - Comments to add to CSS previews.\n * @param catalog - Plugin candidates available without callback execution.\n * @param plugins - Optional plugin runtime used for lazy suggestions and selected candidates.\n */\n constructor(\n index: SourceIndex,\n query: NativeEditorQuery,\n candidates: CandidateQueries,\n revision: string,\n annotations: PreviewOptions,\n catalog: readonly string[],\n plugins?: PluginRuntime,\n ) {\n this.#index = index;\n this.#query = query;\n this.#candidates = candidates;\n this.#revision = revision;\n this.#annotations = annotations;\n this.#catalog = catalog;\n this.#plugins = plugins;\n }\n\n /**\n * Loads plugin suggestions for a completion input, and callback-generated CSS for a selected\n * completion from this captured snapshot, so that a following {@link SourceQueries.query} can\n * use them. Other requests are ignored.\n *\n * @param source - Fixed source for this request, or undefined for an unknown document.\n * @param request - Editor request. A `completion` request loads the plugin suggestions for the\n * candidate at its cursor. A `resolve` request for this snapshot's revision loads CSS, once for\n * each candidate.\n * @throws If a plugin fails or the native loader rejects the generated CSS.\n */\n async prepare(source: PreparedSource | undefined, request: EditorRequest): Promise<void> {\n if (request.kind === \"completion\" && source && this.#plugins) {\n const input = this.#completionInput(source, request.offset);\n const partial =\n input && this.#catalogContext(input.literal.context)\n ? segments(input.literal.prefix + input.prefix, \":\").pop()!\n : \"\";\n if (partial && !this.#inputCatalogs.has(partial)) {\n this.#inputCatalogs.set(partial, await this.#plugins.catalog(partial));\n }\n }\n if (\n request.kind === \"resolve\" &&\n request.snapshot === this.#revision &&\n this.#plugins &&\n !this.#resolved.has(request.candidate)\n ) {\n this.#resolved.set(\n request.candidate,\n new CandidateQueries(await this.#plugins.query(request.candidate)),\n );\n }\n }\n\n /**\n * Answers a source completion, hover, resolution, or color request.\n *\n * @param source - Fixed source from this query's index.\n * @param request - Request with offsets in the original UTF-16 document.\n * @param result - Empty answer for the same source. This query fills its data fields.\n * @returns The supplied answer. Queries may fill caches but do not edit source text.\n * @throws If candidate resolution, CSS formatting, or native color queries fail.\n */\n query(\n source: PreparedSource,\n request: Exclude<EditorRequest, { kind: \"sort\" | \"fixes\" | \"definition\" | \"links\" }>,\n result: EditorResult,\n ): EditorResult {\n if (request.kind === \"resolve\") {\n const literal = this.#index.literals.find(\n (literal) => literal.source === source && literal.boundaries[0] === request.input,\n );\n const candidates = this.#resolved.get(request.candidate) ?? this.#candidates;\n const current = literal && request.snapshot === this.#revision;\n const css = current\n ? request.candidate.endsWith(\":\")\n ? candidates.variant(request.candidate, literal.context)\n : (this.#preview(literal, request.candidate.slice(literal.prefix.length)) ??\n candidates.preview(request.candidate, literal.context))\n : undefined;\n const marker = current ? candidates.marker(request.candidate, literal.context) : null;\n if (css || marker) {\n const formatted = css ? this.#query.formatCss(css, this.#annotations) : \"\";\n result.hover = {\n start: 0,\n end: 0,\n css: formatted,\n detail: css ? this.#candidates.detail(formatted) : \"marker class\",\n ...(marker\n ? {\n documentation: markerDocumentation(marker),\n }\n : {}),\n };\n }\n return result;\n }\n\n if (request.kind === \"previews\") {\n result.previews = this.#index.previews\n .sites(source)\n .filter((site) => site.native.kind !== \"input\")\n .flatMap((site) => {\n const preview = this.#index.previews.assemble(site.native);\n const range = {\n start: site.start,\n end: site.end,\n };\n if (!preview) {\n return [{ ...range, css: \"\", valid: false }];\n }\n return [\n {\n ...range,\n css: preview.css ? this.#query.formatCss(preview.css, this.#annotations) : \"\",\n valid: true,\n ...(preview.runtimeNames.length ? { runtimeNames: preview.runtimeNames } : {}),\n },\n ];\n })\n .sort((a, b) => a.start - b.start || b.end - a.end);\n let end = -1;\n // An enclosing occurrence includes the CSS of the references inside it.\n result.previews = result.previews.filter((preview) => {\n const outer = preview.end > end;\n end = Math.max(end, preview.end);\n return outer;\n });\n return result;\n }\n\n const tokens = this.#sourceTokens(source);\n if (request.kind === \"colors\") {\n result.colors = tokens.flatMap((token) => {\n if (!this.#colorInput(token.literal) || !this.#preview(token.literal, token.text)) {\n return [];\n }\n return this.#candidates\n .colors(token.literal.prefix + token.text)\n .map(({ scheme, ...color }) => ({\n start: token.start,\n end: token.end,\n ...color,\n ...(scheme ? { scheme } : {}),\n }));\n });\n return result;\n }\n\n if (request.kind === \"colorPresentation\") {\n const token = tokens.find(\n (token) => token.start === request.start && token.end === request.end,\n );\n if (!token || !this.#colorInput(token.literal)) {\n return result;\n }\n\n const candidate = colorReplacement(\n token.text,\n token.literal.prefix,\n request.color,\n this.#candidates,\n );\n if (candidate && this.#preview(token.literal, candidate)) {\n result.edits = [\n {\n start: token.start,\n end: token.end,\n newText: escapeContent(candidate, token.literal),\n },\n ];\n }\n return result;\n }\n\n const token = tokens.find(\n (token) => token.start <= request.offset && request.offset <= token.end,\n );\n if (request.kind === \"hover\") {\n if (token) {\n const css = this.#preview(token.literal, token.text);\n const marker = this.#candidates.marker(\n token.literal.prefix + token.text,\n token.literal.context,\n );\n if (css || marker) {\n result.hover = {\n start: token.start,\n end: token.end,\n css: css ? this.#query.formatCss(css, this.#annotations) : \"\",\n ...(marker\n ? {\n documentation: markerDocumentation(marker),\n }\n : {}),\n };\n }\n } else {\n result.hover = this.#expressionPreview(source, request.offset);\n }\n return result;\n }\n\n const input = this.#completionInput(source, request.offset);\n if (!input) {\n return result;\n }\n\n const { literal, start, end, prefix } = input;\n const native = this.#candidates\n .complete(literal.prefix + prefix, literal.context, request.snippets === true)\n .filter(\n ({ label, marker }) =>\n marker ||\n label.endsWith(\":\") ||\n !literal.site ||\n this.#preview(literal, label.slice(literal.prefix.length)),\n );\n const known = new Set(native.map(({ label }) => label));\n result.completions = [\n ...native,\n ...this.#catalogCompletions(literal.prefix + prefix, literal.context)\n .filter((candidate) => !known.has(candidate))\n .map((label) => ({\n label,\n marker: false,\n })),\n ].map(({ label: candidate, marker }) => {\n const label = candidate.slice(literal.prefix.length);\n const source = (text: string) => escapeContent(text, literal);\n return {\n label,\n candidate,\n input: literal.boundaries[0],\n snapshot: this.#revision,\n start,\n end,\n newText: escapeContent(label, literal),\n ...(marker ? { marker } : {}),\n snippet: !request.snippets\n ? undefined\n : marker && candidate.endsWith(\"/\")\n ? markerModifierSnippet(label, source)\n : candidate.endsWith(\":\")\n ? completionSnippet(label, source)\n : undefined,\n retrigger: candidate.endsWith(\":\") || candidate.endsWith(\"-\"),\n };\n });\n\n return result;\n }\n\n /**\n * Finds formatted CSS at an original UTF-16 `offset`, walking ancestors through the first call.\n * A captured occurrence takes precedence over a declaration reached through an alias. Its\n * missing or invalid output ends the search, preventing an enclosing partial preview.\n * Without a captured occurrence, the nearest expression with a resolvable declaration supplies\n * the fallback preview and range.\n *\n * @param source - Prepared source stored in this snapshot's index.\n * @param offset - Cursor offset in the original document's UTF-16 coordinates.\n * @returns Formatted CSS and its original range, or undefined when no complete preview is available.\n * @throws If the native formatter rejects the assembled CSS.\n */\n #expressionPreview(source: PreparedSource, offset: number): EditorResult[\"hover\"] {\n let node = this.#index.nodeAt(source, offset);\n let reference:\n | {\n /** Declaration preview reached through the nearest resolvable expression. */\n preview: GeneratedPreview;\n /** Inclusive start and exclusive end of that expression in original UTF-16 coordinates. */\n range: readonly [number, number];\n }\n | undefined;\n while (node) {\n const site = this.#index.previewSite(source, node);\n if (site) {\n const preview = this.#index.previews.preview(site.native);\n const range = this.#index.range(source, node);\n return preview && range\n ? {\n start: range[0],\n end: range[1],\n css: this.#query.formatCss(preview.css, this.#annotations),\n ...(preview.runtimeNames.length ? { runtimeNames: preview.runtimeNames } : {}),\n }\n : undefined;\n }\n if (!reference) {\n const asset = this.#index.asset(source, node);\n const preview = asset && this.#index.previews.previewIdentity(asset.identity);\n const range = this.#index.range(source, node);\n if (preview && range) {\n reference = {\n preview,\n range,\n };\n }\n }\n if (ts.isCallExpression(node)) {\n break;\n }\n node = node.parent;\n }\n return reference\n ? {\n start: reference.range[0],\n end: reference.range[1],\n css: this.#query.formatCss(reference.preview.css, this.#annotations),\n ...(reference.preview.runtimeNames.length\n ? {\n runtimeNames: reference.preview.runtimeNames,\n }\n : {}),\n }\n : undefined;\n }\n\n /**\n * Renders candidate text in a captured input plan or the standalone input registry.\n * A captured plan already retains those variants; a standalone query receives the prefix\n * explicitly. The original source remains unchanged.\n *\n * @param literal - Indexed literal that supplies the input role, enclosing variants, and plan.\n * @param candidate - Decoded text without the literal's enclosing group prefix.\n * @returns CSS for the replacement, or undefined for failed or unavailable emission.\n * @throws If a matching ordinary utility requirement is malformed in a standalone query.\n */\n #preview(literal: UtilityLiteral, candidate: string): string | undefined {\n if (literal.site) {\n return this.#index.previews.previewInput(\n literal.source,\n literal.site.native.start,\n candidate,\n );\n }\n return this.#candidates.preview(literal.prefix + candidate, literal.context) ?? undefined;\n }\n\n /**\n * Completes dynamic-family candidates that plugins list but compilation has not defined yet.\n *\n * @param text - Decoded partial candidate, including enclosing and written variants.\n * @param context - Input role of the literal. Only utility roles complete catalog names.\n * @returns Candidates with the written variants, for names that start with the partial\n * utility, at most {@link CATALOG_COMPLETIONS} of them in catalog order.\n */\n #catalogCompletions(text: string, context: NativeCandidateContext): string[] {\n if (!this.#catalogContext(context)) {\n return [];\n }\n const parts = segments(text, \":\");\n const partial = parts.pop()!;\n if (!partial) {\n return [];\n }\n const variants = parts.map((part) => `${part}:`).join(\"\");\n return [...new Set([...this.#catalog, ...(this.#inputCatalogs.get(partial) ?? [])])]\n .filter((name) => name.startsWith(partial))\n .slice(0, CATALOG_COMPLETIONS)\n .map((name) => variants + name);\n }\n\n /**\n * Reports whether an input role completes plugin catalog names.\n *\n * @param context - Input role of a literal.\n * @returns Whether the role accepts utilities.\n */\n #catalogContext(context: NativeCandidateContext): boolean {\n return [\"utility\", \"document\", \"anchoredDocument\"].includes(context);\n }\n\n /**\n * Lists the utility tokens of every literal in one source.\n *\n * @param source - Captured source.\n * @returns Tokens with their literals, in literal order.\n */\n #sourceTokens(source: PreparedSource) {\n return this.#index.literals\n .filter((literal) => literal.source === source)\n .flatMap((literal) =>\n this.#tokens(literal).map((token) => ({\n ...token,\n literal,\n })),\n );\n }\n\n /**\n * Finds the completion input at a cursor: the token that contains it, or an empty position in a\n * literal.\n *\n * @param source - Captured source.\n * @param offset - Original UTF-16 cursor offset.\n * @returns The literal, the replaced UTF-16 range, and the decoded text before the cursor, or\n * undefined outside every literal.\n */\n #completionInput(\n source: PreparedSource,\n offset: number,\n ): { literal: UtilityLiteral; start: number; end: number; prefix: string } | undefined {\n const token = this.#sourceTokens(source).find(\n (token) => token.start <= offset && offset <= token.end,\n );\n const literal =\n token?.literal ??\n this.#index.literals.find(\n (literal) =>\n literal.source === source &&\n literal.boundaries[0] <= offset &&\n offset <= literal.boundaries.at(-1)!,\n );\n if (!literal) {\n return undefined;\n }\n const start = token?.start ?? offset;\n const end = token?.end ?? offset;\n const decoded = literal.boundaries.findIndex((position) => position >= offset);\n const decodedStart = literal.boundaries.indexOf(start);\n return {\n literal,\n start,\n end,\n prefix: literal.text.slice(Math.max(0, decodedStart), Math.max(0, decoded)),\n };\n }\n\n /**\n * Allows color operations only for input roles that emit utility declarations.\n * Option and definition-prefix inputs use different value contracts.\n *\n * @param literal - Indexed literal whose context supplies the input role.\n * @returns Whether its role supports a utility candidate's concrete color and replacement.\n */\n #colorInput(literal: UtilityLiteral): boolean {\n return [\"utility\", \"keyframesFrame\", \"viewTransitionUtilities\"].includes(literal.context);\n }\n\n /**\n * Maps whitespace-separated decoded tokens to their exact original spellings.\n *\n * @param literal - Literal with one source boundary for every decoded UTF-16 position,\n * including the end. Whitespace is recognized by JavaScript's `\\S` regular expression.\n * @returns Tokens in source order, without trimming or decoding them again.\n */\n #tokens(literal: UtilityLiteral): {\n /** Decoded non-whitespace text without enclosing group variants. */\n text: string;\n /** Inclusive original UTF-16 offset of the token's source spelling. */\n start: number;\n /** Exclusive original UTF-16 offset of the token's source spelling. */\n end: number;\n }[] {\n return [...literal.text.matchAll(/\\S+/gu)].map((match) => ({\n text: match[0],\n start: literal.boundaries[match.index],\n end: literal.boundaries[match.index + match[0].length],\n }));\n }\n}\n","import type {\n BaseConfig,\n LintSeverity,\n PreviewOptions,\n UtilitySortOptions,\n} from \"@stillwind/config\";\nimport {\n fingerprint,\n type BindingEdit,\n type BindingReport,\n type NativeDesignSystemLoader,\n type NativeEditorQuery,\n type NativeProjectSession,\n} from \"@stillwind/native\";\nimport type { PreparedSource } from \"@stillwind/projection\";\n\nimport { sourceKey } from \"../compilation/project.ts\";\nimport type { ModuleAnalysis } from \"../compilation/request.ts\";\nimport type { PluginRuntime } from \"../css/plugins/runtime.ts\";\nimport { pluginLoader } from \"../css/plugins/session.ts\";\nimport { CandidateQueries } from \"./candidates.ts\";\nimport { editorResult, type EditorEdit, type EditorRequest, type EditorResult } from \"./request.ts\";\nimport { sortSource } from \"./sort.ts\";\nimport { SourceIndex } from \"./source/inputs.ts\";\nimport { SourceQueries } from \"./source/query.ts\";\n\n/**\n * Runs source editor requests and sorting diagnostics against captured compiler output.\n */\nexport class EditorSnapshot {\n /** Owned source buffers and projection metadata captured before publication. */\n readonly #sources: readonly PreparedSource[];\n\n /** First fix actions from compilation reports, captured in original coordinates. */\n readonly #fixes: readonly (readonly BindingEdit[])[];\n\n /** Checker ASTs, stable aliases, and captured emission plans for the graph's sources. */\n readonly #index: SourceIndex;\n\n /** Native design system and effective lint policy captured during construction. */\n readonly #query: NativeEditorQuery;\n\n /** Candidate caches shared by all queries against this snapshot. */\n readonly #candidates: CandidateQueries;\n\n /** Targets for explicit sorting and sorting fixes. False disables both. */\n readonly #sort: Readonly<UtilitySortOptions> | false;\n\n /** Effective prefer-sorted-utilities severity. Off skips its diagnostics and sorting in fixes. */\n readonly #sortSeverity: LintSeverity;\n\n /** Sorting reports cached by full compiler module identity, including empty results. */\n readonly #reports = new Map<string, BindingReport[]>();\n\n /** Completion, hover, and color queries over the same captured sources. */\n readonly #queries: SourceQueries;\n\n /**\n * Captures recognized producers and compiler output for one set of source revisions.\n * Copies source metadata, dependencies, fix actions, and sorting settings before indexing them.\n * Building the source index also scans graph sources in the session.\n *\n * @param graph - Original sources, demanded dependencies, emitted CSS, and lint reports.\n * @param session - Session that compiled the graph and recognizes its producer identities.\n * @param loader - Completed design system with the same compiler options as the session.\n * @param config - Sorting targets and preview comments to capture. Effective lint policy comes\n * from the loader.\n * @param catalog - Finite plugin candidates offered without running their callbacks.\n * @param plugins - Runtime for resolving selected plugin completions without changing the session.\n * @throws If source transport, a projection map, or an original UTF-8 boundary is invalid.\n */\n constructor(\n graph: ModuleAnalysis,\n session: NativeProjectSession,\n loader: NativeDesignSystemLoader,\n config: BaseConfig & {\n preview?: PreviewOptions;\n },\n catalog: readonly string[] = [],\n plugins?: PluginRuntime,\n ) {\n const inputs = structuredClone({\n sources: graph.sources,\n dependencies: graph.dependencies,\n });\n this.#sources = inputs.sources;\n this.#fixes = structuredClone(graph.fixes);\n this.#index = new SourceIndex(\n inputs,\n session,\n graph.modules.map((module) => module.moduleId),\n );\n // Plugin definitions added during compilation live in the session's latest loader.\n this.#query = (pluginLoader(session) ?? loader).editorQuery();\n this.#candidates = new CandidateQueries(this.#query);\n const css = this.#query.lintSettings();\n this.#sort =\n config.sort === false\n ? false\n : {\n stringLiterals: config.sort?.stringLiterals ?? true,\n arrays: config.sort?.arrays ?? true,\n };\n this.#sortSeverity = (css[\"prefer-sorted-utilities\"] as LintSeverity) ?? \"off\";\n const annotations = {\n ...config.preview,\n };\n const revision = fingerprint(JSON.stringify([this.#index.previews.revision, config]));\n this.#queries = new SourceQueries(\n this.#index,\n this.#query,\n this.#candidates,\n revision,\n annotations,\n catalog,\n plugins,\n );\n }\n\n /**\n * Loads plugin suggestions for a completion input, and callback-generated CSS for a selected\n * completion from this captured snapshot, so that a following {@link EditorSnapshot.query} can\n * use them. Other requests are ignored.\n *\n * @param id - Full resolver identity of the requested source.\n * @param request - Editor request. A `completion` request loads the plugin suggestions for the\n * candidate at its cursor. A `resolve` request for this snapshot's revision loads CSS, once for\n * each candidate.\n * @throws If a plugin fails or the native loader rejects the generated CSS.\n */\n async prepare(id: string, request: EditorRequest): Promise<void> {\n const source = this.#sources.find((source) => sourceKey(source.resolverId) === sourceKey(id));\n await this.#queries.prepare(source, request);\n }\n\n /**\n * Computes sorting diagnostics for all graph sources and caches them by module identity.\n * Effective lint severity and source suppression determine which reports are returned.\n * Compilation reports already present in the graph remain separate.\n *\n * @returns Independent copies of sorting reports for the captured sources.\n * @throws If candidate ranking fails or native report construction rejects a source URI or range.\n */\n reports(): BindingReport[] {\n for (const source of this.#sources) {\n this.#lint(source);\n }\n return structuredClone([...this.#reports.values()].flat());\n }\n\n /**\n * Queries a source by resolver identity. Unknown or unmapped positions produce no data.\n * Queries may populate caches, and returned edits leave the original document unchanged.\n *\n * @param id - Full resolver identity captured in the graph, including any query suffix.\n * @param request - Operation and positions in the original document's UTF-16 coordinate space.\n * Completion resolution must reuse the candidate, input boundary, and snapshot fingerprint.\n * @returns Data with the original source fingerprint, or undefined for an unknown source.\n * A known source with no applicable answer returns a result with the relevant field absent or empty.\n * @throws If native candidate resolution, CSS formatting, or lint suppression checks fail.\n */\n query(id: string, request: EditorRequest): EditorResult | undefined {\n const source = this.#sources.find((source) => sourceKey(source.resolverId) === sourceKey(id));\n if (!source) {\n return undefined;\n }\n\n const result: EditorResult = editorResult(source.document.code);\n if (request.kind === \"definition\") {\n return {\n ...result,\n definitions: [],\n };\n }\n if (request.kind === \"links\") {\n return {\n ...result,\n links: [],\n };\n }\n if (request.kind === \"fixes\" || request.kind === \"sort\") {\n const seed =\n request.kind === \"fixes\"\n ? uniqueEdits(\n this.#fixes\n .filter((edits) =>\n edits.every(\n (edit) =>\n edit.location.uri === source.document.uri &&\n edit.location.revision === result.revision,\n ),\n )\n .flat()\n .map((edit) => ({\n start: edit.location.startUtf16,\n end: edit.location.endUtf16,\n newText: edit.replacement,\n })),\n )\n : [];\n result.edits =\n request.kind === \"sort\" || this.#sortSeverity !== \"off\"\n ? sortSource(\n source,\n this.#index,\n this.#candidates,\n this.#sort,\n seed,\n request.kind === \"sort\"\n ? request.protectedRanges?.length\n ? (start, end) =>\n !request.protectedRanges!.some(\n (range) => start < range.end && range.start < end,\n )\n : undefined\n : (start, end) =>\n !this.#query.lintSuppressed(\n source.document.code,\n bytes(source.document.code, start),\n bytes(source.document.code, end),\n \"prefer-sorted-utilities\",\n this.#index.lintComments(source),\n ),\n )\n : seed;\n return result;\n }\n return this.#queries.query(source, request, result);\n }\n\n /**\n * Computes sorting edits once and records reports through the native lint policy.\n * UTF-16 edit boundaries are converted to original UTF-8 byte ranges before reporting.\n * Empty results are cached too, and a failed computation leaves the module uncached.\n *\n * @param source - Unchanged prepared source stored in this snapshot's graph.\n * @throws If candidate ranking fails or native reporting rejects the source URI or byte ranges.\n */\n #lint(source: PreparedSource): void {\n if (this.#reports.has(source.moduleId)) {\n return;\n }\n\n const edits =\n this.#sortSeverity === \"off\"\n ? []\n : sortSource(source, this.#index, this.#candidates, this.#sort);\n const reports = this.#query.reportSortEdits(\n source.document.uri,\n source.document.code,\n edits.map((edit) => ({\n start: bytes(source.document.code, edit.start),\n end: bytes(source.document.code, edit.end),\n replacement: edit.newText,\n })),\n this.#index.lintComments(source),\n );\n this.#reports.set(source.moduleId, reports);\n }\n}\n\n/**\n * Converts an original document position to the native compiler's byte coordinates.\n *\n * @param text - Original source text whose encoding supplies the byte count.\n * @param offset - UTF-16 integer offset within `text`, at a Unicode scalar boundary.\n * The caller must ensure that the offset does not split a surrogate pair.\n * @returns Number of UTF-8 bytes before that position.\n */\nfunction bytes(text: string, offset: number): number {\n return new TextEncoder().encode(text.slice(0, offset)).length;\n}\n\n/**\n * Sorts the supplied array in place and greedily keeps edits that do not overlap earlier ones.\n *\n * @param edits - Edits in the same original UTF-16 coordinate space. The array is reordered by\n * start and then end. Earlier starts win, and a shorter edit wins when starts are equal.\n * @returns A new array of accepted edit objects. Touching ranges and identical zero-width\n * insertions are retained. The edit objects themselves remain unchanged.\n */\nfunction uniqueEdits(edits: EditorEdit[]): EditorEdit[] {\n const result: EditorEdit[] = [];\n for (const edit of edits.sort((a, b) => a.start - b.start || a.end - b.end)) {\n if (result.some((other) => other.start < edit.end && edit.start < other.end)) {\n continue;\n }\n result.push(edit);\n }\n return result;\n}\n","import type { PluginDirectoryEntry } from \"@stillwind/config\";\nimport { fingerprint, stylesheetPluginPaths } from \"@stillwind/native\";\nimport { dirname, isAbsolute, join, relative, resolve } from \"pathe\";\n\nimport type { EditorRequest, EditorResult } from \"../../editor/request.ts\";\n\n/**\n * A complete module specifier that an editor can insert into a CSS string.\n */\nexport interface PluginPathCompletion {\n specifier: string;\n kind: \"module\" | \"file\" | \"directory\";\n}\n\n/**\n * Lists immediate virtual children without reading the physical filesystem.\n *\n * @param files - Absolute file identities, including unsaved documents.\n * @param directory - Absolute directory whose immediate children are requested.\n * @param caseSensitive - Whether directory identity is case sensitive. Defaults to true.\n * @returns Files and inferred parent directories, each listed once.\n */\nexport function pluginDirectory(\n files: ReadonlyMap<string, unknown>,\n directory: string,\n caseSensitive = true,\n): PluginDirectoryEntry[] {\n const prefix = directory.replaceAll(\"\\\\\", \"/\").replace(/\\/$/, \"\") + \"/\";\n const key = (text: string) => (caseSensitive ? text : text.toLowerCase());\n const entries = new Map<string, PluginDirectoryEntry>();\n for (const file of files.keys()) {\n const path = file.replaceAll(\"\\\\\", \"/\");\n if (!key(path).startsWith(key(prefix))) {\n continue;\n }\n const tail = path.slice(prefix.length);\n const name = tail.split(\"/\", 1)[0];\n if (name) {\n entries.set(key(name), {\n name,\n directory: tail.includes(\"/\"),\n });\n }\n }\n return [...entries.values()];\n}\n\n/**\n * Completes local script files, directory prefixes, and package dependencies.\n *\n * @param prefix - Decoded specifier before the CSS cursor.\n * @param importer - Absolute stylesheet identity.\n * @param root - Project directory whose package manifest supplies package names.\n * @param host - Text reads and immediate directory entries from the same captured host.\n * @returns Complete specifiers in lexical order. Missing files and malformed manifests omit suggestions.\n */\nexport async function completePluginPaths(\n prefix: string,\n importer: string,\n root: string,\n host: {\n read(id: string): Promise<string>;\n directory(id: string): Promise<readonly PluginDirectoryEntry[]>;\n },\n): Promise<PluginPathCompletion[]> {\n const entries = new Map<string, PluginPathCompletion>();\n if (!prefix || prefix.startsWith(\".\") || prefix.startsWith(\"/\") || /^[A-Za-z]:\\//.test(prefix)) {\n const slash = prefix.lastIndexOf(\"/\");\n const before = slash < 0 ? \"./\" : prefix.slice(0, slash + 1);\n const partial = slash < 0 ? prefix : prefix.slice(slash + 1);\n const children = await host.directory(resolve(dirname(importer), before)).catch(() => []);\n for (const child of children) {\n if (\n !child.name.startsWith(partial) ||\n child.name === \".git\" ||\n (!child.directory &&\n (!/\\.[cm]?[jt]s$/i.test(child.name) || /\\.d\\.[cm]?ts$/i.test(child.name)))\n ) {\n continue;\n }\n const specifier = before + child.name + (child.directory ? \"/\" : \"\");\n entries.set(specifier, {\n specifier,\n kind: child.directory ? \"directory\" : \"file\",\n });\n }\n }\n if (!prefix.startsWith(\".\") && !prefix.startsWith(\"/\") && !/^[A-Za-z]:/.test(prefix)) {\n const packages = new Set<string>();\n for (const directory of new Set([dirname(importer), root])) {\n const metadata: unknown = await host\n .read(join(directory, \"package.json\"))\n .then(JSON.parse)\n .catch(() => undefined);\n if (!metadata || typeof metadata !== \"object\") {\n continue;\n }\n for (const key of [\n \"dependencies\",\n \"devDependencies\",\n \"peerDependencies\",\n \"optionalDependencies\",\n ]) {\n const dependencies = (metadata as Record<string, unknown>)[key];\n if (!dependencies || typeof dependencies !== \"object\" || Array.isArray(dependencies)) {\n continue;\n }\n for (const specifier of Object.keys(dependencies)) {\n packages.add(specifier);\n }\n }\n }\n for (const specifier of packages) {\n if (specifier.startsWith(prefix)) {\n entries.set(specifier, {\n specifier,\n kind: \"module\",\n });\n }\n if (!prefix.startsWith(specifier + \"/\")) {\n continue;\n }\n let base = dirname(importer);\n while (true) {\n const metadata: unknown = await host\n .read(join(base, \"node_modules\", specifier, \"package.json\"))\n .then(JSON.parse)\n .catch(() => undefined);\n if (metadata && typeof metadata === \"object\") {\n const exports = (metadata as Record<string, unknown>).exports;\n if (exports && typeof exports === \"object\" && !Array.isArray(exports)) {\n for (const [subpath, target] of Object.entries(exports)) {\n const name = specifier + subpath.slice(1);\n if (\n target !== null &&\n subpath.startsWith(\"./\") &&\n !subpath.includes(\"*\") &&\n name.startsWith(prefix)\n ) {\n entries.set(name, {\n specifier: name,\n kind: \"module\",\n });\n }\n }\n }\n break;\n }\n const parent = dirname(base);\n if (parent === base) {\n break;\n }\n base = parent;\n }\n }\n }\n return [...entries.values()].sort((a, b) =>\n a.specifier < b.specifier ? -1 : a.specifier > b.specifier ? 1 : 0,\n );\n}\n\n/**\n * Answers plugin path completion and links without loading or evaluating plugins.\n *\n * @param id - Absolute stylesheet identity inside the project root.\n * @param text - Captured original CSS, including incomplete strings.\n * @param request - Original UTF-16 editor operation.\n * @param options - Configured plugin names, project scope, resolver, and URI mapping.\n * @returns An answer for links or a selected plugin path, otherwise undefined.\n * Unresolved and configured-only names have links without targets. Their callers can suppress\n * ambiguous targets when overlapping projects disagree.\n */\nexport async function queryPluginPaths(\n id: string,\n text: string,\n request: EditorRequest,\n options: {\n root: string;\n names: readonly string[];\n host?: PluginPathHost;\n documentUri(id: string): string;\n },\n): Promise<EditorResult | undefined> {\n if (request.kind !== \"completion\" && request.kind !== \"resolve\" && request.kind !== \"links\") {\n return undefined;\n }\n const name = relative(options.root, id);\n if (name === \"..\" || name.startsWith(\"../\") || isAbsolute(name)) {\n return undefined;\n }\n const encoder = new TextEncoder();\n const bytes = encoder.encode(text);\n const utf16 = (offset: number) => new TextDecoder().decode(bytes.subarray(0, offset)).length;\n const offset =\n request.kind === \"completion\"\n ? request.offset\n : request.kind === \"resolve\"\n ? request.input\n : undefined;\n const paths = stylesheetPluginPaths(\n text,\n offset === undefined ? undefined : encoder.encode(text.slice(0, offset)).length,\n );\n const result: EditorResult = {\n revision: fingerprint(text),\n };\n const snapshot = fingerprint(JSON.stringify([text, options.root, options.names]));\n if (request.kind === \"links\") {\n result.links = await Promise.all(\n paths\n .filter((path) => path.closed)\n .map(async (path) => {\n const target = options.names.includes(path.specifier)\n ? undefined\n : await options.host?.resolve(path.specifier, id).catch(() => undefined);\n return {\n start: utf16(path.start),\n end: utf16(path.end),\n target: target ? options.documentUri(target) : undefined,\n };\n }),\n );\n return result;\n }\n const path = paths.find((path) => path.prefix != null);\n if (!path) {\n return undefined;\n }\n const prefix = path.prefix!;\n const available = new Map(\n ((await options.host?.complete?.(prefix, id, options.root).catch(() => [])) ?? []).map(\n (entry) => [entry.specifier, entry],\n ),\n );\n for (const specifier of options.names) {\n if (specifier.startsWith(prefix)) {\n available.set(specifier, {\n specifier,\n kind: \"module\",\n });\n }\n }\n const detail = (entry: PluginPathCompletion) =>\n options.names.includes(entry.specifier)\n ? \"Configured plugin\"\n : entry.kind === \"directory\"\n ? \"Directory\"\n : \"Plugin module\";\n if (request.kind === \"resolve\") {\n if (request.snapshot === snapshot && available.has(request.candidate)) {\n result.hover = {\n start: 0,\n end: 0,\n css: \"\",\n detail: detail(available.get(request.candidate)!),\n documentation: detail(available.get(request.candidate)!),\n };\n }\n return result;\n }\n result.completions = [...available.values()]\n .filter((entry) => entry.specifier.startsWith(prefix))\n .sort((a, b) => (a.specifier < b.specifier ? -1 : a.specifier > b.specifier ? 1 : 0))\n .map((entry) => ({\n start: utf16(path.start),\n end: utf16(path.end),\n label: entry.specifier,\n candidate: entry.specifier,\n input: request.offset,\n snapshot,\n newText:\n entry.specifier\n .replaceAll(\"\\\\\", \"\\\\\\\\\")\n .replaceAll(path.quote, \"\\\\\" + path.quote)\n .replace(/[\\n\\r\\f]/g, (character) => \"\\\\\" + character.charCodeAt(0).toString(16) + \" \") +\n (path.closed ? \"\" : path.quote),\n detail: detail(entry),\n category: entry.kind,\n retrigger: entry.kind === \"directory\",\n }));\n return result;\n}\n\n/**\n * File resolution and completion used by plugin path navigation. No plugin evaluation is required.\n */\nexport interface PluginPathHost {\n /**\n * Lists complete specifiers for an editor without evaluating their modules.\n *\n * @param prefix - Decoded path text before the CSS cursor.\n * @param importer - Absolute identity of the stylesheet containing the path.\n * @param root - Absolute project directory used to find package metadata.\n * @returns Full specifiers with trailing slashes for directory prefixes.\n */\n complete?(\n prefix: string,\n importer: string,\n root: string,\n ): Promise<readonly PluginPathCompletion[]>;\n\n /**\n * Resolves a module request for plugin file reads and editor navigation without evaluating it.\n *\n * @param specifier - Package specifier with an optional subpath, or a relative or absolute path.\n * @param importer - Resolved identity of the stylesheet that contains the statement.\n * @returns The resolved path, or undefined when the request does not resolve.\n */\n resolve(specifier: string, importer: string): Promise<string | undefined>;\n}\n","import type { BaseConfig, PreviewOptions } from \"@stillwind/config\";\nimport { fingerprint, type BindingReport, type NativeEditorQuery } from \"@stillwind/native\";\n\nimport { catalogInput } from \"../css/plugins/host.ts\";\nimport type { PluginRuntime } from \"../css/plugins/runtime.ts\";\nimport { CandidateQueries } from \"../editor/candidates.ts\";\nimport { colorReplacement, cssColor } from \"../editor/colors.ts\";\nimport { completionSnippet } from \"../editor/completion.ts\";\nimport type { EditorEdit, EditorRequest, EditorResult } from \"../editor/request.ts\";\n\n/** Answers semantic CSS queries and lint fixes from one original buffer and captured design system. */\nexport class StylesheetEditor {\n /** Resolver identity of the stylesheet. */\n readonly #id: string;\n /** Fingerprint of the captured stylesheet text that every report range addresses. */\n readonly #revision: string;\n /** Lint reports whose primary location is this stylesheet. */\n readonly #reports: readonly BindingReport[];\n /** Original buffer whose UTF-16 coordinates are exposed to callers. */\n readonly #text: string;\n /** UTF-8 encoding of the original buffer used to convert native byte ranges. */\n readonly #bytes: Uint8Array;\n /** Query pinned to the design system captured with this buffer. */\n readonly #query: NativeEditorQuery;\n /** Captured comment settings. Omitted fields use native preview defaults. */\n readonly #preview: PreviewOptions;\n /** Fingerprint of source, design-system revision, and serialized configuration for completion resolution. */\n readonly #snapshot: string;\n /** Caches variant previews and completion summaries for this buffer's captured design system. */\n readonly #candidates: CandidateQueries;\n /** Queries that include callback CSS for selected completions in this stylesheet. */\n readonly #resolved = new Map<string, NativeEditorQuery>();\n /** Finite plugin suggestions captured with this stylesheet's design system. */\n readonly #catalog: readonly string[];\n /** Plugin suggestions for editor inputs that {@link StylesheetEditor.prepare} loaded, keyed by input. */\n readonly #inputCatalogs = new Map<string, readonly string[]>();\n /** Resolves completion CSS without changing reports or a session's used utilities. */\n readonly #plugins: PluginRuntime | undefined;\n\n /**\n * Captures original text, lint reports, and query settings for one stylesheet revision.\n * Callers must load the original CSS graph before using sorting or lint fixes.\n * @param id - Resolver identity of the stylesheet.\n * @param text - Complete stylesheet text that the reports were computed from.\n * @param reports - Reports whose primary location is this stylesheet. Reports and edits are copied.\n * Use an empty array when the design system was loaded from recovered CSS.\n * @param query - Immutable design system captured for this source revision.\n * @param config - Compiler and preview settings included in completion identity.\n * @param catalog - Finite plugin candidates offered without running their callbacks.\n * @param plugins - Runtime for resolving selected plugin completions without changing used CSS.\n * @throws If reports cannot be cloned or configuration cannot be serialized.\n */\n constructor(\n id: string,\n text: string,\n reports: readonly BindingReport[],\n query: NativeEditorQuery,\n config: BaseConfig & {\n preview?: PreviewOptions;\n } = {},\n catalog: readonly string[] = [],\n plugins?: PluginRuntime,\n ) {\n this.#id = id;\n this.#catalog = catalog;\n this.#plugins = plugins;\n this.#revision = fingerprint(text);\n this.#reports = structuredClone(reports);\n this.#text = text;\n this.#bytes = new TextEncoder().encode(text);\n this.#query = query;\n this.#candidates = new CandidateQueries(query);\n this.#preview = { ...config.preview };\n this.#snapshot = fingerprint(JSON.stringify([text, query.revision(), config]));\n }\n\n /**\n * Loads plugin suggestions for a completion input, and resolves callback CSS for a selected\n * completion without changing the captured source or reports, so that a following query can\n * use them. Other requests are ignored.\n *\n * @param id - Resolver identity of the requested source. Another identity is ignored.\n * @param request - Editor request. A `completion` request, and a `resolve` request for this\n * stylesheet's completion snapshot, load the plugin suggestions for the candidate at their input.\n * A `resolve` request also loads CSS, once for each candidate. A variant completion is resolved\n * with its `:`.\n * @throws If a plugin fails or the native loader rejects the generated CSS.\n */\n async prepare(id: string, request: EditorRequest): Promise<void> {\n if (id !== this.#id) {\n return;\n }\n if (\n this.#plugins &&\n (request.kind === \"completion\" ||\n (request.kind === \"resolve\" &&\n request.snapshot ===\n this.#completionSnapshot(request.registryDirectives, request.snippets)))\n ) {\n const input = catalogInput(\n this.#text.slice(0, request.kind === \"completion\" ? request.offset : request.input),\n );\n if (input && !this.#inputCatalogs.has(input)) {\n this.#inputCatalogs.set(input, await this.#plugins.catalog(input));\n }\n }\n if (\n request.kind === \"resolve\" &&\n request.snapshot === this.#completionSnapshot(request.registryDirectives, request.snippets) &&\n this.#plugins &&\n !this.#resolved.has(request.candidate)\n ) {\n const variant = this.#query\n .completeStylesheet(this.#text, this.#byteOffset(request.input), {\n catalog: this.#catalogAt(request.input),\n })\n .some((item) => item.label === request.candidate && item.variant);\n this.#resolved.set(\n request.candidate,\n await this.#plugins.query(\n variant && !request.candidate.endsWith(\":\") ? `${request.candidate}:` : request.candidate,\n ),\n );\n }\n }\n\n /**\n * Answers completion, hover, definitions, colors, sorting, and lint-fix requests.\n *\n * @param id - Resolver identity of the requested source.\n * @param request - Operation in the stylesheet's original UTF-16 coordinates. Cursor offsets must\n * be character boundaries within the captured text. Resolve uses the label, input, and snapshot\n * returned by completion. Completion and resolution accept `registryDirectives` and `snippets`,\n * editor-only settings whose defaults are false. Resolve requires the same settings.\n * @returns An answer with the captured source fingerprint, or undefined for another identity.\n * Completion includes original replacement ranges. Hover includes formatted CSS or documentation\n * when the input resolves. Resolve omits hover when its snapshot or label no longer matches.\n * Fixes select each report's first action when all edits address this revision and do not overlap\n * a selected action, then sort edits by offset. Sort uses captured CSS targets independently of\n * lint reporting. Colors include original utility or reference ranges; presentations replace\n * only a currently recognized range in this buffer. Link requests return an empty array;\n * the project host resolves plugin paths.\n * @throws If a matching utility definition has a malformed requirement or CSS formatting fails.\n */\n query(id: string, request: EditorRequest): EditorResult | undefined {\n if (id !== this.#id) {\n return undefined;\n }\n\n const result: EditorResult = {\n revision: this.#revision,\n };\n if (request.kind === \"definition\") {\n const definition = this.#query.stylesheetDefinition(\n this.#text,\n this.#byteOffset(request.offset),\n );\n return {\n ...result,\n definitions: definition ? [definition] : [],\n };\n }\n if (request.kind === \"links\") {\n return {\n ...result,\n links: [],\n };\n }\n if (request.kind === \"colors\" || request.kind === \"colorPresentation\") {\n const colors = this.#query.stylesheetColors(this.#text).map(({ scheme, ...color }) => ({\n ...color,\n start: this.#utf16(color.start),\n end: this.#utf16(color.end),\n ...(scheme ? { scheme } : {}),\n }));\n if (request.kind === \"colors\") {\n result.colors = colors.map(({ candidate: _candidate, ...color }) => color);\n } else {\n const color = colors.find(\n (color) => color.start === request.start && color.end === request.end,\n );\n // Replacing one scheme's color would remove the other argument of `light-dark()`.\n if (color && !color.scheme) {\n const newText = color.candidate\n ? colorReplacement(\n color.candidate,\n \"\",\n request.color,\n new CandidateQueries(this.#query),\n )\n : cssColor(request.color);\n if (newText) {\n result.edits = [\n {\n start: color.start,\n end: color.end,\n newText,\n },\n ];\n }\n }\n }\n return result;\n }\n if (request.kind === \"completion\") {\n result.completions = this.#query\n .completeStylesheet(this.#text, this.#byteOffset(request.offset), {\n registryDirectives: request.registryDirectives === true,\n snippets: request.snippets === true,\n catalog: this.#catalogAt(request.offset),\n })\n .map((item) => ({\n start: this.#utf16(item.start),\n end: this.#utf16(item.end),\n label: item.label,\n candidate: item.label,\n newText: item.label,\n snippet: request.snippets && item.variant ? completionSnippet(item.label) : undefined,\n retrigger: item.label.endsWith(\":\") || (!item.keyword && item.label.endsWith(\"-\")),\n keyword: item.keyword,\n variant: item.variant,\n detail: item.detail ?? undefined,\n sortText: item.sortText ?? undefined,\n input: request.offset,\n snapshot: this.#completionSnapshot(request.registryDirectives, request.snippets),\n }));\n }\n if (request.kind === \"hover\") {\n result.hover = this.#hover(this.#text, request.offset);\n }\n if (\n request.kind === \"resolve\" &&\n request.snapshot === this.#completionSnapshot(request.registryDirectives, request.snippets)\n ) {\n const item = this.#query\n .completeStylesheet(this.#text, this.#byteOffset(request.input), {\n registryDirectives: request.registryDirectives === true,\n snippets: request.snippets === true,\n catalog: this.#catalogAt(request.input),\n })\n .find((item) => item.label === request.candidate);\n if (item) {\n const query = this.#resolved.get(request.candidate) ?? this.#query;\n const start = this.#utf16(item.start);\n const text =\n this.#text.slice(0, start) + item.label + this.#text.slice(this.#utf16(item.end));\n const variant =\n item.label.endsWith(\":\") && !item.keyword\n ? new CandidateQueries(query).variant(item.label, \"utility\")\n : undefined;\n const hover = variant\n ? {\n start: 0,\n end: 0,\n css: this.#query.formatCss(variant, this.#preview),\n }\n : this.#hover(text, start + item.label.length, query);\n if (hover) {\n result.hover = {\n ...hover,\n start: 0,\n end: 0,\n detail: this.#candidates.detail(hover.css),\n };\n }\n }\n }\n if (request.kind === \"sort\") {\n result.edits = this.#query\n .sortStylesheet(\n this.#text,\n request.protectedRanges?.map((range) => ({\n start: this.#byteOffset(range.start),\n end: this.#byteOffset(range.end),\n })),\n )\n .map((edit) => ({\n start: this.#utf16(edit.start),\n end: this.#utf16(edit.end),\n newText: edit.replacement,\n }));\n }\n if (request.kind === \"fixes\") {\n const edits: EditorEdit[] = [];\n for (const report of this.#reports) {\n const action = report.actions[0];\n if (!action?.edits.every((edit) => edit.location.revision === this.#revision)) {\n continue;\n }\n const proposed = action.edits.map((edit) => ({\n start: edit.location.startUtf16,\n end: edit.location.endUtf16,\n newText: edit.replacement,\n }));\n // An overlapping fix waits for the next pass, which analyzes the edited text again.\n if (\n proposed.some((edit) =>\n edits.some((other) => other.start < edit.end && edit.start < other.end),\n )\n ) {\n continue;\n }\n edits.push(...proposed);\n }\n edits.sort((a, b) => a.start - b.start || a.end - b.end);\n result.edits = edits;\n }\n return result;\n }\n\n /**\n * Pins completion resolution to the discovery and snippet settings used for its labels.\n * @param registryDirectives - Whether the request includes registry metadata.\n * @param snippets - Whether the client supports arbitrary variant snippets.\n * @returns A fingerprint of the captured snapshot and normalized editor settings.\n */\n #completionSnapshot(registryDirectives = false, snippets = false): string {\n return fingerprint(JSON.stringify([this.#snapshot, registryDirectives, snippets]));\n }\n\n /**\n * Returns the plugin suggestions for the candidate before a cursor.\n * @param offset - UTF-16 character boundary within the captured text.\n * @returns The finite catalog and the suggestions that {@link StylesheetEditor.prepare} loaded\n * for the candidate's input, without duplicates.\n */\n #catalogAt(offset: number): string[] {\n const input = catalogInput(this.#text.slice(0, offset));\n return [...new Set([...this.#catalog, ...(this.#inputCatalogs.get(input) ?? [])])];\n }\n\n /**\n * Converts a cursor in the original buffer to the native query's byte coordinates.\n * @param offset - UTF-16 character boundary within the captured text.\n * @returns The length in UTF-8 bytes of the text before the cursor.\n */\n #byteOffset(offset: number): number {\n return new TextEncoder().encode(this.#text.slice(0, offset)).length;\n }\n\n /**\n * Converts a native range boundary back to the original buffer's coordinates.\n * @param offset - UTF-8 character boundary within the captured bytes, returned by the native query.\n * @returns The UTF-16 offset at that boundary.\n */\n #utf16(offset: number): number {\n return new TextDecoder().decode(this.#bytes.subarray(0, offset)).length;\n }\n\n /**\n * Queries and formats a hover against original text or a completed copy of that text.\n * @param text - CSS buffer to query, including any synthetic completion replacement.\n * @param offset - UTF-16 character boundary within `text`.\n * @returns CSS and documentation at UTF-16 boundaries in `text`, or undefined for unresolved input.\n * Theme declarations retain their native spelling because the formatter expects complete rules.\n * @throws If candidate resolution or CSS formatting fails.\n */\n #hover(text: string, offset: number, query = this.#query): EditorResult[\"hover\"] {\n const encoder = new TextEncoder();\n const bytes = encoder.encode(text);\n const hover = query.hoverStylesheet(text, encoder.encode(text.slice(0, offset)).length);\n if (!hover) {\n return undefined;\n }\n\n const css = hover.css.startsWith(\"--\")\n ? hover.css\n : hover.css\n ? this.#query.formatCss(hover.css, this.#preview)\n : \"\";\n const decoder = new TextDecoder();\n return {\n start: decoder.decode(bytes.subarray(0, hover.start)).length,\n end: decoder.decode(bytes.subarray(0, hover.end)).length,\n css,\n documentation: hover.documentation || undefined,\n };\n }\n}\n","import {\n lintRules,\n normalizeCompilerConfig,\n type BaseConfig,\n type LintRule,\n} from \"@stillwind/config\";\nimport type { NativeCompilerOptions } from \"@stillwind/native\";\n\n/**\n * Selects the design-system stylesheet request.\n *\n * @param config - Compiler settings. css identifies the stylesheet.\n * @returns The authored path without resolving it. The caller applies the project root.\n * @throws If css does not supply a nonempty stylesheet path.\n */\nexport function cssEntrypoint(config: BaseConfig): string {\n const entry = config.css;\n if (!entry) {\n throw new Error(\"Stillwind requires a CSS-first entrypoint (`css`)\");\n }\n return entry;\n}\n\n/**\n * Applies host defaults to settings passed to a native design-system loader.\n *\n * @param config - Shared compiler settings. Naming callbacks are passed separately to sessions.\n * @returns Native loader options. CSS evaluation supplies utility and variant definitions.\n */\nexport function compilerOptions(config: BaseConfig): NativeCompilerOptions {\n const resolved = normalizeCompilerConfig(config);\n\n return {\n lint: {\n ...Object.fromEntries(\n Object.entries(resolved.lint.rules).map(([name, setting]) => [\n lintRules[name as LintRule].nativeName,\n setting,\n ]),\n ),\n checkLibraries:\n typeof resolved.lint.checkLibraries === \"boolean\"\n ? resolved.lint.checkLibraries\n : [...resolved.lint.checkLibraries],\n checkPlugins:\n typeof resolved.lint.checkPlugins === \"boolean\"\n ? resolved.lint.checkPlugins\n : [...resolved.lint.checkPlugins],\n },\n prefix: resolved.prefix,\n tailwindPrefix: resolved.tailwindPrefix,\n themePrefix: resolved.themePrefix,\n utilityOrder: resolved.utilityOrder,\n stylesheetSort: {\n applyUtilities: resolved.sort.applyUtilities,\n applyStatements: resolved.sort.applyStatements,\n variantBlocks: resolved.sort.variantBlocks,\n },\n target: resolved.target,\n classNamespace: resolved.classNamespace,\n useCssIf: resolved.useCssIf,\n namingRevision: resolved.namingRevision,\n hashLength: resolved.hashLength,\n rootFontSize: resolved.rootFontSize,\n };\n}\n"],"mappings":";;;;;;;;;AAiBA,MAAM,2BAAW,IAAI,QAA8C;;;;;;;;;;AAWnE,SAAgB,cACd,SACA,SACA,aAAa,GACP;CACN,IAAI,SAAS,SACX,SAAS,IAAI,SAAS;EACpB;EACA;CACF,CAAC;MAED,SAAS,OAAO,OAAO;AAE3B;;;;;;;;;;;;;;;;AAiBA,eAAsB,mBAMpB,SAA+B,SAAuB,QAAiC;CACvF,MAAM,UAAU,SAAS,IAAI,OAAO;CACpC,IAAI,CAAC,SACH,OAAO,QAAQ;;CAGjB,MAAM,aAAa;EACjB,MAAM,SAAS,QAAQ,QAAQ,OAAO,SAAS,IAAI;EACnD,QAAQ,OAAO,MAAM;EACrB,QAAQ,aAAa,QAAQ,QAAQ;EACrC,QAAQ,SAAS;CACnB;CACA,IAAI,QAAQ,aAAa,QAAQ,QAAQ,YACvC,KAAK;CAEP,IAAI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