@stillwind/host 0.6.0 → 0.8.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/dist/browser.js +8 -5
- package/dist/browser.js.map +1 -1
- package/dist/{configuration-CnrzO-F3.js → configuration-MQZe6ufN.js} +26 -8
- package/dist/configuration-MQZe6ufN.js.map +1 -0
- package/dist/index.js +12 -6
- package/dist/index.js.map +1 -1
- package/dist/{options-yvOsPpQU.js → options-PMjJ1c8W.js} +3 -3
- package/dist/{options-yvOsPpQU.js.map → options-PMjJ1c8W.js.map} +1 -1
- package/dist/{plugin-DvCyhK1k.js → plugin-CxD6forV.js} +2 -2
- package/dist/{plugin-DvCyhK1k.js.map → plugin-CxD6forV.js.map} +1 -1
- package/package.json +6 -5
- package/dist/configuration-CnrzO-F3.js.map +0 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/compilation/filesystem.ts","../src/compilation/finalize.ts","../src/compilation/source-map.ts","../src/css/css-source-map.ts","../src/semantics/node/project.ts","../src/semantics/node/facts.ts","../src/semantics/node/hidden-spawn.ts","../src/semantics/node/checker.ts","../src/semantics/node/decoder.ts","../src/semantics/node/service.ts","../src/project/diagnostic-map.ts","../src/project/analysis/host.ts","../src/project/analysis/project.ts","../src/project/editor.ts","../src/project/plugins.ts","../src/project/stylesheets.ts","../src/project/filesystem.ts","../src/project/workspace.ts"],"sourcesContent":["import { relative } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\n\nimport { cleanModuleId, fileSourceKind, type ModuleDescriptor } from \"./module-source.ts\";\n\n/**\n * Derives a compiler module identity relative to a filesystem root.\n *\n * @param root - Filesystem directory from which the identity is made relative.\n * @param id - Filesystem path to identify. Callers remove resolver queries before using this\n * helper.\n * @returns A relative path with forward slashes. Paths outside the root retain `..` segments. This\n * function does not enforce containment.\n */\nexport function compilerModuleId(root: string, id: string): string {\n return relative(root, id).replaceAll(\"\\\\\", \"/\");\n}\n\n/**\n * Infers parser metadata from a filesystem path and assigns compiler and checker identities.\n *\n * @param root - Project directory used for relative compiler identities.\n * @param id - Absolute source path, optionally followed by a query or fragment suffix.\n * @returns Metadata for the file after removing its query or fragment suffix.\n */\nexport function fileModuleDescriptor(root: string, id: string): ModuleDescriptor {\n const file = cleanModuleId(id);\n const { syntax, format } = fileSourceKind(file);\n return {\n moduleId: compilerModuleId(root, file),\n document: {\n uri: pathToFileURL(file).href,\n format,\n },\n checkerFileName: file,\n projectionFileName: file.replaceAll(\"\\\\\", \"/\"),\n syntax,\n };\n}\n","/**\n * Prepends an optional side-effect stylesheet import to compiled JavaScript.\n *\n * @param code - Compiled JavaScript text. The import is inserted before all existing text.\n * @param stylesheetSpecifier - Module specifier to import. Omission or an empty string leaves the\n * code unchanged.\n * @returns Final JavaScript text with the optional import and its following newline.\n */\nexport function finalizeModule(code: string, stylesheetSpecifier?: string): string {\n return finalizeModuleWithMap(code, stylesheetSpecifier).code;\n}\n\n/**\n * Half-open UTF-16 range removed from the compiled buffer during host finalization. The current\n * finalizer returns no removed ranges.\n */\nexport type FinalizedModuleEdit = {\n /** Inclusive UTF-16 offset in the compiled buffer before finalization. */\n from: number;\n /** Exclusive UTF-16 offset in that same buffer. */\n to: number;\n};\n\n/**\n * Finalizes compiled JavaScript and describes the inserted prefix for source-map generation.\n *\n * @param code - Compiled JavaScript before host finalization.\n * @param stylesheetSpecifier - Optional side-effect import specifier. A falsy value inserts no\n * import.\n * @returns Final code, the exact prefix inserted before it, and an empty list of removed ranges.\n */\nexport function finalizeModuleWithMap(code: string, stylesheetSpecifier?: string) {\n const stylesheetImport = stylesheetSpecifier\n ? `import ${JSON.stringify(stylesheetSpecifier)};\\n`\n : \"\";\n return {\n code: stylesheetImport + code,\n prefix: stylesheetImport,\n removed: [] as FinalizedModuleEdit[],\n };\n}\n","import { resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nimport {\n GenMapping,\n addSegment,\n setSourceContent,\n toEncodedMap,\n type EncodedSourceMap,\n} from \"@jridgewell/gen-mapping\";\nimport remapping, { type SourceMap } from \"@jridgewell/remapping\";\nimport { TraceMap, type SourceMapInput } from \"@jridgewell/trace-mapping\";\n\n/**\n * Traces framework output through a Stillwind transform when embedded source text identifies the\n * transformed input.\n *\n * @param generated - Framework output map.\n * @param original - Map or map chain from the Stillwind-transformed input back to original sources.\n * @param transformedSource - Exact text to match against the generated map's `sourcesContent`.\n * @returns A composed map. Only matching immediate sources are replaced. Other sources retain their\n * mappings.\n * @throws If a supplied source map cannot be decoded or composed.\n */\nexport function composeFrameworkSourceMap(\n generated: SourceMapInput,\n original: SourceMapInput | readonly SourceMapInput[],\n transformedSource: string,\n): SourceMap {\n const traced = new TraceMap(generated);\n const matches = new Set(\n traced.resolvedSources.filter(\n (_source, index) => traced.sourcesContent?.[index] === transformedSource,\n ),\n );\n return remapping(generated, (source, context) =>\n context.depth === 1 && matches.has(source) ? (original as SourceMapInput) : null,\n );\n}\n\n/**\n * Traces a CSS pipeline map through the original map of its carrier resource.\n *\n * @param generated - Pipeline output map, or a map chain accepted by the composition library.\n * @param original - Map or chain from the CSS carrier back to authored sources.\n * @param resource - Absolute carrier path with forward slashes. File URLs are decoded, and relative\n * source paths are resolved against the process working directory before comparison.\n * @returns A composed map that replaces only immediate sources resolving to the carrier path.\n * @throws If a supplied source map cannot be decoded or composed.\n */\nexport function composeCarrierSourceMap(\n generated: SourceMapInput | SourceMapInput[],\n original: SourceMapInput | readonly SourceMapInput[],\n resource: string,\n): SourceMap {\n return remapping(generated, (source, context) =>\n context.depth === 1 &&\n resolve(source.startsWith(\"file:\") ? fileURLToPath(source) : source).replaceAll(\"\\\\\", \"/\") ===\n resource\n ? (original as SourceMapInput)\n : null,\n );\n}\n\n/**\n * Map or ordered map chain from a module's input back to its original sources. Null and undefined\n * mean that no upstream map is available. Each map may be serialized or supplied as an object.\n */\nexport type UpstreamSourceMap = SourceMapInput | readonly SourceMapInput[] | undefined | null;\n\n/**\n * Composes the native output map with the upstream loader map or ordered map chain\n * describing its input. Without upstream, returns the generated object unchanged.\n * Invalid maps or incompatible chains may throw from the mapping library.\n *\n * @param generated - Map from compiled JavaScript back to the input received by Stillwind.\n * @param upstream - Optional map or ordered map chain from that input back to original sources.\n * @returns The generated map unchanged when no upstream map is supplied, otherwise a composed map.\n * @throws If map decoding fails or a supplied map chain is incompatible.\n */\nexport function composeModuleSourceMap(\n generated: EncodedSourceMap,\n upstream: UpstreamSourceMap,\n): EncodedSourceMap | SourceMap {\n return upstream\n ? remapping(\n [JSON.stringify(generated), ...(Array.isArray(upstream) ? upstream : [upstream])],\n () => null,\n )\n : generated;\n}\n\n/**\n * One compiler replacement before host finalization inserts a prefix or removes text.\n * All offsets are absolute UTF-16 code units in the original and compiled buffers.\n * Replacement gaps without expression intervals map to `originalStart`.\n */\nexport interface CompilerMapping {\n /** Inclusive original offset. Equals end for insertion. */\n originalStart: number;\n /** Exclusive original offset, at or after start. */\n originalEnd: number;\n /** Inclusive offset in the complete compiled buffer. */\n generatedStart: number;\n /** Exclusive compiled offset. Equals start for deletion. */\n generatedEnd: number;\n /**\n * Nonempty, nonoverlapping intervals contained in this replacement, sorted by\n * generated start. Source order may differ. Missing/empty means anchor-only mapping.\n */\n expressions?: {\n /** Inclusive original offset. The anchor for a nonexact interval. */\n originalStart: number;\n /** Exclusive original offset of the expression or encoded character. */\n originalEnd: number;\n /** Inclusive compiled offset, before host edits. */\n generatedStart: number;\n /** Exclusive compiled offset, strictly greater than start. */\n generatedEnd: number;\n /** True requires identical text/equal lengths. False anchors all units at original start. */\n exact: boolean;\n }[];\n}\n\n/**\n * Builds a JavaScript source map from compiler replacements and host finalization edits.\n *\n * Unchanged text maps character by character. Replacement text maps to its original start unless an\n * expression interval provides a more precise correspondence. All offsets use UTF-16 code units.\n *\n * @param source - Original source whose text is embedded in the map.\n * @param compiled - Compiler output before the host inserts a prefix or removes intervals.\n * @param id - Source identity used as the map's file and sole source name.\n * @param mappings - Nonoverlapping compiler replacements in generated-start order, with valid\n * original and generated ranges.\n * @param removed - Nonoverlapping ranges removed from `compiled`, in ascending order.\n * @param prefix - Exact text inserted before the retained compiler output. It advances generated\n * positions without receiving original mappings.\n * @returns An encoded version 3 map for the finalized output with original source content.\n */\nexport function moduleSourceMap(\n source: string,\n compiled: string,\n id: string,\n mappings: readonly CompilerMapping[],\n removed: readonly {\n /** Inclusive UTF-16 offset removed from compiled. */\n from: number;\n /** Exclusive UTF-16 offset in the same compiled buffer. */\n to: number;\n }[],\n prefix: string,\n): EncodedSourceMap {\n const map = new GenMapping({ file: id });\n setSourceContent(map, id, source);\n const lines = [0];\n for (let index = 0; index < source.length; index++) {\n if (source[index] === \"\\n\") {\n lines.push(index + 1);\n }\n }\n let line = prefix.split(\"\\n\").length - 1;\n let column = prefix.length - prefix.lastIndexOf(\"\\n\") - 1;\n let editIndex = 0;\n let removedIndex = 0;\n let expressionIndex = 0;\n let delta = 0;\n let originalLine = 0;\n for (let index = 0; index < compiled.length; index++) {\n while (removedIndex < removed.length && removed[removedIndex].to <= index) {\n removedIndex++;\n }\n if (removedIndex < removed.length && removed[removedIndex].from <= index) {\n continue;\n }\n while (editIndex < mappings.length && mappings[editIndex].generatedEnd <= index) {\n const edit = mappings[editIndex++];\n delta = edit.originalEnd - edit.generatedEnd;\n expressionIndex = 0;\n }\n const edit = mappings[editIndex];\n const expressions = edit?.expressions ?? [];\n while (\n expressionIndex < expressions.length &&\n expressions[expressionIndex].generatedEnd <= index\n ) {\n expressionIndex++;\n }\n const expression = expressions[expressionIndex];\n const original =\n expression && expression.generatedStart <= index\n ? expression.originalStart + (expression.exact ? index - expression.generatedStart : 0)\n : edit && edit.generatedStart <= index\n ? edit.originalStart\n : index + delta;\n // A folded record can jump backwards between distant source lines.\n if (\n original < lines[originalLine] ||\n (originalLine + 1 < lines.length && lines[originalLine + 1] <= original)\n ) {\n let low = 0;\n let high = lines.length;\n while (low < high) {\n const middle = (low + high) >>> 1;\n if (lines[middle] <= original) {\n low = middle + 1;\n } else {\n high = middle;\n }\n }\n originalLine = low - 1;\n }\n addSegment(map, line, column, id, originalLine, original - lines[originalLine]);\n if (compiled[index] === \"\\n\") {\n line++;\n column = 0;\n } else {\n column++;\n }\n }\n return toEncodedMap(map);\n}\n","import { isAbsolute, resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\n\nimport {\n GenMapping,\n addSegment,\n setSourceContent,\n toEncodedMap,\n type EncodedSourceMap,\n} from \"@jridgewell/gen-mapping\";\nimport remapping, { type SourceMap } from \"@jridgewell/remapping\";\nimport type { EncodedSourceMap as MutableEncodedSourceMap } from \"@jridgewell/trace-mapping\";\n\nimport { cssBannerPrefix } from \"./banners.ts\";\n\n/**\n * Producer map used to trace native CSS locations from a transformed script or component back to\n * its authored source.\n */\nexport interface CssUpstreamMap {\n /**\n * Producer filesystem identity used as the base for relative map sources. Ordinary query and\n * fragment suffixes may follow its path.\n */\n id: string;\n /** Exact source name in the native CSS map to which this producer map applies. */\n sourceMapSource: string;\n /** JSON text for an encoded version 3 map from producer input to authored sources. */\n map: string;\n}\n\n/**\n * Composes one producer map into the matching immediate source of a CSS map.\n *\n * Relative producer sources are resolved against its resource path and optional source root. Other\n * CSS sources keep their existing mappings.\n *\n * @param map - Encoded CSS map whose source names identify original producer inputs.\n * @param upstream - Optional producer map and the exact CSS source name to replace.\n * @returns The composed map, or the input map unchanged when upstream is absent or lacks a sources\n * array or nonempty mappings.\n * @throws If producer JSON, source URLs, or source-map composition are invalid.\n */\nfunction composeUpstream(\n map: EncodedSourceMap,\n upstream?: CssUpstreamMap,\n): EncodedSourceMap | SourceMap {\n if (!upstream) {\n return map;\n }\n const resource = pathToFileURL(resolve(upstream.id.split(/[?#]/, 1)[0])).href;\n const original = JSON.parse(upstream.map);\n if (!Array.isArray(original.sources) || !original.mappings) {\n return map;\n }\n /**\n * Resolves a map source while retaining its query and fragment.\n * @param source - Absolute path or URL reference. Backslashes are normalized to slashes.\n * @param base - Absolute URL used to resolve relative references.\n * @returns A file URL for an absolute path, or the resolved URL for another reference.\n * @throws If the reference or base cannot form a valid URL.\n */\n const sourceUrl = (source: string, base: string) => {\n const normalized = source.replaceAll(\"\\\\\", \"/\");\n const clean = normalized.split(/[?#]/, 1)[0];\n return isAbsolute(clean)\n ? pathToFileURL(clean).href + normalized.slice(clean.length)\n : new URL(normalized, base).href;\n };\n const base = original.sourceRoot\n ? sourceUrl(original.sourceRoot.replace(/\\/?$/, \"/\"), resource)\n : resource;\n original.sources = original.sources.map((source: string) => sourceUrl(source, base));\n delete original.sourceRoot;\n return remapping(JSON.stringify(map), (source, context) =>\n context.depth === 1 && source === upstream.sourceMapSource ? original : null,\n );\n}\n\n/**\n * Native locations linking generated CSS intervals to authored text. All interval offsets count\n * UTF-8 bytes before resource placeholders are replaced.\n */\nexport interface CssLocations {\n /** Source table indexed by each entry's `source` field. */\n sources: {\n /** Source identity recorded in the emitted version 3 map. */\n sourceMapSource: string;\n /**\n * Authored source text used to derive original lines, UTF-16 columns, and optional\n * `sourcesContent`.\n */\n content: string;\n }[];\n /**\n * Nonoverlapping generated CSS intervals. Rendering sorts them by generated start. Callers must\n * supply valid source indexes and byte boundaries.\n */\n entries: {\n /** Zero-based index into `sources` for the authored interval. */\n source: number;\n /** Inclusive UTF-8 byte offset in generated CSS before resource replacement. */\n generatedStart: number;\n /** Exclusive UTF-8 byte offset in that CSS, at or after `generatedStart`. */\n generatedEnd: number;\n /** Inclusive UTF-8 byte offset in the selected source's content. */\n originalStart: number;\n /** Exclusive UTF-8 byte offset in that content, at or after `originalStart`. */\n originalEnd: number;\n /**\n * True maps matching text byte for byte from `originalStart`. False maps the generated interval\n * to its original start.\n */\n exact: boolean;\n }[];\n}\n\n/** CSS and native source locations before resource URLs and upstream maps are composed. */\nexport interface CssSourceMapInput {\n /** Preserved notices selected for this CSS body. */\n banners?: readonly string[];\n /** Stylesheet text containing any unresolved resource placeholder tokens. */\n css: string;\n /** Native source locations whose generated offsets count UTF-8 bytes in `css`. */\n sourceMap: CssLocations;\n}\n\n/**\n * Rewrites resource placeholders while retaining native UTF-8 source locations.\n *\n * @param output - CSS and native source locations before resource replacement. Source indexes and\n * byte boundaries must be valid for the supplied CSS and authored text.\n * @param replacements - Resource placeholders mapped to escaped URL text.\n * @param upstream - Optional maps from producer input back to its original source, in composition order.\n * @param includeSourcesContent - Whether the inline map retains source text. Defaults to true.\n * @returns Resolved CSS with an inline version 3 map, or an empty string when the input CSS is empty.\n * @throws If an upstream map cannot be decoded, its source URLs are invalid, or composition fails.\n */\nexport function cssWithSourceMap(\n output: CssSourceMapInput,\n replacements: ReadonlyMap<string, string>,\n upstream?: CssUpstreamMap | readonly CssUpstreamMap[],\n includeSourcesContent = true,\n) {\n if (!output.css) {\n return \"\";\n }\n const { css, sourceMap } = output;\n const positions = sourceMap.sources.map(({ content }) => {\n const result = new Map<number, [number, number]>();\n let byte = 0;\n let line = 0;\n let column = 0;\n for (const char of content) {\n result.set(byte, [line, column]);\n byte += Buffer.byteLength(char);\n if (char === \"\\n\") {\n line++;\n column = 0;\n } else {\n column += char.length;\n }\n }\n result.set(byte, [line, column]);\n return result;\n });\n const names = sourceMap.sources.map(({ sourceMapSource }) => sourceMapSource);\n const map = new GenMapping();\n names.forEach((name, index) => setSourceContent(map, name, sourceMap.sources[index].content));\n let result = cssBannerPrefix(output.banners ?? []);\n let byte = 0;\n let line = result.match(/\\r\\n|\\r|\\n/g)?.length ?? 0;\n let column = result.split(\"\\n\").at(-1)!.length;\n let entryIndex = 0;\n const entries = [...sourceMap.entries].sort((a, b) => a.generatedStart - b.generatedStart);\n const edits = [...replacements];\n for (let offset = 0; offset < css.length;) {\n while (entryIndex < entries.length && entries[entryIndex].generatedEnd <= byte) {\n entryIndex++;\n }\n const entry = entries[entryIndex];\n const active = entry && entry.generatedStart <= byte ? entry : undefined;\n const replacement = edits.find(([placeholder]) => css.startsWith(placeholder, offset));\n const originalText = replacement?.[0] ?? String.fromCodePoint(css.codePointAt(offset)!);\n const emitted = replacement?.[1] ?? originalText;\n const position =\n active &&\n positions[active.source].get(\n active.originalStart + (active.exact ? byte - active.generatedStart : 0),\n );\n for (const char of emitted) {\n if (active && position) {\n addSegment(map, line, column, names[active.source], ...position);\n } else {\n addSegment(map, line, column);\n }\n if (char === \"\\n\") {\n line++;\n column = 0;\n } else {\n column += char.length;\n }\n }\n result += emitted;\n byte += Buffer.byteLength(originalText);\n offset += originalText.length;\n }\n return (\n result +\n \"\\n/*# sourceMappingURL=data:application/json;base64,\" +\n Buffer.from(\n JSON.stringify(\n (Array.isArray(upstream) ? upstream : [upstream]).reduce(\n (map, source) => composeUpstream(map, source),\n toEncodedMap(map),\n ),\n (key, value) => (key === \"sourcesContent\" && !includeSourcesContent ? undefined : value),\n ),\n ).toString(\"base64\") +\n \" */\"\n );\n}\n\n/** Stylesheet text and its decoded inline source map, ready for a bundler's CSS pipeline. */\nexport interface DecodedCssSourceMap {\n /** CSS with the recognized trailing inline source-map comment removed. */\n code: string;\n /**\n * Decoded version 3 map with mutable arrays and string source identities, or null when the CSS\n * has no recognized trailing map.\n */\n map:\n | (MutableEncodedSourceMap & {\n /** Source identities indexed by the decoded map's segments. */\n sources: string[];\n })\n | null;\n}\n\n/**\n * Decodes the trailing inline map emitted by `cssWithSourceMap` or a compatible CSS carrier.\n *\n * @param css - Stylesheet text. A recognized map must contain a base64-encoded version 3 JSON map\n * in the trailing comment format emitted by `cssWithSourceMap`.\n * @returns CSS and its decoded map. Without a recognized trailing map, the CSS is unchanged and\n * the map is null. JSON is decoded without validating its source-map fields.\n * @throws If a recognized inline map contains invalid JSON.\n */\nexport function decodeCssSourceMap(css: string): DecodedCssSourceMap {\n const match =\n /\\n\\/\\*# sourceMappingURL=data:application\\/json;base64,([A-Za-z0-9+/=]+) \\*\\/$/.exec(css);\n if (!match) {\n return {\n code: css,\n map: null,\n };\n }\n return {\n code: css.slice(0, match.index),\n map: JSON.parse(Buffer.from(match[1], \"base64\").toString(\"utf8\")) as NonNullable<\n DecodedCssSourceMap[\"map\"]\n >,\n };\n}\n","import { createHash } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport process from \"node:process\";\n\nimport type {\n NativeAssetRecord as AssetRecord,\n NativeIdentity as IdentityId,\n} from \"@stillwind/native\";\n\nimport { TypeFactsError, type TypeFactSource } from \"../backend.ts\";\nimport { CheckerSource, checkerId } from \"../checker-source.ts\";\n\n/**\n * Normalizes filesystem names used as keys in the virtual checker overlay.\n *\n * @param fileName - Absolute or relative filesystem path.\n * @returns An absolute path with forward slashes, lowercased on Windows to match case-insensitive\n * filesystem lookups.\n */\nexport const normalize = (fileName: string) => {\n const name = path.resolve(fileName).replaceAll(\"\\\\\", \"/\");\n return process.platform === \"win32\" ? name.toLowerCase() : name;\n};\n\n/**\n * Virtual project files, checker range mappings, and declaration identities prepared for one\n * collection request.\n */\nexport interface PreparedProject {\n /**\n * Normalized absolute filenames mapped to virtual text, including checker sources, helpers,\n * globals, and project configuration.\n */\n virtualFiles: Map<string, string>;\n /**\n * Checker buffers in source and buffer order, retaining the correspondence to original probes.\n */\n mappings: CheckerSource[];\n /**\n * Serialized identity keys collected from all checker buffers, mapped to their native\n * declarations.\n */\n identities: Map<string, IdentityId>;\n}\n\n/**\n * TypeScript settings inherited by the generated project used for semantic queries.\n */\nexport type TypeScriptProject =\n | {\n /** Selects settings inherited from a consumer tsconfig. */\n readonly kind: \"configured\";\n /** Absolute path to the consumer's tsconfig. */\n readonly configPath: string;\n }\n | {\n /** Selects Stillwind's defaults without a consumer tsconfig. */\n readonly kind: \"isolated\";\n };\n\n/**\n * Fixed filesystem and TypeScript settings shared by collections in one checker service.\n */\nexport interface TypeFactsEnvironment {\n /** Absolute directory used for checker resolution and generated configuration paths. */\n readonly root: string;\n /** Settings inherited by the checker. Isolated projects use Stillwind's compiler defaults. */\n readonly project: TypeScriptProject;\n}\n\n/**\n * Selects the TypeScript environment before starting a checker.\n *\n * @param root - Filesystem project directory, resolved to an absolute path.\n * @param tsconfig - Absolute or root-relative config path. Omission selects an existing root\n * `tsconfig.json`. False selects isolated defaults even when that file exists.\n * @returns Fixed settings without evaluating configuration or starting the checker.\n * @throws If an explicitly selected path is empty or its configuration file does not exist.\n */\nexport function resolveTypeFactsEnvironment(\n root: string,\n tsconfig?: string | false,\n): TypeFactsEnvironment {\n root = path.resolve(root);\n if (typeof tsconfig === \"string\" && !tsconfig.trim()) {\n throw new Error(\"TypeScript configuration path must not be empty\");\n }\n const configPath = path.resolve(root, typeof tsconfig === \"string\" ? tsconfig : \"tsconfig.json\");\n if (typeof tsconfig === \"string\" && !existsSync(configPath)) {\n throw new Error(`TypeScript configuration does not exist: ${configPath}`);\n }\n return {\n root,\n project:\n tsconfig !== false && existsSync(configPath)\n ? {\n kind: \"configured\",\n configPath,\n }\n : {\n kind: \"isolated\",\n },\n };\n}\n\n/**\n * File contents captured for one collection. Ambient declarations override overlays at matching\n * paths. Prepared checker sources and the generated configuration override both maps.\n */\nexport interface TypeFactsInputs {\n /** Absolute paths to replacement text. Files participate only when the checker references them. */\n overlayFiles?: ReadonlyMap<string, string>;\n /** Absolute declaration paths to text. Every supplied declaration becomes a project root file. */\n ambientDeclarations?: ReadonlyMap<string, string>;\n}\n\n/**\n * Builds checker sources and an in-memory project configuration for semantic queries.\n *\n * @param sources - Prepared sources with validated mappings, original probes, and dependency\n * resolutions.\n * @param assetsByModuleId - Native declaration records keyed by compiler module identity.\n * @param shadowTsconfigPath - Absolute filename of the generated in-memory TypeScript project.\n * @param project - Consumer configuration to inherit, or isolated compiler defaults.\n * @param inputs - Captured file replacements and declarations required by this collection.\n * @param configuredDeclarations - Declaration files selected by the consumer's tsconfig.\n * @returns Virtual text and range mappings without writing any files to disk.\n * @throws If checker edits or projection maps are invalid, or an original probe has no\n * checker-buffer correspondence.\n */\nexport function prepareProject(\n sources: readonly TypeFactSource[],\n assetsByModuleId: ReadonlyMap<string, readonly AssetRecord[]>,\n shadowTsconfigPath: string,\n project: TypeScriptProject,\n inputs: TypeFactsInputs,\n configuredDeclarations: readonly string[],\n): PreparedProject {\n const virtualFiles = new Map(\n [...(inputs.overlayFiles ?? []), ...(inputs.ambientDeclarations ?? [])].map(([name, text]) => [\n normalize(name),\n text,\n ]),\n );\n const mappings: CheckerSource[] = [];\n const allIdentities = new Map<string, IdentityId>();\n const globals = new Set<string>();\n const ids = new Map(sources.map((source) => [source.resolverId, checkerId(source)]));\n for (const source of sources) {\n const declarations = source.kind === \"projected\" && source.projection.checkerGlobals;\n if (declarations) {\n const fingerprint = createHash(\"sha256\").update(declarations).digest(\"hex\").slice(0, 16);\n const id = normalize(\n path.join(path.dirname(shadowTsconfigPath), `.stillwind-globals-${fingerprint}.d.ts`),\n );\n virtualFiles.set(id, declarations);\n globals.add(id);\n }\n const syntax = source.kind === \"direct\" ? source.syntax : source.projection.syntax;\n const buffers = source.checkerBuffers ?? [\n {\n source: source.kind === \"direct\" ? source.document.code : source.projection.code,\n language:\n syntax.language === \"tsx\" || syntax.language === \"jsx\"\n ? (\"tsx\" as const)\n : (\"ts\" as const),\n },\n ];\n for (const [index, buffer] of buffers.entries()) {\n const shadow = new CheckerSource(\n source,\n buffer,\n index,\n assetsByModuleId.get(source.moduleId) ?? [],\n ids,\n );\n virtualFiles.set(normalize(shadow.id), shadow.text);\n if (shadow.helperModule) {\n virtualFiles.set(normalize(shadow.helperModule.id), shadow.helperModule.text);\n }\n mappings.push(shadow);\n for (const [key, identity] of shadow.identities) {\n allIdentities.set(key, identity);\n }\n }\n for (const probe of source.probes) {\n if (\n !mappings.some(\n (mapping) =>\n mapping.source === source &&\n [...mapping.probes.values()].some(\n (candidate) => candidate.start === probe.start && candidate.end === probe.end,\n ),\n )\n ) {\n throw new TypeFactsError(\n source.moduleId,\n probe.start,\n probe.end,\n \"checker\",\n \"Cannot map this expression to a checker source\",\n );\n }\n }\n }\n virtualFiles.set(\n normalize(shadowTsconfigPath),\n JSON.stringify({\n ...(project.kind === \"configured\"\n ? {\n extends: project.configPath,\n }\n : {}),\n compilerOptions: {\n allowJs: true,\n checkJs: true,\n ...(project.kind === \"isolated\"\n ? {\n jsx: \"preserve\",\n module: \"esnext\",\n moduleResolution: \"bundler\",\n strict: true,\n target: \"esnext\",\n types: [],\n }\n : {}),\n noEmit: true,\n skipLibCheck: true,\n allowImportingTsExtensions: true,\n },\n files: [\n ...configuredDeclarations,\n ...[...(inputs.ambientDeclarations?.keys() ?? [])].map(normalize),\n ...globals,\n ...mappings.map((mapping) => mapping.id),\n ...new Set(sources.flatMap((source) => source.checkerTypes ?? [])),\n ],\n include: [],\n exclude: [],\n }),\n );\n return {\n virtualFiles,\n mappings,\n identities: allIdentities,\n };\n}\n","import type { NativeTypeFact as TypeFact } from \"@stillwind/native\";\nimport type { Node, SourceFile } from \"typescript-7/unstable/ast\";\nimport { isCallExpression } from \"typescript-7/unstable/ast/is\";\nimport type { Diagnostic, Type } from \"typescript-7/unstable/sync\";\n\nimport { TypeFactsError, type UnverifiedRange } from \"../backend.ts\";\nimport { CheckerSource } from \"../checker-source.ts\";\nimport type { AssetTypeDecoder } from \"./decoder.ts\";\n\n/**\n * Traverses a checker AST in preorder.\n *\n * @param node - Root visited before its descendants.\n * @param callback - Operation called once for the root and each child exposed by `forEachChild`.\n * Thrown errors stop traversal.\n */\nexport function visit(node: Node, callback: (node: Node) => void) {\n callback(node);\n node.forEachChild((child) => visit(child, callback));\n}\n\n/**\n * Flattens a checker diagnostic and its nested message chain for matching and display.\n *\n * @param diagnostic - Checker diagnostic with optional nested messages.\n * @returns Diagnostic text followed recursively by child messages, separated by newlines.\n */\nexport function diagnosticText(diagnostic: Diagnostic): string {\n return [diagnostic.text, ...(diagnostic.messageChain ?? []).map(diagnosticText)].join(\"\\n\");\n}\n\n/**\n * Tests whether a TypeScript argument error belongs to a style producer call.\n * Lowering reports unsupported macro arguments as lints, so these errors do not invalidate the\n * facts of the call. The operands still require valid facts.\n *\n * @param diagnostic - Checker diagnostic for `sourceFile`.\n * @param sourceFile - Checker source file that contains the diagnostic.\n * @param mapping - Producer call ranges of the same source.\n * @returns Whether the diagnostic is an argument error (TS2345 or TS2769) whose innermost\n * enclosing call is a recorded producer call.\n */\nexport function producerArgumentDiagnostic(\n diagnostic: Diagnostic,\n sourceFile: SourceFile,\n mapping: CheckerSource,\n): boolean {\n if (diagnostic.code !== 2345 && diagnostic.code !== 2769) {\n return false;\n }\n let owner: Node | undefined;\n visit(sourceFile, (node) => {\n if (\n isCallExpression(node) &&\n node.getStart(sourceFile) <= diagnostic.pos &&\n node.end >= diagnostic.end &&\n (!owner || node.end - node.getStart(sourceFile) < owner.end - owner.getStart(sourceFile))\n ) {\n owner = node;\n }\n });\n return !!owner && mapping.producers.has(`${owner.getStart(sourceFile)}:${owner.end}`);\n}\n\n/**\n * Decodes the types of checker expressions matched to original semantic probes.\n *\n * @param sourceFile - Final checker AST for the mapped buffer.\n * @param mapping - Original probes indexed by exact checker AST start and end positions.\n * @param decoder - Decoder with asset brands already registered from producer types.\n * @param nodes - Expression nodes from sourceFile, in AST traversal order.\n * @param typesAt - Returns one type per node, in the supplied order. Undefined means no type is available.\n * @param unverified - Optional array to append unavailable original ranges to. Supplying it keeps\n * other facts usable when a probe lacks an expression or a finite declaration type.\n * @returns Facts in AST traversal order with original byte ranges. Known types that do not\n * represent Stillwind assets produce null values. Unresolved recognition-only probes are skipped\n * in both strict and partial queries.\n * @throws If unverified is omitted and a probe has no matching expression or a required type cannot\n * be resolved. Errors from typesAt also propagate.\n */\nexport function factsForSource(\n sourceFile: SourceFile,\n mapping: CheckerSource,\n decoder: AssetTypeDecoder,\n nodes: readonly Node[],\n typesAt: (nodes: readonly Node[]) => readonly (Type | undefined)[],\n unverified?: UnverifiedRange[],\n): TypeFact[] {\n const expressions: Node[] = [];\n const matched = new Set<string>();\n for (const node of nodes) {\n const key = `${node.getStart(sourceFile)}:${node.end}`;\n if (mapping.probes.has(key)) {\n expressions.push(node);\n matched.add(key);\n }\n }\n for (const [key, probe] of mapping.probes) {\n if (!matched.has(key)) {\n const error = new TypeFactsError(\n mapping.source.moduleId,\n probe.start,\n probe.end,\n \"checker\",\n \"Projected expression has no matching checker AST node\",\n );\n if (!unverified) {\n throw error;\n }\n unverified.push({\n moduleId: error.moduleId,\n start: error.start,\n end: error.end,\n reason: error.message,\n });\n }\n }\n\n const types = typesAt(expressions);\n const facts: TypeFact[] = [];\n for (const [index, expression] of expressions.entries()) {\n const probe = mapping.probes.get(`${expression.getStart(sourceFile)}:${expression.end}`)!;\n const type = types[index];\n const decoded = type\n ? decoder.decode(type, probe.recognitionOnly ?? false)\n : { kind: \"unverified\" as const };\n if (decoded.kind !== \"asset\") {\n if (\n decoded.kind === \"unverified\" ||\n (decoded.kind === \"unbranded\" && !probe.recognitionOnly)\n ) {\n if (probe.recognitionOnly) {\n continue;\n }\n const error = new TypeFactsError(\n mapping.source.moduleId,\n probe.start,\n probe.end,\n \"identity\",\n \"Cannot determine a finite set of declaration identities. Preserve the value's inferred type, use an explicit union, or use a generic parameter.\",\n );\n if (!unverified) {\n throw error;\n }\n unverified.push({\n moduleId: error.moduleId,\n start: error.start,\n end: error.end,\n reason: error.message,\n });\n } else {\n facts.push({\n ...probe,\n value: null,\n });\n }\n continue;\n }\n facts.push({\n ...probe,\n value: decoded.value,\n });\n }\n\n return facts;\n}\n","import childProcess from \"node:child_process\";\nimport { syncBuiltinESMExports } from \"node:module\";\n\n/**\n * Runs a function while `child_process.spawn` hides the console windows of new processes.\n *\n * The TypeScript API starts its checker with `spawn` and has no option for `windowsHide`. Under\n * Electron, `Code.exe` is a Windows GUI program that has no console, so Windows opens a visible\n * console for `tsc.exe` unless the spawn call hides it.\n *\n * @param action - Synchronous function that starts processes. Asynchronous work after it returns\n * uses the original `spawn`.\n * @returns The function's return value. `spawn` is restored before the return or the throw.\n * @throws If the function throws.\n */\nexport function withHiddenSpawnWindows<T>(action: () => T): T {\n const { spawn } = childProcess;\n childProcess.spawn = ((command: string, args: readonly string[], options: object) =>\n spawn(command, args, {\n ...options,\n windowsHide: true,\n })) as typeof spawn;\n // ESM imports of `node:child_process` read a copy that only this call updates.\n syncBuiltinESMExports();\n try {\n return action();\n } finally {\n childProcess.spawn = spawn;\n syncBuiltinESMExports();\n }\n}\n","import { existsSync } from \"node:fs\";\nimport path from \"node:path\";\n\nimport type { NativeAssetRecord as AssetRecord } from \"@stillwind/native\";\nimport type { Node, SourceFile } from \"typescript-7/unstable/ast\";\nimport { isExpression } from \"typescript-7/unstable/ast/is\";\nimport {\n API,\n Snapshot,\n type Checker,\n type Diagnostic,\n type Type,\n} from \"typescript-7/unstable/sync\";\n\nimport type { TypeFactSource } from \"../backend.ts\";\nimport type { TypePropertyCache } from \"./decoder.ts\";\nimport { visit } from \"./facts.ts\";\nimport { withHiddenSpawnWindows } from \"./hidden-spawn.ts\";\nimport {\n normalize,\n prepareProject,\n type PreparedProject,\n type TypeFactsEnvironment,\n type TypeFactsInputs,\n type TypeScriptProject,\n} from \"./project.ts\";\n\n/**\n * Cumulative checker lifecycle and filesystem counters for one service. They include recovery\n * attempts and are not reset between collections.\n */\nexport interface TypeScriptFactsStats {\n /** Number of API construction attempts, including starts after invalidation or query failure. */\n starts: number;\n /**\n * Number of snapshot updates that returned a snapshot, including updates followed by a query\n * failure.\n */\n snapshots: number;\n /** Number of snapshot updates made while a previous snapshot was retained. */\n incrementalSnapshots: number;\n /** Number of recovery restarts attempted after a failure other than `TypeFactsError`. */\n restarts: number;\n /** Number of checker read callbacks answered with text from the virtual overlay. */\n overlayReads: number;\n /**\n * Number of checker read callbacks delegated to the filesystem because the overlay had no text. A\n * request does not imply a successful disk read.\n */\n diskReadRequests: number;\n}\n\n/**\n * Owns the Node checker process, snapshots, and answers cached within each snapshot.\n * The analysis service serializes calls and closes the checker after pending work finishes.\n */\nexport class NodeChecker {\n /** Property answers for the current snapshot. Cleared before replacing that snapshot. */\n readonly properties: TypePropertyCache = {\n named: new Map(),\n all: new Map(),\n };\n\n /** Types keyed by filename and AST range within the current snapshot. */\n readonly #queryTypes = new Map<string, Type | undefined>();\n\n /** Expression nodes in AST traversal order, keyed by checker filename. */\n readonly #queryNodes = new Map<string, Node[]>();\n\n /** Syntactic and semantic diagnostics for each checker file in the current snapshot. */\n readonly diagnostics = new Map<string, readonly Diagnostic[]>();\n\n /** Paths observed by disk reads and existence checks, including missing paths and overlay checks. */\n readonly dependencies = new Set<string>();\n\n /**\n * Live cumulative counters updated by this service. Consumers needing a stable report must copy\n * their values.\n */\n readonly stats: TypeScriptFactsStats = {\n starts: 0,\n snapshots: 0,\n incrementalSnapshots: 0,\n restarts: 0,\n overlayReads: 0,\n diskReadRequests: 0,\n };\n\n /** Copy of the selected TypeScript settings, fixed for this service's lifetime. */\n readonly #project: TypeScriptProject;\n\n /** Filesystem root supplied as the checker API working directory. */\n readonly #projectRoot: string;\n\n /**\n * Absolute filename of the in-memory `.stillwind-tsconfig.json`. The service does not write it to\n * disk.\n */\n readonly #shadowTsconfigPath: string;\n\n /** Active checker API instance, replaced after a recoverable collection failure. */\n #api: API;\n\n /**\n * Latest retained checker snapshot, also retained after query failures until the next update,\n * restart, or close.\n */\n #snapshot: Snapshot | undefined;\n\n /**\n * Current normalized filename overlay read dynamically by the checker API filesystem callbacks.\n */\n #virtualFiles = new Map<string, string>();\n\n /**\n * Starts a checker API for a project root without creating its first snapshot.\n *\n * @param environment - Absolute filesystem root and selected TypeScript settings. The checker\n * copies these settings and uses them for its lifetime. Create a new checker to change them.\n * @throws If the checker API cannot start.\n */\n constructor(environment: TypeFactsEnvironment) {\n this.#project = { ...environment.project };\n this.#projectRoot = environment.root;\n this.#shadowTsconfigPath = path.join(environment.root, \".stillwind-tsconfig.json\");\n this.#api = this.#startApi();\n }\n\n /**\n * Builds virtual checker files using the project's TypeScript settings.\n *\n * @param sources - Prepared sources and probes for this request.\n * @param assets - Declarations grouped by compiler module ID.\n * @param inputs - Overlays and ambient declarations used for config reads and checker files.\n * @returns Virtual files, checker mappings, and declaration identities for the supplied sources.\n * @throws If configuration parsing, checker mapping, or declaration preparation fails.\n */\n prepareProject(\n sources: readonly TypeFactSource[],\n assets: ReadonlyMap<string, readonly AssetRecord[]>,\n inputs: TypeFactsInputs,\n ): PreparedProject {\n return prepareProject(\n sources,\n assets,\n this.#shadowTsconfigPath,\n this.#project,\n inputs,\n this.#configuredDeclarations(inputs),\n );\n }\n\n /**\n * Queries types once per expression in the current snapshot.\n *\n * @param checker - Checker that owns the current snapshot.\n * @param nodes - Expression nodes from that snapshot, in the requested order.\n * @returns Types in the same order. Undefined records a missing type. Answers are cached until the snapshot changes.\n * @throws If the checker query fails.\n */\n types(checker: Checker, nodes: readonly Node[]): (Type | undefined)[] {\n const keys = nodes.map((node) => `${node.getSourceFile().fileName}:${node.pos}:${node.end}`);\n const missing = new Map<string, Node>();\n for (const [index, key] of keys.entries()) {\n if (!this.#queryTypes.has(key)) {\n missing.set(key, nodes[index]);\n }\n }\n if (missing.size) {\n const values = checker.getTypeAtLocation([...missing.values()]);\n [...missing.keys()].forEach((key, index) => this.#queryTypes.set(key, values[index]));\n }\n return keys.map((key) => this.#queryTypes.get(key));\n }\n\n /**\n * Finds expression nodes once per file in the current snapshot.\n *\n * @param file - Source file from the current checker snapshot.\n * @returns Cached expression nodes in AST traversal order. Do not mutate the array.\n */\n expressions(file: SourceFile): readonly Node[] {\n let nodes = this.#queryNodes.get(file.fileName);\n if (!nodes) {\n const expressions: Node[] = [];\n visit(file, (node) => {\n if (isExpression(node)) {\n expressions.push(node);\n }\n });\n nodes = expressions;\n this.#queryNodes.set(file.fileName, nodes);\n }\n return nodes;\n }\n\n /**\n * Reads the consumer's declaration roots using the captured configuration overlays. Ordinary\n * source files selected by the consumer remain outside the generated project's root files.\n *\n * @param inputs - File replacements used while parsing the selected configuration.\n * @returns Declaration filenames selected by TypeScript, or an empty list for isolated settings.\n * Restores the overlay used by the retained snapshot before returning or throwing.\n * @throws If TypeScript cannot parse the selected configuration or its inherited files.\n */\n #configuredDeclarations(inputs: TypeFactsInputs): readonly string[] {\n if (this.#project.kind === \"isolated\") {\n return [];\n }\n const previous = this.#virtualFiles;\n this.#virtualFiles = new Map(\n [...(inputs.overlayFiles ?? []), ...(inputs.ambientDeclarations ?? [])].map(\n ([name, text]) => [normalize(name), text],\n ),\n );\n try {\n return this.#api\n .parseConfigFile(this.#project.configPath)\n .fileNames.filter((file) => /\\.d\\.[cm]?ts$/i.test(file));\n } finally {\n this.#virtualFiles = previous;\n }\n }\n\n /**\n * Starts a checker API whose filesystem callbacks consult the current virtual overlay.\n *\n * @returns A new API using the project root, with timing collection enabled. Increments starts\n * before construction. Read callbacks update the filesystem counters.\n * @throws If API construction fails.\n */\n #startApi(): API {\n this.stats.starts += 1;\n return withHiddenSpawnWindows(\n () =>\n new API({\n cwd: this.#projectRoot,\n collectTiming: true,\n fs: {\n directoryExists: (directoryName) => {\n const prefix = normalize(directoryName).replace(/\\/$/, \"\") + \"/\";\n return [...this.#virtualFiles.keys()].some((name) => name.startsWith(prefix))\n ? true\n : undefined;\n },\n fileExists: (fileName) => {\n this.dependencies.add(fileName);\n return this.#virtualFiles.has(normalize(fileName)) ? true : undefined;\n },\n readFile: (fileName) => {\n const overlay = this.#virtualFiles.get(normalize(fileName));\n if (overlay === undefined) {\n this.dependencies.add(fileName);\n this.stats.diskReadRequests += 1;\n } else {\n this.stats.overlayReads += 1;\n }\n return overlay;\n },\n },\n }),\n );\n }\n\n /**\n * Disposes the previous snapshot and API, then replaces the API without clearing virtual files or\n * counters.\n *\n * @throws If cleanup or creation of the replacement API fails.\n */\n restart(): void {\n this.#disposeApi();\n this.#api = this.#startApi();\n }\n\n /**\n * Releases the API and all answers whose objects belong to its snapshot.\n */\n #disposeApi(): void {\n this.#snapshot?.dispose();\n this.#snapshot = undefined;\n this.#clearQueries();\n this.#api.close();\n }\n\n /**\n * Discards query results before replacing a checker snapshot.\n */\n #clearQueries(): void {\n this.properties.named.clear();\n this.properties.all.clear();\n this.#queryTypes.clear();\n this.#queryNodes.clear();\n this.diagnostics.clear();\n }\n\n /**\n * Replaces virtual files and retains the new snapshot after releasing the previous one.\n *\n * @param prepared - Complete normalized virtual project, retained as the new filesystem overlay.\n * @returns The checker project from the new snapshot. Snapshot counters are incremented after update.\n * @throws If snapshot update or disposal fails, or the generated project cannot be opened.\n */\n updateProject(prepared: PreparedProject) {\n const changed: string[] = [];\n const created: string[] = [];\n const deleted: string[] = [];\n for (const [fileName, contents] of prepared.virtualFiles) {\n if (!this.#virtualFiles.has(fileName)) {\n (existsSync(fileName) ? changed : created).push(fileName);\n } else if (this.#virtualFiles.get(fileName) !== contents) {\n changed.push(fileName);\n }\n }\n for (const fileName of this.#virtualFiles.keys()) {\n if (!prepared.virtualFiles.has(fileName)) {\n (existsSync(fileName) ? changed : deleted).push(fileName);\n }\n }\n this.#virtualFiles = prepared.virtualFiles;\n\n if (this.#snapshot && changed.length === 0 && created.length === 0 && deleted.length === 0) {\n const project = this.#snapshot.getProject(this.#shadowTsconfigPath);\n if (project) {\n return project;\n }\n }\n\n this.#clearQueries();\n const next = this.#snapshot\n ? this.#api.updateSnapshot({\n fileChanges: {\n changed,\n created,\n deleted,\n },\n })\n : this.#api.updateSnapshot({\n openProjects: [this.#shadowTsconfigPath],\n });\n this.stats.snapshots += 1;\n if (this.#snapshot) {\n this.stats.incrementalSnapshots += 1;\n }\n this.#snapshot?.dispose();\n this.#snapshot = next;\n const project = next.getProject(this.#shadowTsconfigPath);\n if (!project) {\n throw new Error(\"TypeScript 7 could not open the Stillwind shadow project\");\n }\n return project;\n }\n\n /**\n * Releases the checker process and all objects owned by its snapshot.\n */\n close(): void {\n this.#disposeApi();\n }\n}\n","import type { NativeExportedValue, NativeIdentity, NativeSymbolicValue } from \"@stillwind/native\";\nimport {\n SignatureKind,\n TypeFlags,\n type Checker,\n type Type,\n type Symbol as TypeSymbol,\n} from \"typescript-7/unstable/sync\";\n\n/**\n * Result of decoding a checker type.\n *\n * `nonAsset` covers types whose values cannot be Stillwind assets: primitive types, macro use types,\n * and object types to which no producer type of the snapshot is assignable. `unbranded` covers object types without\n * asset branding to which a producer type is assignable. Such a value is not a macro receiver, but\n * it may hold an asset whose type was widened, so lowering cannot treat it as a confirmed\n * non-asset. Without producer types, every object type without branding is `unbranded`.\n */\ntype DecodedType =\n | {\n kind: \"asset\";\n value: NativeExportedValue;\n }\n | {\n kind: \"nonAsset\" | \"unbranded\" | \"unverified\";\n };\n\n/** Types whose values cannot be Stillwind assets. */\nconst primitiveTypeFlags =\n TypeFlags.StringLike |\n TypeFlags.NumberLike |\n TypeFlags.BigIntLike |\n TypeFlags.BooleanLike |\n TypeFlags.EnumLike |\n TypeFlags.ESSymbolLike |\n TypeFlags.Null |\n TypeFlags.Undefined |\n TypeFlags.Void |\n TypeFlags.Never;\n\n/**\n * Native declaration identity containing its asset kind, declaring module, original byte range, and\n * binding name.\n */\ntype IdentityId = NativeIdentity;\n\n/**\n * Decodes a string-literal identity type or union using the current declaration table.\n *\n * @param type - Checker type of an identity property, or undefined when the property is\n * unavailable.\n * @param identities - Serialized keys mapped to known native declaration identities.\n * @param kind - Asset family that every candidate must belong to.\n * @returns Candidates in type-member order. Returns `\"unknown\"` if the type is absent,\n * nonliteral, or unknown to the table, and `\"mismatch\"` if a candidate belongs to a\n * different asset family.\n */\nfunction knownIdentities(\n type: Type | undefined,\n identities: ReadonlyMap<string, IdentityId>,\n kind: IdentityId[\"kind\"],\n): \"unknown\" | \"mismatch\" | IdentityId[] {\n if (!type) {\n return \"unknown\";\n }\n const types = type.isUnionType() ? type.getTypes() : [type];\n const result: IdentityId[] = [];\n let unknown = false;\n for (const candidate of types) {\n const identity = candidate.isStringLiteralType() ? identities.get(candidate.value) : undefined;\n if (!identity) {\n unknown = true;\n continue;\n }\n if (identity.kind !== kind) {\n return \"mismatch\";\n }\n result.push(identity);\n }\n return unknown ? \"unknown\" : result;\n}\n\n/**\n * Packages known declarations as a finite native symbolic value.\n *\n * @param kind - Asset family shared by the supplied identities.\n * @param identities - Candidate identities retained in their supplied order.\n * @returns A finite symbolic value containing a copied candidate array.\n */\nfunction symbolic(\n kind: IdentityId[\"kind\"],\n identities: readonly IdentityId[],\n): NativeSymbolicValue {\n return {\n kind,\n candidates: {\n kind: \"finite\",\n values: [...identities],\n },\n };\n}\n\n/** Property lookups owned by one checker snapshot. */\nexport type TypePropertyCache = {\n /** Symbols keyed by type ID and property name. Missing properties are cached as undefined. */\n named: Map<string, TypeSymbol | undefined>;\n /** Complete property lists keyed by type ID from the same snapshot. */\n all: Map<number, readonly TypeSymbol[]>;\n};\n\n/**\n * Decodes checker types into native declaration candidates using brand properties discovered from\n * producer modules.\n */\nexport class AssetTypeDecoder {\n /**\n * Checker for the current project snapshot, used to inspect exported types and their properties.\n */\n readonly #checker: Checker;\n /** Shared property lookups. The owning service clears them before replacing the snapshot. */\n readonly #properties: TypePropertyCache;\n /**\n * All declaration keys registered in the current virtual project, mapped to original native\n * identities.\n */\n readonly #identities: ReadonlyMap<string, IdentityId>;\n /** Checker symbol IDs of modules whose exported asset brands have already been inspected. */\n readonly #modules = new Set<number>();\n /** Internal names of discovered unique-symbol brand properties mapped to their asset families. */\n readonly #brands = new Map<string, IdentityId[\"kind\"]>();\n /** Registered producer call types, used to detect object types that may hold a widened asset. */\n readonly #producers: Type[] = [];\n\n /**\n * Creates a decoder for one checker snapshot and declaration table.\n *\n * @param checker - Checker owning all types supplied to this decoder.\n * @param identities - Serialized identity keys inserted into the project's producer calls.\n * @param properties - Property cache for the same checker snapshot. May be shared with other decoders.\n */\n constructor(\n checker: Checker,\n identities: ReadonlyMap<string, IdentityId>,\n properties: TypePropertyCache,\n ) {\n this.#checker = checker;\n this.#identities = identities;\n this.#properties = properties;\n }\n\n /**\n * Looks up a named property once per snapshot, including missing properties.\n *\n * @param type - Type from this decoder's checker snapshot.\n * @param name - Property name to look up.\n * @returns The property symbol, or undefined when absent. Stores the answer in the shared cache.\n */\n #property(type: Type, name: string): TypeSymbol | undefined {\n const key = `${type.id}:${name}`;\n if (!this.#properties.named.has(key)) {\n this.#properties.named.set(key, this.#checker.getPropertyOfType(type, name));\n }\n return this.#properties.named.get(key);\n }\n\n /**\n * Looks up all properties of a type once per snapshot.\n *\n * @param type - Type from this decoder's checker snapshot.\n * @returns The cached property list. Do not mutate it.\n */\n #allProperties(type: Type): readonly TypeSymbol[] {\n let properties = this.#properties.all.get(type.id);\n if (!properties) {\n properties = this.#checker.getPropertiesOfType(type);\n this.#properties.all.set(type.id, properties);\n }\n return properties;\n }\n\n /**\n * Discovers ref, keyframe, and view-transition brands in a producer type's declaring module.\n *\n * @param type - Producer call type from this decoder's checker snapshot. The type is retained for\n * later decoding. Missing alias modules and already inspected modules are skipped. The discovered\n * property names are retained for later decoding.\n */\n register(type: Type): void {\n this.#producers.push(type);\n const module = type.getAliasSymbol()?.getParent();\n if (!module || this.#modules.has(module.id)) {\n return;\n }\n this.#modules.add(module.id);\n for (const [name, kind, brand] of [\n [\"StyleRef\", \"ref\", \"refIdentity\"],\n [\"StyleKeyframes\", \"keyframes\", \"keyframesIdentity\"],\n [\"StyleViewTransition\", \"viewTransition\", \"viewTransitionIdentity\"],\n ] as const) {\n const symbol = this.#checker.getMemberInModuleExports(module, name);\n if (!symbol) {\n continue;\n }\n const declared = this.#checker.getDeclaredTypeOfSymbol(symbol);\n const property = this.#checker\n .getPropertiesOfType(declared)\n .find((property) => property.name.startsWith(`__@${brand}@`));\n if (property) {\n this.#brands.set(property.name, kind);\n }\n }\n }\n\n /**\n * Tests whether a type alias is declared by a registered macro module. Such a type describes a\n * macro use or declaration, not an author's widened asset.\n *\n * @param type - Type from this decoder's checker snapshot.\n * @returns Whether the alias symbol's module was inspected by {@link register}.\n */\n #declaredByMacro(type: Type): boolean {\n const module = type.getAliasSymbol()?.getParent();\n return !!module && this.#modules.has(module.id);\n }\n\n /**\n * Resolves a checker type to finite candidates from a single asset family.\n *\n * @param type - Type of a probed expression from the current checker snapshot.\n * @param recognitionOnly - True skips checks for widened asset types when only macro recognition is needed.\n * @returns Finite candidates, a confirmed non-asset, an object type that may hold a widened\n * asset, or an unverified value whose declarations cannot be determined.\n */\n decode(type: Type, recognitionOnly: boolean): DecodedType {\n if (type.flags & (TypeFlags.Any | TypeFlags.Unknown)) {\n return { kind: \"unverified\" };\n }\n const constituents = type.isUnionType() ? type.getTypes() : [type];\n const values: IdentityId[] = [];\n let family: IdentityId[\"kind\"] | undefined;\n let recognized = false;\n let valid = true;\n let finite = true;\n for (const constituent of constituents) {\n if (constituent.flags & primitiveTypeFlags) {\n valid = false;\n continue;\n }\n let kind: IdentityId[\"kind\"] | undefined;\n let identityType: Type | undefined;\n const style = this.#property(constituent, \"data-__stillwindStyleIdentity\");\n if (style) {\n kind = \"style\";\n identityType = this.#checker.getTypeOfSymbol(style);\n } else {\n for (const brand of this.#allProperties(constituent)) {\n const candidateKind = this.#brands.get(brand.name);\n if (!candidateKind) {\n continue;\n }\n const callable =\n candidateKind === \"viewTransition\" ? this.#property(constituent, \"for\") : undefined;\n const method = callable && this.#checker.getTypeOfSymbol(callable);\n const declaration =\n candidateKind === \"viewTransition\"\n ? method && this.#checker.getSignaturesOfType(method, SignatureKind.Call).length > 0\n : this.#checker.getSignaturesOfType(constituent, SignatureKind.Call).length > 0;\n if (!declaration) {\n continue;\n }\n kind = candidateKind;\n identityType = this.#checker.getTypeOfSymbol(brand);\n if (kind === \"ref\" && identityType) {\n const ref = this.#property(identityType, \"ref\");\n identityType = ref && this.#checker.getTypeOfSymbol(ref);\n }\n break;\n }\n }\n const name = (constituent.getAliasSymbol() ?? constituent.getSymbol())?.name;\n recognized ||=\n !!kind || (!!name && /^Style(?:Result|Ref|Keyframes|ViewTransition)$/.test(name));\n if (!kind) {\n valid = false;\n continue;\n }\n if (family && family !== kind) {\n valid = false;\n continue;\n }\n family = kind;\n const candidates = knownIdentities(identityType, this.#identities, kind);\n if (candidates === \"mismatch\") {\n valid = false;\n } else if (candidates === \"unknown\") {\n finite = false;\n } else {\n values.push(...candidates);\n }\n }\n if (valid && family === \"style\" && !finite) {\n // A style result with an unknown declaration still has a known runtime form. The\n // compiler merges it as a base without a CSS ordering dependency.\n return {\n kind: \"asset\",\n value: {\n kind: \"styles\",\n value: {\n kind: \"style\",\n candidates: {\n kind: \"universe\",\n },\n },\n },\n };\n }\n if (!valid || !family || values.length === 0) {\n if (recognized) {\n return {\n kind: \"unverified\",\n };\n }\n const widened =\n !recognitionOnly &&\n constituents.some(\n (constituent) =>\n !(constituent.flags & primitiveTypeFlags) &&\n !this.#declaredByMacro(constituent) &&\n (this.#producers.length === 0 ||\n this.#producers.some((producer) =>\n this.#checker.isTypeAssignableTo(producer, constituent),\n )),\n );\n return {\n kind: widened ? \"unbranded\" : \"nonAsset\",\n };\n }\n const kinds = {\n style: \"styles\",\n ref: \"refs\",\n keyframes: \"keyframes\",\n viewTransition: \"viewTransitions\",\n } as const;\n return {\n kind: \"asset\",\n value: {\n kind: kinds[family],\n value: symbolic(family, values),\n },\n };\n }\n}\n","import type { NativeAssetRecord, NativeTypeFact } from \"@stillwind/native\";\nimport type { Node } from \"typescript-7/unstable/ast\";\nimport {\n isCallExpression,\n isExportDeclaration,\n isImportDeclaration,\n isSourceFile,\n isStringLiteral,\n} from \"typescript-7/unstable/ast/is\";\n\nimport {\n TypeFactsError,\n type AvailableFacts,\n type TypeFactSource,\n type TypeFactsBackend,\n type UnverifiedRange,\n} from \"../backend.ts\";\nimport { checkerId, withRequestedProbes } from \"../checker-source.ts\";\nimport { NodeChecker, type TypeScriptFactsStats } from \"./checker.ts\";\nimport { AssetTypeDecoder } from \"./decoder.ts\";\nimport { visit, diagnosticText, producerArgumentDiagnostic, factsForSource } from \"./facts.ts\";\nimport {\n normalize,\n type PreparedProject,\n type TypeFactsEnvironment,\n type TypeFactsInputs,\n} from \"./project.ts\";\n\n/**\n * Native declaration record carrying an identity, metadata, and the original-byte range of its\n * producer call.\n */\nexport type AssetRecord = NativeAssetRecord;\n\n/** Semantic value attached to an original UTF-8 expression range for native lowering. */\nexport type TypeFact = NativeTypeFact;\n\n/**\n * Collects declaration facts with a reusable Node checker. Close the service after pending queries finish.\n */\nexport class TypeScriptFactsService implements TypeFactsBackend {\n /** Project inputs retained until setProjectSources replaces them. Queries select a subset. */\n #installed?: {\n sources: readonly TypeFactSource[];\n assets: ReadonlyMap<string, readonly AssetRecord[]>;\n inputs: TypeFactsInputs;\n };\n\n /** Checker buffers prepared from the installed project inputs. */\n #prepared?: PreparedProject;\n\n /**\n * Whether close has been requested. Subsequent collections reject and repeated close calls do\n * nothing.\n */\n #closed = false;\n\n /** Checker process and snapshot caches owned by this service. */\n readonly #checker: NodeChecker;\n\n /** Paths observed by disk reads and existence checks, including missing paths and overlay checks. */\n readonly dependencies: Set<string>;\n\n /**\n * Live cumulative counters updated by this service. Consumers needing a stable report must copy\n * their values.\n */\n readonly stats: TypeScriptFactsStats;\n\n /**\n * Creates a service and starts its checker process without opening a snapshot.\n *\n * @param environment - Fixed project root and TypeScript settings.\n * @throws If the checker process cannot start.\n */\n constructor(environment: TypeFactsEnvironment) {\n this.#checker = new NodeChecker(environment);\n this.dependencies = this.#checker.dependencies;\n this.stats = this.#checker.stats;\n }\n\n /**\n * Keeps project inputs for later queries and clears prepared checker buffers.\n *\n * @param sources - Prepared project sources, retained by reference until replaced.\n * @param assets - Declarations grouped by compiler module ID, retained with the sources.\n * @param inputs - File overlays and ambient declarations. Omission supplies no extra files.\n * Do not mutate these inputs while they are installed. Queries select their own probes and sources.\n */\n setProjectSources(\n sources: readonly TypeFactSource[],\n assets: ReadonlyMap<string, readonly AssetRecord[]>,\n inputs: TypeFactsInputs = {},\n ): void {\n this.#installed = { sources, assets, inputs };\n this.#prepared = undefined;\n }\n\n /**\n * Collects finite declaration candidates for original-coordinate probes.\n *\n * Queries reuse the current snapshot when files have not changed. Mapping, assignment, and\n * identity errors throw TypeFactsError. Other checker failures restart the API and retry once.\n * Only diagnostics about Stillwind declaration contracts affect the result.\n *\n * @param sources - Prepared sources and original-byte probes, with validated projection\n * correspondences where needed.\n * @param assetsByModuleId - Declaration records keyed by compiler module identity.\n * @param inputs - Overlays and ambient declarations for an independent query. Omission supplies none.\n * When project sources are installed, preparation uses their installed inputs instead.\n * @returns Facts keyed by compiler module identity. Facts for the same original range are\n * deduplicated across buffers. Conflicting values throw. Known non-asset types produce null facts.\n * Unresolved recognition-only probes produce no fact.\n * @throws If the service is closed, preparation or checker contracts fail, or the API fails. A\n * failed query retry throws an AggregateError containing both query failures.\n */\n collect(\n sources: readonly TypeFactSource[],\n assetsByModuleId: ReadonlyMap<string, readonly AssetRecord[]>,\n inputs: TypeFactsInputs = {},\n ): Map<string, TypeFact[]> {\n return this.#collect(sources, assetsByModuleId, inputs, false).facts;\n }\n\n /**\n * Collects verified facts, reusing the snapshot when files have not changed.\n *\n * @param sources - Prepared sources and original UTF-8 probes with validated checker correspondences.\n * @param assetsByModuleId - Declaration records grouped by compiler module identity.\n * @param inputs - Overlays and ambient declarations for an independent query. Omission supplies none.\n * When project sources are installed, preparation uses their installed inputs instead.\n * @returns Verified facts and unavailable original ranges. Unavailable queries do not discard\n * facts collected for other expressions.\n * @throws If the service is closed, project preparation fails, facts conflict, or checker restart and retry fail.\n */\n collectAvailable(\n sources: readonly TypeFactSource[],\n assetsByModuleId: ReadonlyMap<string, readonly AssetRecord[]>,\n inputs: TypeFactsInputs = {},\n ): AvailableFacts {\n return this.#collect(sources, assetsByModuleId, inputs, true);\n }\n\n /**\n * Resolves authored imports and exports using module symbols in the selected TypeScript settings.\n *\n * @param sources - Prepared sources whose checker buffers contain the authored module requests.\n * Independent resolution ignores probes. An installed project also prepares its probes for later queries.\n * @param assetsByModuleId - Declaration records used to expose generated helper types.\n * @param inputs - Overlays and ambient declarations for independent resolution. Omission supplies none.\n * An installed project uses the inputs supplied by setProjectSources.\n * @returns Request-to-identity maps grouped by source resolver identity. Prepared checker paths\n * map back to resolver identities. Other resolutions retain checker filenames, including declarations.\n * Requests without a matching module symbol are omitted.\n * @throws If the service is closed, project preparation fails, or checker resolution fails.\n */\n resolveModules(\n sources: readonly TypeFactSource[],\n assetsByModuleId: ReadonlyMap<string, readonly AssetRecord[]>,\n inputs: TypeFactsInputs = {},\n ): Map<string, Map<string, string>> {\n if (this.#closed) {\n throw new Error(\"TypeScript facts service is closed\");\n }\n const inventory = this.#installed?.sources ?? sources;\n const prepared = this.#prepare(sources, assetsByModuleId, inputs, true);\n const project = this.#checker.updateProject(prepared);\n const result = new Map<string, Map<string, string>>();\n for (const mapping of prepared.mappings) {\n const file = project.program.getSourceFile(mapping.id);\n if (!file) {\n continue;\n }\n const resolutions = result.get(mapping.source.resolverId) ?? new Map<string, string>();\n result.set(mapping.source.resolverId, resolutions);\n visit(file, (node) => {\n if (\n !(isImportDeclaration(node) || isExportDeclaration(node)) ||\n !node.moduleSpecifier ||\n !isStringLiteral(node.moduleSpecifier)\n ) {\n return;\n }\n const symbol = project.checker.getSymbolAtLocation(node.moduleSpecifier);\n const declaration = symbol?.declarations.find((declaration) => {\n const node = declaration.resolve(project);\n return (\n node !== undefined && (isSourceFile(node) || node.getSourceFile().isDeclarationFile)\n );\n });\n if (declaration) {\n const fileName = declaration.resolve(project)!.getSourceFile().fileName;\n const original = inventory.find(\n (source) => normalize(checkerId(source)) === normalize(fileName),\n );\n const key = `${node.moduleSpecifier.getStart(file)}:${node.moduleSpecifier.end}`;\n resolutions.set(\n mapping.moduleSpecifiers.get(key) ?? node.moduleSpecifier.text,\n original?.resolverId ?? fileName,\n );\n }\n });\n }\n return result;\n }\n\n /**\n * Prepares one request and retries an unexpected checker failure once with a clean API.\n *\n * @param sources - Prepared sources and original UTF-8 probes.\n * @param assetsByModuleId - Declaration records grouped by compiler identity.\n * @param inputs - Complete overlays and ambient declarations for the request.\n * @param available - Whether unavailable facts are recorded instead of rejecting the request.\n * @returns Collected facts and unavailable ranges from the successful attempt.\n * @throws If preparation fails, a TypeFactsError occurs, restart fails, or both query attempts fail.\n */\n #collect(\n sources: readonly TypeFactSource[],\n assetsByModuleId: ReadonlyMap<string, readonly AssetRecord[]>,\n inputs: TypeFactsInputs,\n available: boolean,\n ): AvailableFacts {\n if (this.#closed) {\n throw new Error(\"TypeScript facts service is closed\");\n }\n if (this.#installed) {\n const updated = withRequestedProbes(this.#installed.sources, sources);\n if (updated !== this.#installed.sources) {\n this.#installed = { ...this.#installed, sources: updated };\n this.#prepared = undefined;\n }\n }\n const full = this.#prepare(sources, assetsByModuleId, inputs);\n const selected = new Set(sources.map((source) => source.resolverId));\n const mappings = full.mappings.filter((mapping) => selected.has(mapping.source.resolverId));\n const prepared = {\n ...full,\n mappings,\n identities: new Map(mappings.flatMap((mapping) => [...mapping.identities])),\n };\n try {\n return this.#collectPrepared(prepared, available);\n } catch (firstError) {\n if (firstError instanceof TypeFactsError) {\n throw firstError;\n }\n this.stats.restarts += 1;\n this.#restartApi();\n try {\n return this.#collectPrepared(prepared, available);\n } catch (retryError) {\n throw new AggregateError(\n [firstError, retryError],\n `TypeScript 7 checker failed before and after a clean restart: ${String(retryError)}`,\n );\n }\n }\n }\n\n /**\n * Reuses prepared project inputs or prepares only the requested sources if project preparation fails.\n *\n * @param sources - Requested sources to use when no project is installed or preparation fails.\n * @param assets - Declarations grouped by module ID for those sources.\n * @param inputs - Overlays and ambient declarations for the requested sources.\n * @param resolutionOnly - True omits probes when preparing only the requested sources for import resolution.\n * @returns Prepared checker files and mappings. Successful project preparation is cached.\n * @throws If the requested sources or their TypeScript configuration cannot be prepared.\n */\n #prepare(\n sources: readonly TypeFactSource[],\n assets: ReadonlyMap<string, readonly AssetRecord[]>,\n inputs: TypeFactsInputs,\n resolutionOnly = false,\n ): PreparedProject {\n if (this.#installed && this.#prepared) {\n return this.#prepared;\n }\n if (this.#installed) {\n try {\n this.#prepared = this.#checker.prepareProject(\n this.#installed.sources,\n this.#installed.assets,\n this.#installed.inputs,\n );\n return this.#prepared;\n } catch {\n // Unrelated invalid checker mappings must not reject a scoped query.\n }\n }\n return this.#checker.prepareProject(\n resolutionOnly ? sources.map((source) => ({ ...source, probes: [] })) : sources,\n assets,\n inputs,\n );\n }\n\n /**\n * Marks the service closed, disposes its retained snapshot, and closes the checker API. Repeated\n * calls return without further work.\n *\n * @throws If snapshot disposal or API cleanup fails.\n */\n close(): void {\n if (this.#closed) {\n return;\n }\n this.#closed = true;\n this.#prepared = undefined;\n this.#checker.close();\n }\n\n /**\n * Discards cached disk contents and the retained snapshot while keeping the selected environment.\n * The next collection opens a new project. Calls after close have no effect.\n *\n * @throws If checker cleanup or restart fails.\n */\n invalidate(): void {\n if (!this.#closed) {\n this.#restartApi();\n }\n }\n\n /**\n * Updates the snapshot and collects facts from the prepared checker buffers.\n *\n * @param prepared - Virtual files, original-coordinate mappings, and serialized declaration identities.\n * @param available - Whether contract failures become unverified ranges where recovery is possible.\n * @returns Deduplicated facts by compiler identity and unverified original UTF-8 ranges.\n * @throws If snapshot update fails, a checker file is missing, facts conflict, or strict collection fails.\n */\n #collectPrepared(prepared: PreparedProject, available: boolean): AvailableFacts {\n const project = this.#checker.updateProject(prepared);\n const unverified: UnverifiedRange[] = [];\n const result = new Map<string, TypeFact[]>();\n const decoder = new AssetTypeDecoder(\n project.checker,\n prepared.identities,\n this.#checker.properties,\n );\n const producers: Node[] = [];\n for (const mapping of prepared.mappings) {\n const file = project.program.getSourceFile(mapping.id);\n if (!file) {\n continue;\n }\n producers.push(\n ...this.#checker\n .expressions(file)\n .filter(\n (node) =>\n isCallExpression(node) && mapping.producers.has(`${node.getStart(file)}:${node.end}`),\n ),\n );\n }\n for (const type of this.#checker.types(project.checker, producers)) {\n if (type) {\n decoder.register(type);\n }\n }\n for (const mapping of prepared.mappings) {\n const sourceFile = project.program.getSourceFile(mapping.id);\n if (!sourceFile) {\n throw new Error(`TypeScript 7 omitted ${mapping.id}`);\n }\n let diagnostics = this.#checker.diagnostics.get(mapping.id);\n if (!diagnostics) {\n diagnostics = [\n ...project.program.getSyntacticDiagnostics(mapping.id),\n ...project.program.getSemanticDiagnostics(mapping.id),\n ];\n this.#checker.diagnostics.set(mapping.id, diagnostics);\n }\n const diagnostic = diagnostics.find(\n (d) =>\n !producerArgumentDiagnostic(d, sourceFile, mapping) &&\n /stillwind\\/v1:|StyleResult|StyleRef|StyleKeyframes|StyleViewTransition|__stillwindDeclarationIdentity|data-__stillwindStyleIdentity/.test(\n diagnosticText(d),\n ),\n );\n if (diagnostic) {\n const start = mapping.originalOffset(diagnostic.pos) ?? undefined;\n const end = mapping.originalOffset(diagnostic.end, true) ?? undefined;\n const message = diagnosticText(diagnostic).replace(\n /stillwind\\/v1:[A-Za-z0-9_-]+/g,\n \"declaration identity\",\n );\n const error = new TypeFactsError(\n mapping.source.moduleId,\n start,\n end,\n \"assignment\",\n `TS${diagnostic.code}: ${message} Preserve declaration candidates with an explicit union or a generic parameter.`,\n );\n if (!available) {\n throw error;\n }\n unverified.push({ moduleId: error.moduleId, start, end, reason: error.message });\n }\n const facts = factsForSource(\n sourceFile,\n mapping,\n decoder,\n this.#checker.expressions(sourceFile),\n (nodes) => this.#checker.types(project.checker, nodes),\n available ? unverified : undefined,\n );\n const previous = result.get(mapping.source.moduleId) ?? [];\n for (const fact of facts) {\n const existing = previous.find(\n (value) => value.start === fact.start && value.end === fact.end,\n );\n if (existing && JSON.stringify(existing.value) !== JSON.stringify(fact.value)) {\n throw new TypeFactsError(\n mapping.source.moduleId,\n fact.start,\n fact.end,\n \"checker\",\n \"Ambiguous checker results for this original expression\",\n );\n }\n if (!existing) {\n previous.push(fact);\n }\n }\n result.set(mapping.source.moduleId, previous);\n }\n return {\n facts: result,\n unverified,\n };\n }\n\n /**\n * Clears prepared inputs and replaces the checker process after invalidation or query failure.\n */\n #restartApi(): void {\n this.#prepared = undefined;\n this.#checker.restart();\n }\n}\n\n/**\n * Collects facts with a temporary checker service and closes it afterward.\n *\n * @param sources - Prepared sources and their original-byte semantic probes.\n * @param assetsByModuleId - Native declarations keyed by compiler module identity.\n * @param environment - Fixed filesystem root and TypeScript settings for the temporary checker.\n * @param inputs - File replacements and declarations required by this collection.\n * @returns Facts keyed by compiler module identity. The temporary checker is closed before returning.\n * @throws If service startup, fact collection, or cleanup fails.\n */\nexport function collectTypeScriptFacts(\n sources: readonly TypeFactSource[],\n assetsByModuleId: ReadonlyMap<string, readonly AssetRecord[]>,\n environment: TypeFactsEnvironment,\n inputs: TypeFactsInputs = {},\n): Map<string, TypeFact[]> {\n const service = new TypeScriptFactsService(environment);\n try {\n return service.collect(sources, assetsByModuleId, inputs);\n } finally {\n service.close();\n }\n}\n","import path from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\n\nimport {\n TraceMap,\n decodedMappings,\n originalPositionFor,\n sourceContentFor,\n} from \"@jridgewell/trace-mapping\";\nimport {\n fingerprint,\n type BindingLabel,\n type BindingLocation,\n type BindingReport,\n} from \"@stillwind/native\";\n\nimport { cleanModuleId, type PreparedSource } from \"../compilation/index.ts\";\n\n/**\n * Maps reports through upstream loader maps to their original source documents.\n *\n * @param reports - Reports with byte offsets and UTF-16 locations in prepared source documents.\n * @param sources - Prepared sources whose document metadata supplies upstream maps.\n * @param read - Reads original file text when the map has no embedded content, or when a label\n * needs a document-level fallback. Identities passed here are absolute file paths.\n * @returns Reports with original positions and content fingerprints. Unmappable labels become\n * document-scoped. An action is retained only when every edit maps to an unchanged text range.\n * @throws If required source reads or upstream map decoding fail.\n */\nexport async function mapAnalysisReports(\n reports: readonly BindingReport[],\n sources: readonly PreparedSource[],\n read: (id: string) => Promise<string>,\n): Promise<BindingReport[]> {\n const documents = new Map(sources.map((source) => [source.document.uri, source]));\n\n /**\n * Maps a location when both endpoints identify exact segments in the same original file.\n * @param location - Prepared document range with zero-based lines and UTF-16 columns.\n * @param exact - Whether the mapped and prepared ranges must contain identical text.\n * @returns The original location when no upstream map exists, a mapped location, or undefined\n * when endpoints, source identity, bounds, or required text equality cannot be established.\n * @throws If map decoding or a required original file read fails.\n */\n const mapLocation = async (\n location: BindingLocation,\n exact: boolean,\n ): Promise<BindingLocation | undefined> => {\n const source = documents.get(location.uri);\n if (!source?.document.upstreamMap) {\n return location;\n }\n const trace = new TraceMap(\n source.document.upstreamMap,\n path.isAbsolute(cleanModuleId(source.resolverId))\n ? pathToFileURL(cleanModuleId(source.resolverId)).href\n : undefined,\n );\n const start = originalPositionFor(trace, {\n line: location.startLine + 1,\n column: location.startColumn,\n });\n const end = originalPositionFor(trace, {\n line: location.endLine + 1,\n column: location.endColumn,\n });\n const mappings = decodedMappings(trace);\n /**\n * Checks whether a generated position has a segment containing an original source position.\n * @param line - Zero-based generated line.\n * @param column - Zero-based UTF-16 column that must equal a segment start.\n * @returns Whether a matching segment exists, or undefined when the line has no mappings.\n */\n const endpoint = (line: number, column: number) =>\n mappings[line]?.some((segment) => segment.length > 1 && segment[0] === column);\n if (\n !endpoint(location.startLine, location.startColumn) ||\n !endpoint(location.endLine, location.endColumn)\n ) {\n return;\n }\n if (\n !start.source ||\n start.source !== end.source ||\n start.line === null ||\n end.line === null ||\n start.column === null ||\n end.column === null\n ) {\n return;\n }\n const uri = start.source.startsWith(\"file:\")\n ? start.source\n : path.isAbsolute(start.source)\n ? pathToFileURL(start.source).href\n : undefined;\n if (!uri) {\n return;\n }\n const code = sourceContentFor(trace, start.source) ?? (await read(fileURLToPath(uri)));\n /**\n * Converts an original map position to an offset in the captured text.\n * @param line - One-based original line.\n * @param column - Nonnegative UTF-16 column that excludes a trailing carriage return.\n * @returns A UTF-16 offset, or undefined when the line or column exceeds the text bounds.\n */\n const offset = (line: number, column: number) => {\n const lines = code.split(\"\\n\");\n if (line < 1 || line > lines.length || column > lines[line - 1].replace(/\\r$/, \"\").length) {\n return;\n }\n return lines.slice(0, line - 1).reduce((sum, text) => sum + text.length + 1, 0) + column;\n };\n const startUtf16 = offset(start.line, start.column);\n const endUtf16 = offset(end.line!, end.column!);\n if (\n startUtf16 === undefined ||\n endUtf16 === undefined ||\n endUtf16 < startUtf16 ||\n (exact &&\n code.slice(startUtf16, endUtf16) !==\n source.document.code.slice(location.startUtf16, location.endUtf16))\n ) {\n return;\n }\n return {\n uri,\n revision: fingerprint(code),\n start: Buffer.byteLength(code.slice(0, startUtf16)),\n end: Buffer.byteLength(code.slice(0, endUtf16)),\n startUtf16,\n endUtf16,\n startLine: start.line - 1,\n startColumn: start.column,\n endLine: end.line! - 1,\n endColumn: end.column!,\n };\n };\n\n /**\n * Maps a label or limits it to document scope when its range cannot be mapped.\n * @param value - Label in a prepared document. The input object is not mutated.\n * @returns A copied label. A readable file fallback receives a current fingerprint and zero range.\n * @throws If map decoding or a required file read fails.\n */\n const label = async (value: BindingLabel): Promise<BindingLabel> => {\n const mapped = await mapLocation(value.location, false);\n if (mapped) {\n return {\n ...value,\n location: mapped,\n };\n }\n const source = documents.get(value.location.uri);\n const file = source && cleanModuleId(source.resolverId);\n if (file && path.isAbsolute(file)) {\n const code = await read(file);\n return {\n ...value,\n scope: \"document\",\n location: {\n ...value.location,\n uri: pathToFileURL(file).href,\n revision: fingerprint(code),\n start: 0,\n end: 0,\n startUtf16: 0,\n endUtf16: 0,\n startLine: 0,\n endLine: 0,\n startColumn: 0,\n endColumn: 0,\n },\n };\n }\n return {\n ...value,\n scope: \"document\",\n };\n };\n\n return Promise.all(\n reports.map(async (report) => {\n const actions: BindingReport[\"actions\"] = [];\n for (const action of report.actions) {\n const edits = await Promise.all(\n action.edits.map(async (edit) => {\n const location = await mapLocation(edit.location, true);\n return (\n location && {\n ...edit,\n location,\n }\n );\n }),\n );\n if (edits.every((edit) => edit !== undefined)) {\n actions.push({\n ...action,\n edits,\n });\n }\n }\n return {\n ...report,\n primary: await label(report.primary),\n related: await Promise.all(report.related.map(label)),\n actions,\n };\n }),\n );\n}\n","import path from \"node:path\";\nimport process from \"node:process\";\nimport { fileURLToPath } from \"node:url\";\n\nimport type { BaseConfig, PreviewOptions } from \"@stillwind/config\";\nimport {\n NativeProjectSession,\n type BindingReport,\n type NativeDesignSystemLoader,\n} from \"@stillwind/native\";\n\nimport type { CompilerHost } from \"../../compilation/index.ts\";\nimport {\n attachPlugins,\n isStylesheet,\n loadCssGraph,\n loadEditorCssGraph,\n pluginLoader,\n type CssHost,\n type CssPluginInputs,\n type EditorCssGraph,\n type PluginRuntime,\n} from \"../../css/index.ts\";\nimport type { DesignSystemContext } from \"../../editor/index.ts\";\nimport type { TypeFactsEnvironment } from \"../../semantics/index.ts\";\nimport { compilerOptions, cssEntrypoint } from \"../options.ts\";\nimport { StylesheetEditor } from \"../stylesheet-editor.ts\";\n\n/**\n * Loads compiler inputs and CSS for one Node analysis project. AnalysisProject serializes calls\n * and installs captured document contents before asking this backend to resolve or load modules.\n */\nexport interface AnalysisHost extends CompilerHost {\n /** Absolute project directory used for identities and CSS paths. */\n root: string;\n /**\n * Compiler and preview settings fixed for this host's lifetime. Relative CSS and tsconfig paths\n * use root.\n */\n config: BaseConfig & {\n preview?: PreviewOptions;\n };\n /** CSS resolution and reads using the same captured document buffers as source loading. */\n css: CssHost;\n /** Fixed TypeScript settings selected when this host opens. */\n readonly typeFactsEnvironment: TypeFactsEnvironment;\n /** False disables additional semantic queries for this project. */\n readonly typeFacts?: false;\n /**\n * Checks whether a resolved target can be analyzed by this host.\n *\n * @param id - Full resolver identity of the target.\n * @returns Whether load can supply supported source for the identity.\n */\n supports(id: string): boolean;\n /**\n * Replaces all buffers used by subsequent source and CSS reads.\n *\n * @param documents - Absolute file paths to captured text. Missing entries use backend reads.\n * @returns A promise that resolves when subsequent reads can use the supplied snapshot.\n * @throws If the backend cannot install the supplied buffers.\n */\n setDocuments(documents: ReadonlyMap<string, string>): Promise<void>;\n /**\n * Discards backend caches before the next transaction. Must not overlap resolution or loads.\n *\n * @returns A promise that resolves when cached reads and resolutions have been invalidated.\n * @throws If backend invalidation fails.\n */\n invalidate(): Promise<void>;\n /**\n * Releases backend resources. The caller first waits for pending host operations.\n *\n * @returns A promise for cleanup completion.\n * @throws If backend cleanup fails.\n */\n close(): Promise<void>;\n}\n\n/**\n * Loads CSS and tracks the host dependencies that require a fresh design system.\n */\nexport class AnalysisCss {\n /** Files read by CSS or plugins. Open-buffer changes to these files reload CSS. */\n readonly #dependencies = new Set<string>();\n\n /** Delegates CSS operations to the host and records watched dependencies. */\n readonly #css: CssHost;\n\n /** CSS loader retained until a CSS update or explicit invalidation. */\n #loader?: NativeDesignSystemLoader;\n\n /** Session that uses the retained loader. Replaced when CSS changes. */\n #session?: NativeProjectSession;\n\n /** Query-only CSS graph, rebuilt after CSS changes and kept separate from strict analysis. */\n #editorCss?: EditorCssGraph;\n\n /** Identities that the retained loader marked for stylesheet lint, in load order. */\n #lintSources: string[] = [];\n\n /**\n * Plugin runtime of the retained loader. A CSS update keeps it as the previous runtime of the\n * next load, so definitions of unchanged plugins survive.\n */\n #plugins?: PluginRuntime;\n\n /** Host operations are called only inside the project's serialized transactions. */\n readonly #host: AnalysisHost;\n\n /**\n * Wraps CSS watching without loading files.\n * @param host - Host owned by the analysis project. Calls retain the host as their receiver.\n */\n constructor(host: AnalysisHost) {\n this.#host = host;\n this.#css = {\n resolve: (specifier, importer) => host.css.resolve(specifier, importer),\n read: (id) => host.css.read(id),\n documentUri: (id) => host.css.documentUri(id),\n sourceMapSource: (id) => host.css.sourceMapSource(id),\n plugins: host.css.plugins,\n lint: host.css.lint?.bind(host.css),\n watch: (id) => {\n this.#dependencies.add(id);\n host.css.watch(id);\n },\n };\n }\n\n /** Current strict loader, or undefined before loading or after invalidation. */\n get loader(): NativeDesignSystemLoader | undefined {\n return this.#loader;\n }\n\n /** Session that uses the strict loader, or undefined until load succeeds. */\n get session(): NativeProjectSession | undefined {\n return this.#session;\n }\n\n /** Plugin runtime of the latest successful load. Kept across CSS changes for reuse. */\n get plugins(): PluginRuntime | undefined {\n return this.#plugins;\n }\n\n /** Stylesheets marked for lint by the last strict load, in load order. */\n get lintSources(): readonly string[] {\n return this.#lintSources;\n }\n\n /**\n * Checks whether an open-buffer edit requires reloading CSS.\n *\n * @param id - Absolute path of the changed document.\n * @returns Whether it is a stylesheet or a dependency watched by CSS or a plugin.\n */\n affects(id: string): boolean {\n return isStylesheet(id) || [...this.#dependencies].some((file) => sameFile(file, id));\n }\n\n /** Returns the files that CSS or plugins have read. */\n get dependencies(): ReadonlySet<string> {\n return this.#dependencies;\n }\n\n /**\n * Discards loaders and the native session while keeping plugins available for the next load.\n */\n invalidate(): void {\n this.#loader = undefined;\n this.#session = undefined;\n this.#editorCss = undefined;\n }\n\n /**\n * Discards a failed plugin runtime and the loaders that depend on it before individual analysis retries.\n */\n discardPlugins(): void {\n this.invalidate();\n this.#plugins = undefined;\n }\n\n /**\n * Loads the configured CSS graph once until CSS invalidation clears it.\n *\n * @returns The retained loader with compiler options applied.\n * @throws If resolving, reading, or loading the CSS graph fails.\n */\n async load(): Promise<NativeDesignSystemLoader> {\n if (!this.#loader) {\n const css = path.resolve(this.#host.root, cssEntrypoint(this.#host.config));\n const loaded = await loadCssGraph(\n css,\n compilerOptions(this.#host.config),\n this.#css,\n undefined,\n undefined,\n this.#pluginInputs(),\n );\n this.#loader = loaded.loader;\n this.#lintSources = loaded.lintSources;\n this.#plugins = loaded.plugins;\n this.#session = new NativeProjectSession(\n this.#loader,\n false,\n \"development\",\n this.#host.config.naming,\n );\n attachPlugins(this.#session, this.#plugins, this.#plugins?.generation);\n }\n return this.#loader;\n }\n\n /**\n * Loads the design system for questions that read no source file.\n *\n * @returns A query over the definitions of the latest plugin load, and the plugin runtime.\n * @throws If resolving, reading, or loading the CSS graph fails.\n */\n async designSystem(): Promise<Pick<DesignSystemContext, \"query\" | \"plugins\">> {\n const loader = await this.load();\n return {\n query: (pluginLoader(this.#session!) ?? loader).editorQuery(),\n plugins: this.#plugins,\n };\n }\n\n /**\n * Selects the plugins of the project's CSS graph.\n *\n * @returns Configured plugins, the project root, and the runtime of the last load.\n */\n #pluginInputs(): CssPluginInputs {\n return {\n plugins: this.#host.config.plugins,\n tailwind: this.#host.config.tailwind,\n important: this.#host.config.important,\n root: this.#host.root,\n previous: this.#plugins,\n };\n }\n\n /**\n * Loads a query graph from original CSS or recovered definitions, without publishing its reports.\n *\n * @returns The cached editor graph, reusing the strict loader when available. Otherwise, a failed\n * original load is retried with recovered definitions. CSS invalidation clears this cache.\n * @throws If neither the original nor the recovered CSS graph can be resolved, read, and loaded.\n */\n async editor(): Promise<EditorCssGraph> {\n if (!this.#editorCss) {\n if (this.#loader) {\n this.#editorCss = {\n loader: this.#loader,\n resources: [],\n lintSources: this.#lintSources,\n recovered: false,\n plugins: this.#plugins,\n };\n } else {\n this.#editorCss = await loadEditorCssGraph(\n path.resolve(this.#host.root, cssEntrypoint(this.#host.config)),\n compilerOptions(this.#host.config),\n this.#css,\n this.#pluginInputs(),\n );\n }\n }\n return this.#editorCss;\n }\n\n /**\n * Creates a strict stylesheet editor and its lint reports.\n *\n * @param entry - Absolute stylesheet path in this host.\n * @returns Reports for that document and an editor using the same CSS definitions.\n * @throws If CSS loading, source reading, or plugin catalog loading fails.\n */\n async stylesheet(\n entry: string,\n ): Promise<{ reports: BindingReport[]; snapshot: StylesheetEditor }> {\n const loader = await this.load();\n const reports = loader.stylesheetReports().filter((report) => {\n const uri = report.primary.location.uri;\n return uri.startsWith(\"file:\")\n ? sameFile(fileURLToPath(uri), entry)\n : uri === this.#host.css.documentUri(entry);\n });\n return {\n reports,\n snapshot: new StylesheetEditor(\n entry,\n await this.#host.css.read(entry),\n reports,\n loader.editorQuery(),\n this.#host.config,\n (await this.#plugins?.catalog()) ?? [],\n this.#plugins,\n ),\n };\n }\n\n /**\n * Creates an editor from original CSS, or from recovered definitions when strict loading fails.\n *\n * @param entry - Absolute stylesheet path. Files outside the linted CSS graph are skipped.\n * @returns The editor and whether recovery was needed, or undefined outside the graph.\n * @throws If CSS recovery, source reading, or plugin catalog loading fails.\n */\n async editorSnapshot(\n entry: string,\n ): Promise<{ snapshot: StylesheetEditor; recovered: boolean } | undefined> {\n const graph = await this.editor();\n if (!graph.lintSources.some((source) => sameFile(source, entry))) {\n return undefined;\n }\n const reports = graph.recovered\n ? []\n : graph.loader\n .stylesheetReports()\n .filter((report) => report.primary.location.uri === this.#host.css.documentUri(entry));\n return {\n recovered: graph.recovered,\n snapshot: new StylesheetEditor(\n entry,\n await this.#host.css.read(entry),\n reports,\n graph.loader.editorQuery(),\n this.#host.config,\n (await graph.plugins?.catalog()) ?? [],\n graph.plugins,\n ),\n };\n }\n}\n\n/**\n * Compares file paths as the host filesystem does.\n *\n * @param a - File path resolved against the process working directory when relative.\n * @param b - File path resolved in the same way.\n * @returns Whether both paths name the same file, ignoring case on Windows.\n */\nexport function sameFile(a: string, b: string): boolean {\n /**\n * Normalizes a path for comparison.\n *\n * @param file - File path.\n * @returns The absolute path, lowercased on Windows.\n */\n const key = (file: string) =>\n process.platform === \"win32\" ? path.resolve(file).toLowerCase() : path.resolve(file);\n return key(a) === key(b);\n}\n","import path from \"node:path\";\n\nimport type { BindingReport } from \"@stillwind/native\";\n\nimport { analyzeModule, type ModuleAnalysis } from \"../../compilation/index.ts\";\nimport { CompilationProject, sourceKey } from \"../../compilation/project.ts\";\nimport { isStylesheet } from \"../../css/index.ts\";\nimport { queryPluginPaths } from \"../../css/plugins/paths.ts\";\nimport { prepareSourcePlugins } from \"../../css/plugins/session.ts\";\nimport {\n EditorSnapshot,\n queryDesignSystem,\n type DesignSystemRequest,\n type DesignSystemResult,\n type EditorRequest,\n type EditorResult,\n} from \"../../editor/index.ts\";\nimport {\n TypeScriptFactsService,\n type TypeFactsBackend,\n type TypeScriptFactsStats,\n} from \"../../semantics/index.ts\";\nimport { mapAnalysisReports } from \"../diagnostic-map.ts\";\nimport { StylesheetEditor } from \"../stylesheet-editor.ts\";\nimport { AnalysisCss, type AnalysisHost } from \"./host.ts\";\n\n/**\n * Result of an unpublished analysis at one project revision.\n */\nexport interface AnalysisResult {\n /** Entry resolver identity supplied to analyze. */\n entry: string;\n /** Project change counter captured when analysis was queued. */\n revision: number;\n /**\n * Complete describes available analysis inputs, even if reports contain compiler errors.\n * Incomplete retains partial findings or an exception. Stale and cancelled omit reports and graph.\n */\n status: \"complete\" | \"incomplete\" | \"stale\" | \"cancelled\";\n /** Findings mapped to original document URIs and zero-based UTF-16 positions. */\n reports: BindingReport[];\n /** Observed semantic graph, including dependency status and unavailable facts. Omitted on discard or early failure. */\n graph?: ModuleAnalysis;\n /** Caught exception as text. Compiler reports alone do not populate this field. */\n error?: string;\n}\n\n/**\n * Owns open buffers, checker queries, and serialized analysis for one host.\n */\nexport class AnalysisProject {\n /** Prepared sources shared by analyses of different entries. */\n readonly #compilation = new CompilationProject();\n\n /** CSS state and dependencies owned by this project. */\n readonly #css: AnalysisCss;\n\n /** Owned host. The project serializes its operations and closes it during cleanup. */\n readonly host: AnalysisHost;\n\n /** Optional factory used once when semantic analysis first needs a backend. */\n readonly #backend?: () => TypeFactsBackend;\n\n /** Unsaved original buffers keyed by absolute path and captured before each queued operation. */\n readonly #documents = new Map<\n string,\n {\n /** Complete original document text. */\n source: string;\n /** Last accepted safe integer version while the path is open. */\n version: number;\n }\n >();\n\n /** Editor snapshots retained by entry identity until their project revision changes. */\n readonly #editors = new Map<\n string,\n {\n /** Project change counter represented by this snapshot. */\n revision: number;\n /** Immutable view used for editor queries: a script graph or one linted stylesheet. */\n snapshot: EditorSnapshot | StylesheetEditor;\n /** True when CSS definitions were recovered and structural edits require strict analysis. */\n recovered?: boolean;\n }\n >();\n\n /** Lazily selected custom or Node semantic backend owned by this project. */\n #semantics?: TypeFactsBackend;\n\n /** Change counter used to discard pending analyses and editor answers. */\n #revision = 0;\n\n /** Serializes transactions and absorbs failures before subsequent work. */\n #queue: Promise<unknown> = Promise.resolve();\n\n /** Node backend retained separately to expose checker statistics. */\n #facts?: TypeScriptFactsService;\n\n /** Requests backend invalidation before the next transaction. */\n #dirty = true;\n\n /** Requests replacement of the cached CSS loader. */\n #cssDirty = true;\n\n /** Requests semantic disk-cache invalidation after an external change. */\n #diskDirty = true;\n\n /** Prevents transactions from producing new results during cleanup. */\n #closed = false;\n\n /**\n * Takes ownership of a backend without loading CSS or starting a checker.\n *\n * @param host - Initialized backend whose TypeScript environment uses the same root. Release\n * this project with `close` when its analysis services are no longer needed.\n * @param backend - Optional lazy semantic backend factory. Omission selects the Node checker.\n */\n constructor(host: AnalysisHost, backend?: () => TypeFactsBackend) {\n this.host = host;\n this.#css = new AnalysisCss(host);\n this.#backend = backend;\n }\n\n /**\n * Reads counters from the owned Node checker without exposing its mutable statistics object.\n * @returns A copy of the counters, or undefined before checker creation or with a custom backend.\n */\n get checkerStats(): TypeScriptFactsStats | undefined {\n return this.#facts && { ...this.#facts.stats };\n }\n\n /**\n * Stores an unsaved buffer. Changed text advances the revision and makes pending results stale.\n *\n * @param id - File path resolved from the process working directory when relative.\n * @param source - Complete original document text.\n * @param version - Safe integer greater than the open buffer's version. An identical buffer and\n * version have no effect. Identical text with a newer version updates only the version.\n * A document can restart its version sequence after closeDocument.\n * @throws If the version is invalid or does not increase for a changed open buffer.\n */\n update(id: string, source: string, version: number): void {\n id = path.resolve(id);\n const previous = this.#documents.get(id);\n if (previous?.version === version && previous.source === source) {\n return;\n }\n if (!Number.isSafeInteger(version) || (previous && previous.version >= version)) {\n throw new Error(\"Analysis document versions must increase\");\n }\n this.#documents.set(id, {\n source,\n version,\n });\n if (previous?.source === source) {\n return;\n }\n if (this.#compilation.source(id)?.document.code !== source) {\n this.#compilation.invalidate(id);\n }\n this.#revision++;\n this.#dirty = true;\n this.#cssDirty ||= this.#css.affects(id);\n }\n\n /**\n * Removes an unsaved buffer and advances the revision when one existed.\n *\n * @param id - File path, resolved in the same way as update. Later reads use the host's source\n * provider. Unknown paths have no effect.\n */\n closeDocument(id: string): void {\n id = path.resolve(id);\n if (this.#documents.delete(id)) {\n this.#compilation.invalidate(id);\n this.#revision++;\n this.#dirty = true;\n this.#cssDirty ||= this.#css.affects(id);\n }\n }\n\n /**\n * Lists the files that analysis has observed, for comparison with paths in watch notifications.\n *\n * @returns Keys from `sourceKey` for prepared sources, files that CSS or plugins read, and paths\n * that the checker read or tested, including missing paths. A custom semantic backend contributes\n * nothing.\n */\n reads(): Set<string> {\n return new Set([\n ...this.#compilation.sourceKeys(),\n ...[...this.#css.dependencies, ...(this.#facts?.dependencies ?? [])].map(sourceKey),\n ]);\n }\n\n /** Makes pending results stale. The next transaction rebuilds CSS and backend caches. */\n invalidate(): void {\n this.#compilation.invalidate();\n this.#revision++;\n this.#dirty = true;\n this.#cssDirty = true;\n this.#diskDirty = true;\n }\n\n /**\n * Lists the stylesheets that this project lints, using the document contents captured when this\n * method is called.\n *\n * @param editor - When false (the default), loads the original CSS and rejects invalid input.\n * When true, retries a failed load with recovered definitions so incomplete CSS can still\n * determine membership for completion, hover, and colors.\n * @returns Identities of the CSS entry and the imported files that the CSS host marks for lint,\n * in load order. Package CSS is excluded unless the host marks it. Returns an empty list\n * if the captured buffers become outdated before loading starts.\n * @throws If the project is closed, installing buffers or invalidating caches fails, or the\n * selected CSS loading mode fails.\n */\n stylesheets(editor = false): Promise<string[]> {\n const revision = this.#revision;\n const documents = new Map([...this.#documents].map(([id, document]) => [id, document.source]));\n const task = this.#queue.then(async () => {\n if (this.#closed) {\n throw new Error(\"Analysis project is closed\");\n }\n if (!(await this.#installDocuments(documents, revision))) {\n return [];\n }\n\n if (editor) {\n return [...(await this.#css.editor()).lintSources];\n }\n await this.#css.load();\n return [...this.#css.lintSources];\n });\n this.#queue = task.catch(() => {});\n return task;\n }\n\n /**\n * Queues analysis using the document contents and revision captured when this method is called.\n *\n * @param entry - Full resolver identity of a supported target, or of a stylesheet that\n * {@link stylesheets} lists. A stylesheet's reports are its stylesheet lint findings, and its\n * result has no graph. Membership filtering is performed by AnalysisWorkspace, not by this\n * project.\n * @param signal - Optional cancellation checked before and after queued work. Cancellation\n * discards results without interrupting a checker query that has already started.\n * @returns Reports for the entry and demanded semantic dependencies. Host failures appear as\n * incomplete results with error text. Unavailable semantic information appears in the graph's\n * unverified ranges. Stale and cancelled results omit reports and graphs.\n */\n analyze(entry: string, signal?: AbortSignal): Promise<AnalysisResult> {\n const revision = this.#revision;\n const documents = new Map([...this.#documents].map(([id, document]) => [id, document.source]));\n const task = this.#queue.then(async (): Promise<AnalysisResult> => {\n const before = this.#discardReason(revision, signal);\n if (before) {\n return discardedResult(entry, revision, before);\n }\n const result = await this.#analyzeSnapshot(entry, revision, documents);\n const after = this.#discardReason(revision, signal);\n return after ? discardedResult(entry, revision, after) : result;\n });\n\n this.#queue = task.catch(() => {});\n return task;\n }\n\n /**\n * Loads targets together and prepares plugin candidates using the current buffers.\n *\n * @param entries - Full resolver IDs. The workspace must apply project membership rules first.\n * @returns Completion of preparation. Closed or outdated requests stop without publishing results.\n * Loading and plugin failures are left for each target's analysis to report. A failed plugin\n * runtime is discarded before retrying.\n */\n prepare(entries: readonly string[]): Promise<void> {\n const revision = this.#revision;\n const documents = new Map([...this.#documents].map(([id, document]) => [id, document.source]));\n const task = this.#queue.then(async () => {\n if (this.#closed || this.#discardReason(revision)) {\n return;\n }\n try {\n if (!(await this.#installDocuments(documents, revision))) {\n return;\n }\n\n const loader = await this.#css.load();\n if (this.#discardReason(revision)) {\n return;\n }\n await this.#compilation.prepare(entries, this.host, this.#css.session!);\n await prepareSourcePlugins(this.#css.session!, loader, this.#compilation.texts());\n } catch {\n this.#css.discardPlugins();\n // Scoped analysis reports loading and preparation failures for their original targets.\n }\n });\n this.#queue = task.catch(() => {});\n return task;\n }\n\n /**\n * Queries the captured analysis for an entry. Buffer changes or cancellation discard its answer.\n * CSS completion, hover, resolution, and colors can load recovered definitions for incomplete\n * input. CSS sorting and lint fixes require the original graph to load successfully.\n * Plugin path completion and links read captured CSS inside the project root without loading\n * its graph or executing plugins.\n *\n * @param entry - Full resolver identity. The workspace applies target membership filtering.\n * @param request - Operation with offsets in the original UTF-16 document.\n * @param signal - Optional cancellation checked before and after queued work.\n * @returns The current editor answer, or undefined after closure, cancellation, a revision change,\n * failed entry analysis, or a semantic CSS query outside the graph's stylesheets marked for lint.\n * @throws If preparing a CSS query fails or the editor query rejects a candidate or preview.\n */\n query(\n entry: string,\n request: EditorRequest,\n signal?: AbortSignal,\n ): Promise<EditorResult | undefined> {\n const revision = this.#revision;\n const documents = new Map([...this.#documents].map(([id, document]) => [id, document.source]));\n const task = this.#queue.then(async () => {\n if (this.#closed || this.#discardReason(revision, signal)) {\n return undefined;\n }\n if (isStylesheet(entry) && [\"completion\", \"resolve\", \"links\"].includes(request.kind)) {\n if (!(await this.#installDocuments(documents, revision, signal))) {\n return undefined;\n }\n const text = await this.host.css.read(entry).catch(() => undefined);\n if (text === undefined) {\n return undefined;\n }\n const navigation = await queryPluginPaths(entry, text, request, {\n root: this.host.root,\n names: this.host.config.plugins?.map((plugin) => plugin.name) ?? [],\n host: this.host.css.plugins,\n documentUri: (id) => this.host.css.documentUri(id),\n });\n if (navigation) {\n return this.#discardReason(revision, signal) ? undefined : navigation;\n }\n }\n const structural = request.kind === \"sort\" || request.kind === \"fixes\";\n if (structural && this.#editors.get(entry)?.recovered) {\n this.#editors.delete(entry);\n }\n if (this.#editors.get(entry)?.revision !== revision) {\n if (\n isStylesheet(entry) &&\n [\"completion\", \"hover\", \"resolve\", \"colors\", \"colorPresentation\"].includes(request.kind)\n ) {\n if (!(await this.#installDocuments(documents, revision, signal))) {\n return undefined;\n }\n const editor = await this.#css.editorSnapshot(entry);\n if (!editor) {\n return undefined;\n }\n this.#editors.set(entry, {\n revision,\n ...editor,\n });\n } else {\n await this.#analyzeSnapshot(entry, revision, documents);\n }\n }\n const snapshot = this.#editors.get(entry)?.snapshot;\n await snapshot?.prepare(entry, request);\n const result = snapshot?.query(entry, request);\n return this.#discardReason(revision, signal) ? undefined : result;\n });\n this.#queue = task.catch(() => {});\n return task;\n }\n\n /**\n * Answers a question about the design system, using the current buffers.\n *\n * @param request - Theme, utility, or variant request.\n * @returns The answer, or undefined when the captured buffers become outdated.\n * @throws If the project is closed, CSS loading fails, or a plugin fails.\n */\n designSystem(request: DesignSystemRequest): Promise<DesignSystemResult | undefined> {\n const revision = this.#revision;\n const documents = new Map([...this.#documents].map(([id, document]) => [id, document.source]));\n const task = this.#queue.then(async () => {\n if (this.#closed) {\n throw new Error(\"Analysis project is closed\");\n }\n if (!(await this.#installDocuments(documents, revision))) {\n return undefined;\n }\n return queryDesignSystem(\n {\n ...(await this.#css.designSystem()),\n annotations: this.host.config.preview,\n },\n request,\n );\n });\n this.#queue = task.catch(() => {});\n return task;\n }\n\n /**\n * Marks the project closed, discards pending results, and waits for queued work before cleanup.\n * Repeated calls return without requesting further cleanup.\n *\n * @throws If checker or backend cleanup fails.\n * @returns A promise that resolves after queued analysis and cleanup. Repeated calls made after\n * closure starts return immediately. They do not wait for the first call's cleanup.\n */\n async close(): Promise<void> {\n if (this.#closed) {\n return;\n }\n\n this.#closed = true;\n this.#editors.clear();\n this.#revision++;\n await this.#queue;\n\n const results = await Promise.allSettled([\n Promise.resolve().then(() => this.#semantics?.close()),\n Promise.resolve().then(() => this.host.close()),\n ]);\n const errors = results.flatMap((result) =>\n result.status === \"rejected\" ? [result.reason] : [],\n );\n if (errors.length) {\n throw new AggregateError(errors, \"Failed to close Stillwind analysis services\");\n }\n }\n\n /**\n * Determines whether a captured operation can still publish its result.\n *\n * @param revision - Change counter captured when the operation was queued.\n * @param signal - Optional request cancellation, which takes precedence over staleness.\n * @returns The discard status, or undefined while the capture remains current.\n */\n #discardReason(revision: number, signal?: AbortSignal): \"cancelled\" | \"stale\" | undefined {\n if (signal?.aborted) {\n return \"cancelled\";\n }\n if (revision !== this.#revision) {\n return \"stale\";\n }\n return undefined;\n }\n\n /**\n * Installs captured buffers, refreshes caches, and retains an editor snapshot after compilation.\n *\n * @param entry - Supported full resolver identity to analyze.\n * @param revision - Change counter associated with the captured documents.\n * @param documents - Independent map of open absolute paths to original text.\n * @returns Findings mapped to original documents. Host failures become incomplete results with error text.\n */\n async #analyzeSnapshot(\n entry: string,\n revision: number,\n documents: ReadonlyMap<string, string>,\n ): Promise<AnalysisResult> {\n const result: AnalysisResult = { entry, revision, status: \"incomplete\", reports: [] };\n try {\n if (this.#closed) {\n throw new Error(\"Analysis project is closed\");\n }\n if (!(await this.#installDocuments(documents, revision))) {\n return result;\n }\n if (isStylesheet(entry)) {\n const stylesheet = await this.#css.stylesheet(entry);\n result.reports = stylesheet.reports;\n result.status = \"complete\";\n this.#editors.set(entry, {\n revision,\n snapshot: stylesheet.snapshot,\n });\n return result;\n }\n if (!this.host.supports?.(entry)) {\n throw new Error(`The ${this.host.constructor.name} host cannot analyze ${entry}`);\n }\n await this.#css.load();\n const loader = this.#css.loader!;\n const session = this.#css.session!;\n const graph = await analyzeModule(\n session,\n () => this.#semanticBackend(),\n entry,\n this.host,\n {\n overlayFiles: documents,\n },\n revision === this.#revision ? this.#compilation : undefined,\n );\n result.graph = structuredClone(graph);\n result.reports = await mapAnalysisReports(\n graph.batches.flatMap((batch) => batch.reports),\n graph.sources,\n (id) => this.host.read(id),\n );\n const editor = new EditorSnapshot(\n graph,\n session,\n loader,\n this.host.config,\n (await this.#css.plugins?.catalog()) ?? [],\n this.#css.plugins,\n );\n result.reports.push(...editor.reports());\n this.#editors.set(entry, {\n revision,\n snapshot: editor,\n });\n result.status = analysisComplete(graph) ? \"complete\" : \"incomplete\";\n } catch (error) {\n result.error = error instanceof Error ? error.message : String(error);\n if (error instanceof Error && \"reports\" in error && Array.isArray(error.reports)) {\n result.reports = error.reports as BindingReport[];\n }\n }\n return result;\n }\n\n /**\n * Installs captured buffers and refreshes caches before work continues.\n *\n * @param documents - Original buffers captured with the supplied revision.\n * @param revision - Revision that owns this queued operation.\n * @param signal - Optional cancellation checked between host operations.\n * @returns Whether the operation can continue with these buffers after cache refresh.\n * @throws If installing buffers or refreshing host or checker caches fails.\n */\n async #installDocuments(\n documents: ReadonlyMap<string, string>,\n revision: number,\n signal?: AbortSignal,\n ): Promise<boolean> {\n await this.host.setDocuments(documents);\n if (this.#discardReason(revision, signal)) {\n return false;\n }\n await this.#resetCaches();\n return !this.#discardReason(revision, signal);\n }\n\n /**\n * Consumes dirty flags and invalidates semantic, CSS, and host caches as requested.\n *\n * @returns Completion of required invalidation, or no work when the project is clean.\n * @throws If semantic or host invalidation fails.\n */\n async #resetCaches(): Promise<void> {\n if (!this.#dirty) {\n return;\n }\n this.#dirty = false;\n if (this.#diskDirty) {\n this.#diskDirty = false;\n await this.#semantics?.invalidate();\n }\n if (this.#cssDirty) {\n this.#cssDirty = false;\n this.#css.invalidate();\n }\n await this.host.invalidate();\n }\n\n /**\n * Lazily selects the custom backend or creates the Node checker with fixed project settings.\n *\n * @returns The owned backend, or undefined when type facts are disabled.\n * @throws If backend creation fails.\n */\n #semanticBackend(): TypeFactsBackend | undefined {\n if (this.host.typeFacts === false) {\n return undefined;\n }\n if (!this.#semantics) {\n const backend = this.#backend?.();\n if (backend) {\n this.#semantics = backend;\n } else {\n this.#facts = new TypeScriptFactsService(this.host.typeFactsEnvironment);\n this.#semantics = this.#facts;\n }\n }\n return this.#semantics;\n }\n}\n\n/**\n * Creates a result that carries no reports or graph after a capture becomes unusable.\n *\n * @param entry - Requested resolver identity.\n * @param revision - Change counter captured when the request was queued.\n * @param status - Reason the capture was discarded.\n * @returns An empty analysis result preserving request identity and revision.\n */\nfunction discardedResult(\n entry: string,\n revision: number,\n status: \"stale\" | \"cancelled\",\n): AnalysisResult {\n return {\n entry,\n revision,\n status,\n reports: [],\n };\n}\n\n/**\n * Checks whether all demanded semantic inputs were available, independently of compiler error reports.\n *\n * @param graph - Observed graph returned by compilation.\n * @returns Whether no ranges are unverified and no dependency is unresolved or unsupported.\n */\nfunction analysisComplete(graph: ModuleAnalysis): boolean {\n return (\n graph.unverified.length === 0 &&\n !graph.dependencies.some(\n (dependency) => dependency.status === \"unresolved\" || dependency.status === \"unsupported\",\n )\n );\n}\n","import {\n NativeProjectSession,\n type BindingOutput,\n type NativeDesignSystemLoader,\n} from \"@stillwind/native\";\n\nimport { cleanModuleId, compileModule, type CompilerHost } from \"../compilation/index.ts\";\nimport type { LoadedCssGraph } from \"../css/css.ts\";\nimport { attachPlugins } from \"../css/plugins/session.ts\";\nimport {\n TypeScriptFactsService,\n resolveTypeFactsEnvironment,\n type TypeFactsEnvironment,\n type TypeScriptFactsStats,\n} from \"../semantics/index.ts\";\n\n/** Versioned source buffer that can replace a filesystem read during editor analysis. */\nexport interface EditorDocument {\n /**\n * Resolver identity of the document. Editor operations remove query and fragment suffixes for\n * ordinary file IDs.\n */\n id: string;\n /**\n * Safe integer, including negative values, that must increase for each update while this\n * document stays open.\n */\n version: number;\n /** Current unsaved document text supplied to source preparation and compilation. */\n source: string;\n}\n\n/**\n * Result of analyzing one document against a captured editor revision, with any previously\n * successful preview.\n */\nexport interface EditorAnalysis {\n /** Copy of the entry buffer captured when analysis started. */\n document: EditorDocument;\n /**\n * Project change counter captured at analysis start. Any document update, close of an open\n * document, or invalidation advances it.\n */\n revision: number;\n /** Observed coverage: the result includes only dependencies demanded by this analysis. */\n coverage: \"observed\";\n /**\n * Success means usable code without compiler errors or deny-level lint. Partial retains an\n * incomplete or rejected result. Stale means the project revision changed. Cancelled means the\n * signal was aborted. Stale and cancelled results omit output.\n */\n status: \"success\" | \"partial\" | \"stale\" | \"cancelled\";\n /**\n * Current compilation output, including reports for partial results when available. Stale or\n * cancelled analysis removes this field.\n */\n output?: BindingOutput;\n /**\n * Caught exception message. Compiler reports returned in collect mode do not populate this field.\n */\n error?: string;\n /**\n * Distinct dependency resolver identities observed by the compilation, in first observation\n * order, including those observed before failure.\n */\n dependencies: string[];\n /**\n * Copy of checker counters when this analysis needed type facts. Omitted when no checker was\n * created.\n */\n checkerStats?: TypeScriptFactsStats;\n /**\n * Successful preview retained for this document when analysis started. Failed, stale, or\n * cancelled attempts do not replace the stored success.\n */\n previousSuccess?: {\n /** Document version that produced the retained preview. */\n version: number;\n /** Project revision captured by the successful analysis. */\n revision: number;\n /** Successful compiler output retained for editor preview. */\n output: BindingOutput;\n };\n}\n\n/** Versioned, unpublished previews. Each request owns its compiler session. */\nexport class EditorProject {\n /**\n * Open unsaved buffers keyed by cleaned resolver identity. Analysis captures a map of these\n * buffers before asynchronous work.\n */\n readonly #documents = new Map<string, EditorDocument>();\n /**\n * Most recent successful output for each cleaned document identity, retained across later\n * unsuccessful attempts.\n */\n readonly #successes = new Map<string, NonNullable<EditorAnalysis[\"previousSuccess\"]>>();\n /**\n * Project change counter used to reject results whose source or dependencies changed during\n * analysis.\n */\n #revision = 0;\n\n /** Filesystem root used to initialize the type-facts service when an analysis needs it. */\n readonly root: string;\n /**\n * Dependency resolver and source metadata operations. Open buffers override its reader during\n * analysis.\n */\n readonly host: CompilerHost;\n /**\n * Factory that must return a completed design-system loader suitable for a new compiler session\n * on every analysis, or a loaded CSS graph whose plugins define dynamic candidates.\n */\n readonly designSystem: () =>\n | NativeDesignSystemLoader\n | Pick<LoadedCssGraph, \"loader\" | \"plugins\">;\n /** Fixed checker settings reused by independent analyses and retained without rereading tsconfig. */\n readonly #typeFactsEnvironment: TypeFactsEnvironment;\n\n /**\n * Creates an editor project without opening documents or creating a checker.\n *\n * @param root - Filesystem project root used for checker resolution.\n * @param host - Source descriptors, dependency resolver, and reader used by analysis.\n * @param designSystem - Factory returning a loaded design system, or a loaded CSS graph with its\n * plugins, for each independent analysis.\n * @param typeFactsEnvironment - Fixed checker settings whose root matches this project. Omission\n * selects an existing root tsconfig or isolated defaults.\n */\n constructor(\n root: string,\n host: CompilerHost,\n designSystem: () => NativeDesignSystemLoader | Pick<LoadedCssGraph, \"loader\" | \"plugins\">,\n typeFactsEnvironment = resolveTypeFactsEnvironment(root),\n ) {\n this.root = root;\n this.host = host;\n this.designSystem = designSystem;\n this.#typeFactsEnvironment = typeFactsEnvironment;\n }\n\n /**\n * Stores an unsaved buffer and advances the project revision.\n *\n * @param document - Buffer with a safe integer version greater than the current version for its\n * cleaned identity. A copy is stored.\n * @throws If the version is not a safe integer or does not increase for an open document.\n */\n update(document: EditorDocument): void {\n const id = cleanModuleId(document.id);\n const previous = this.#documents.get(id);\n if (\n !Number.isSafeInteger(document.version) ||\n (previous && document.version <= previous.version)\n ) {\n throw new Error(\"Editor document versions must increase monotonically\");\n }\n this.#documents.set(id, { ...document, id });\n this.#revision += 1;\n }\n\n /**\n * Removes an open buffer and its retained successful preview.\n *\n * @param id - Document identity, cleaned in the same way as `update`. Removing an open buffer\n * advances the revision. An unknown identity has no effect.\n */\n close(id: string): void {\n id = cleanModuleId(id);\n if (this.#documents.delete(id)) {\n this.#revision += 1;\n }\n this.#successes.delete(id);\n }\n\n /**\n * Advances the revision after disk dependencies or the design system change, making in-progress\n * analysis stale.\n */\n invalidate(): void {\n this.#revision += 1;\n }\n\n /**\n * Compiles an open document with the unsaved buffers captured at analysis start.\n *\n * The analysis owns a new compiler session and closes any checker it creates. Dependency reads\n * prefer captured open buffers. Compiler diagnostics are collected. Other failures become the\n * returned error text. Stale or cancelled work retains neither current output nor a new\n * successful preview.\n *\n * @param id - Identity of an open document. Ordinary query and fragment suffixes are removed.\n * @param signal - Optional cancellation signal checked around asynchronous dependency operations\n * and before returning.\n * @returns A promise for the versioned result, observed dependencies, optional checker counters,\n * and the success retained when analysis started.\n * @throws If the document is not open. Cleanup failures can also reject the promise.\n */\n async analyze(id: string, signal?: AbortSignal): Promise<EditorAnalysis> {\n id = cleanModuleId(id);\n const document = this.#documents.get(id);\n if (!document) {\n throw new Error(`Editor document is not open: ${id}`);\n }\n const revision = this.#revision;\n const overlays = new Map(this.#documents);\n const dependencies = new Set<string>();\n const result: EditorAnalysis = {\n document: { ...document },\n revision,\n coverage: \"observed\",\n status: \"partial\",\n dependencies: [],\n previousSuccess: this.#successes.get(id),\n };\n /**\n * Requires this analysis to retain the captured project revision and an active signal.\n * @throws If cancellation or a newer project revision makes this analysis obsolete.\n */\n const assertActive = () => {\n if (signal?.aborted) {\n throw new Error(\"Editor analysis cancelled\");\n }\n if (revision !== this.#revision) {\n throw new Error(\"Editor analysis superseded\");\n }\n };\n let facts: TypeScriptFactsService | undefined;\n try {\n assertActive();\n const design = this.designSystem();\n const graph =\n \"loader\" in design\n ? design\n : {\n loader: design,\n plugins: undefined,\n };\n const session = new NativeProjectSession(graph.loader, false);\n attachPlugins(session, graph.plugins);\n const output = await compileModule(\n session,\n () => {\n facts ??= new TypeScriptFactsService(this.#typeFactsEnvironment);\n return facts;\n },\n document.source,\n id,\n {\n describe: (dependency) => this.host.describe(dependency),\n resolve: async (...args) => {\n assertActive();\n const resolved = await this.host.resolve(...args);\n assertActive();\n return resolved;\n },\n read: async (dependency) => {\n assertActive();\n const source =\n overlays.get(cleanModuleId(dependency))?.source ?? (await this.host.read(dependency));\n assertActive();\n return source;\n },\n watch: (dependency) => dependencies.add(dependency),\n warn: () => {},\n },\n {\n diagnostics: \"collect\",\n typeFactsInputs: {\n overlayFiles: new Map([...overlays].map(([id, value]) => [id, value.source])),\n },\n },\n );\n assertActive();\n result.output = output;\n const denied = output?.lintFindings.some(\n (finding) => output.lintSettings[finding.rule] === \"deny\",\n );\n if (output?.code != null && output.diagnostics.length === 0 && !denied) {\n result.status = \"success\";\n this.#successes.set(id, {\n version: document.version,\n revision,\n output,\n });\n }\n } catch (error) {\n result.error = error instanceof Error ? error.message : String(error);\n } finally {\n if (facts) {\n result.checkerStats = {\n ...facts.stats,\n };\n }\n facts?.close();\n result.dependencies = [...dependencies];\n }\n if (signal?.aborted || revision !== this.#revision) {\n result.status = signal?.aborted ? \"cancelled\" : \"stale\";\n delete result.output;\n }\n return result;\n }\n}\n","import { readFile, readdir, stat } from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\n\nimport type { PluginDirectoryEntry } from \"@stillwind/config\";\nimport { evaluateModule } from \"@stillwind/config/node\";\n\nimport { defaultPluginExport, type LoadedPlugin, type PluginHost } from \"../css/plugins/host.ts\";\nimport { completePluginPaths } from \"../css/plugins/paths.ts\";\n\n/**\n * Lists disk children for plugin completion and plugin directory reads, following\n * directory symlinks.\n * @param id - Absolute directory to enumerate without loading its scripts.\n * @returns Immediate entries in filesystem order. Broken symlinks are treated as files.\n * @throws If the directory cannot be read.\n */\nexport async function readPluginDirectory(id: string): Promise<PluginDirectoryEntry[]> {\n return Promise.all(\n (await readdir(id, { withFileTypes: true })).map(async (entry) => ({\n name: entry.name,\n directory:\n entry.isDirectory() ||\n (entry.isSymbolicLink() &&\n (await stat(path.join(id, entry.name))\n .then((value) => value.isDirectory())\n .catch(() => false))),\n })),\n );\n}\n\n/**\n * Plugin files evaluated from a relative or absolute `@plugin` path, keyed by entry path. Each entry\n * records the text of its bundled local files, so a load reuses the plugin only while every text is\n * unchanged.\n */\nconst files = new Map<\n string,\n {\n /** Text of each bundled local file when the plugin was evaluated. */\n sources: ReadonlyMap<string, string>;\n /** Files that the evaluation observed, including resolved packages. */\n dependencies: readonly string[];\n /** Plugin that the entry exports by default. */\n plugin: LoadedPlugin;\n }\n>();\n\n/**\n * Loads plugin packages and plugin files with Node module resolution from the stylesheet that\n * contains the `@plugin` statement, and reads files from the filesystem.\n *\n * A package specifier is imported with Node's module cache, so a changed package takes effect only\n * in a new process. A relative or absolute path is bundled with its local imports and evaluated\n * again after any of those files changes.\n */\nexport const nodePluginHost: PluginHost = {\n complete: (prefix, importer, root) =>\n completePluginPaths(prefix, importer, root, {\n read: (id) => readFile(id, \"utf8\"),\n directory: readPluginDirectory,\n }),\n async load(specifier, importer, watch) {\n const resolved = createRequire(importer).resolve(specifier);\n if (!specifier.startsWith(\".\") && !path.isAbsolute(specifier)) {\n return defaultPluginExport(await import(pathToFileURL(resolved).href), specifier);\n }\n let cached = files.get(resolved);\n if (\n !cached ||\n !(await Promise.all(\n [...cached.sources].map(async ([file, text]) =>\n readFile(file, \"utf8\").then(\n (current) => current === text,\n () => false,\n ),\n ),\n ).then((results) => results.every(Boolean)))\n ) {\n const { exported, dependencies, sources } = await evaluateModule(resolved);\n cached = {\n sources,\n dependencies,\n plugin: defaultPluginExport(\n {\n default: exported,\n },\n specifier,\n ),\n };\n files.set(resolved, cached);\n }\n for (const dependency of cached.dependencies) {\n watch(dependency);\n }\n return cached.plugin;\n },\n async resolve(specifier, importer) {\n try {\n return createRequire(importer).resolve(specifier);\n } catch {\n return undefined;\n }\n },\n async read(path) {\n return await readFile(path, \"utf8\");\n },\n list: readPluginDirectory,\n};\n","import path from \"node:path\";\n\nimport { ResolverFactory } from \"oxc-resolver\";\n\n/**\n * Creates a resolver for stylesheet imports. It selects `.css` files, the `style` export\n * condition, and the `style` package field, as CSS tooling resolves packages such as\n * `tw-animate-css`.\n *\n * @returns A new resolver with its own cache.\n */\nexport function stylesheetResolver(): ResolverFactory {\n return new ResolverFactory({\n extensions: [\".css\"],\n conditionNames: [\"style\", \"import\", \"default\"],\n mainFields: [\"style\", \"main\"],\n });\n}\n\n/**\n * Creates a stylesheet package resolver for hosts whose own resolver selects JavaScript entries.\n *\n * @returns A function that resolves a specifier from an importing file to a path, or to\n * undefined when the specifier does not resolve.\n */\nexport function createStylesheetResolver(): (\n specifier: string,\n importer: string,\n) => Promise<string | undefined> {\n const resolver = stylesheetResolver();\n return async (specifier, importer) =>\n (await resolver.async(path.dirname(importer), specifier)).path;\n}\n","import { readFile, stat } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport process from \"node:process\";\nimport { pathToFileURL } from \"node:url\";\n\nimport { captureProjectConfig, type AnalysisProjectConfig } from \"@stillwind/config\";\nimport { resolveProjectConfig } from \"@stillwind/config/node\";\nimport { ResolverFactory } from \"oxc-resolver\";\n\nimport { fileModuleDescriptor } from \"../compilation/index.ts\";\nimport { completePluginPaths, pluginDirectory } from \"../css/plugins/paths.ts\";\nimport { resolveTypeFactsEnvironment } from \"../semantics/index.ts\";\nimport type { AnalysisHost } from \"./analysis/host.ts\";\nimport { nodePluginHost, readPluginDirectory } from \"./plugins.ts\";\nimport { stylesheetResolver } from \"./stylesheets.ts\";\n\n/**\n * Creates a Node analysis host with captured buffers, source providers, and CSS resolution.\n * Custom source resolution takes precedence over identities supplied by the semantic backend.\n *\n * @param config - One evaluated project. Custom source and projection callbacks receive the\n * buffers installed by setDocuments. Prepared inputs bypass custom projection preparation.\n * @param directory - Configuration directory used to resolve a relative project root.\n * @returns An owned host with fixed TypeScript settings. CSS and checker creation remain lazy.\n * @throws If TypeScript settings cannot be selected or the CSS resolver cannot be initialized.\n */\nexport function createFileSystemAnalysisHost(\n config: AnalysisProjectConfig,\n directory: string,\n): AnalysisHost {\n config = captureProjectConfig(config);\n const resolvedConfig = resolveProjectConfig(config, directory);\n const root = resolvedConfig.root!;\n const typeFactsEnvironment = resolveTypeFactsEnvironment(root, resolvedConfig.tsconfig);\n const cssResolver = stylesheetResolver();\n const frameworkResolver = new ResolverFactory({\n extensions: [\".astro\", \".svelte\", \".vue\"],\n conditionNames: [\"import\", \"default\"],\n tsconfig:\n typeFactsEnvironment.project.kind === \"configured\"\n ? {\n configFile: typeFactsEnvironment.project.configPath,\n references: \"auto\",\n }\n : undefined,\n });\n\n let documents: ReadonlyMap<string, string> = new Map();\n let buffers: ReadonlyMap<string, string> = new Map();\n\n /**\n * Normalizes paths for lookup in the captured buffer map.\n *\n * @param id - File path resolved against the process working directory when relative.\n * @returns An absolute path, lowercased on Windows to share keys across case variations.\n */\n const documentKey = (id: string) =>\n process.platform === \"win32\" ? path.resolve(id).toLowerCase() : path.resolve(id);\n\n /**\n * Reads a captured buffer before falling back to the physical file.\n *\n * @param id - File path accepted by the Node filesystem.\n * @returns Captured text when present, otherwise UTF-8 file text.\n * @throws If the required physical file cannot be read.\n */\n const read = (id: string) =>\n Promise.resolve(buffers.get(documentKey(id)) ?? readFile(id, \"utf8\"));\n\n /**\n * Lists a directory with the open buffers inside it, so that an unsaved file appears as an entry.\n *\n * @param id - Absolute directory path.\n * @returns Disk and buffered entries, each listed once.\n * @throws If neither the disk nor the buffers contain the directory.\n */\n const list = async (id: string) => {\n const buffered = pluginDirectory(documents, id, process.platform !== \"win32\");\n const entries = [\n ...(await readPluginDirectory(id).catch((error: unknown) => {\n if (!buffered.length) {\n throw error;\n }\n return [];\n })),\n ...buffered,\n ];\n return [\n ...new Map(\n entries.map((entry) => [\n process.platform === \"win32\" ? entry.name.toLowerCase() : entry.name,\n entry,\n ]),\n ).values(),\n ];\n };\n\n /**\n * Selects script and framework sources eligible for default analysis.\n *\n * @param id - File path tested case-insensitively by extension.\n * @returns Whether the path has a supported extension and is not a TypeScript declaration file.\n */\n const supports = (id: string) =>\n /\\.(?:[cm]?[jt]sx?|vue|svelte|astro)$/i.test(id) && !/\\.d\\.[cm]?ts$/i.test(id);\n\n return {\n root,\n config: resolvedConfig,\n typeFactsResolution: true,\n typeFacts: config.typeFacts,\n typeFactsEnvironment,\n supports: (id) =>\n config.sources?.kind === \"custom\" ? config.sources.supports(id) : supports(id),\n describe: (id) => fileModuleDescriptor(root, id),\n read,\n load: async (id) => {\n const context = { root, documents };\n const input =\n config.sources?.kind === \"custom\"\n ? await config.sources.load(id, context)\n : {\n resolverId: id,\n ...fileModuleDescriptor(root, id),\n document: {\n ...fileModuleDescriptor(root, id).document,\n code: await read(id),\n },\n };\n return !(\"kind\" in input) && config.projection?.kind === \"custom\"\n ? config.projection.prepare(input)\n : input;\n },\n resolve: async (specifier, importer) => {\n if (config.sources?.kind === \"custom\") {\n const id = await config.sources.resolve?.(specifier, importer, { root, documents });\n return id\n ? {\n id,\n }\n : null;\n }\n if (/\\.(?:vue|svelte|astro)$/i.test(specifier)) {\n if (specifier.startsWith(\".\") || path.isAbsolute(specifier)) {\n const id = path.resolve(path.dirname(importer), specifier);\n if (buffers.has(documentKey(id))) {\n return {\n id,\n };\n }\n }\n const id = (await frameworkResolver.async(path.dirname(importer), specifier)).path;\n return id\n ? {\n id,\n }\n : null;\n }\n return null;\n },\n watch: () => {},\n warn: () => {},\n css: {\n resolve: async (specifier, importer) => {\n const result = await cssResolver.async(path.dirname(importer), specifier);\n if (!result.path) {\n throw new Error(`Cannot resolve CSS ${specifier} from ${importer}: ${result.error}`);\n }\n return result.path;\n },\n read,\n documentUri: (id) => pathToFileURL(id).href,\n sourceMapSource: (id) => pathToFileURL(id).href,\n watch: () => {},\n plugins: {\n ...nodePluginHost,\n read,\n /**\n * Resolves a plugin file request, preferring open buffers for a relative or absolute\n * path so that an unsaved plugin file resolves.\n *\n * @param specifier - Package specifier or path.\n * @param importer - Stylesheet that contains the statement.\n * @returns A buffered or existing file, or undefined when the request does not resolve\n * to a file.\n */\n async resolve(specifier, importer) {\n if (specifier.startsWith(\".\") || path.isAbsolute(specifier)) {\n const base = path.resolve(path.dirname(importer), specifier);\n for (const suffix of [\"\", \".js\", \".json\", \"/index.js\"]) {\n const candidate = base + suffix;\n if (buffers.has(documentKey(candidate))) {\n return candidate;\n }\n }\n }\n const resolved = await nodePluginHost.resolve(specifier, importer);\n return resolved &&\n (await stat(resolved)\n .then((value) => value.isFile())\n .catch(() => false))\n ? resolved\n : undefined;\n },\n list,\n complete: (prefix, importer, projectRoot) =>\n completePluginPaths(prefix, importer, projectRoot, {\n read,\n directory: (id) => list(id).catch(() => []),\n }),\n },\n },\n setDocuments: async (next) => {\n documents = next;\n buffers = new Map([...next].map(([id, text]) => [documentKey(id), text]));\n },\n invalidate: async () => {\n cssResolver.clearCache();\n frameworkResolver.clearCache();\n },\n close: async () => {},\n };\n}\n","import path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nimport { captureProjectConfig, type CapturedProjectConfig } from \"@stillwind/config\";\nimport { loadConfiguration } from \"@stillwind/config/node\";\nimport { minimatch } from \"minimatch\";\nimport { glob } from \"tinyglobby\";\n\nimport { sourceKey } from \"../compilation/project.ts\";\nimport { isStylesheet } from \"../css/index.ts\";\nimport type {\n DesignSystemRequest,\n DesignSystemResult,\n EditorRequest,\n EditorResult,\n} from \"../editor/index.ts\";\nimport { sameFile } from \"./analysis/host.ts\";\nimport { AnalysisProject, type AnalysisResult } from \"./analysis/project.ts\";\nimport { createFileSystemAnalysisHost } from \"./filesystem.ts\";\n\n/** A project's configuration and results, retained independently when scopes overlap. */\nexport interface WorkspaceProject {\n /** Evaluated project settings. Relative root and scope globs use configFile's directory and host root. */\n readonly config: CapturedProjectConfig;\n /** Absolute path of the configuration that owns this project. */\n readonly configFile: string;\n /** Owned analysis state. Buffers outside this project's target scope can still be dependencies. */\n readonly analysis: AnalysisProject;\n}\n\n/** Analysis results for one explicitly enumerated target in one project. */\nexport interface WorkspaceResult {\n /** Zero-based index into the workspace's projects array. */\n project: number;\n /** Absolute configuration path used to group this result. */\n config: string;\n /** Captured result whose reports have been filtered to this project's configured scope. */\n result: AnalysisResult;\n}\n\n/**\n * Recognizes a declaration file that a target glob such as `*.ts` selects by accident. Other files\n * that the host cannot analyze stay in scope, so their analysis reports the wrong `files` entry.\n *\n * @param project - Project whose host decides what it can analyze.\n * @param file - Absolute file path.\n * @returns Whether the file is a declaration file that the host cannot analyze.\n */\nfunction skipsDeclaration(project: WorkspaceProject, file: string): boolean {\n return /.d.[cm]?ts$/i.test(file) && !project.analysis.host.supports(file);\n}\n\n/** Owns every project in one evaluated configuration and keeps overlapping scopes independent. */\nexport class AnalysisWorkspace {\n /** Absolute paths with open buffers, including paths outside the configured target globs. */\n readonly #openDocuments = new Set<string>();\n /** Configuration files and imports whose changes require reopening this workspace. */\n readonly #configurationDependencies: readonly string[];\n /** Absolute path evaluated when this workspace opened. Reopen the workspace to apply configuration changes. */\n readonly configFile: string;\n /** Fixed project records in configuration order. Each analysis service owns mutable state. */\n readonly projects: readonly WorkspaceProject[];\n\n /**\n * Retains the evaluated configuration and takes ownership of its initialized projects.\n *\n * @param configFile - Absolute configuration path.\n * @param projects - Successfully opened hosts in configuration order.\n * @param dependencies - Absolute configuration and import paths recorded during evaluation.\n */\n private constructor(\n configFile: string,\n projects: WorkspaceProject[],\n dependencies: readonly string[],\n ) {\n this.configFile = configFile;\n this.projects = projects;\n this.#configurationDependencies = dependencies;\n }\n\n /**\n * Evaluates configuration and opens every project, closing earlier hosts if initialization fails.\n *\n * @param configFile - Trusted configuration path. Relative paths use the process working directory.\n * @returns A workspace that owns its project hosts. Close it when replacing the configuration.\n * @throws If configuration evaluation or project initialization fails.\n */\n static async open(configFile: string): Promise<AnalysisWorkspace> {\n configFile = path.resolve(configFile);\n const { config, dependencies } = await loadConfiguration(configFile);\n const projects: WorkspaceProject[] = [];\n try {\n for (const supplied of config.projects) {\n const project = captureProjectConfig(supplied);\n const host = createFileSystemAnalysisHost(project, path.dirname(configFile));\n projects.push({\n config: project,\n configFile,\n analysis: new AnalysisProject(host),\n });\n }\n return new AnalysisWorkspace(configFile, projects, dependencies);\n } catch (error) {\n await Promise.allSettled(projects.map((project) => project.analysis.close()));\n throw error;\n }\n }\n\n /**\n * Matches target scope independently of whether the source exists on disk.\n *\n * @param project - Project whose root, include globs, and exclusions define membership.\n * @param file - Absolute file path to test.\n * @returns Whether the path matches files without matching excludes, node_modules, or .git. A\n * declaration file that the host cannot analyze is outside the scope.\n * Dependency traversal does not use this filter.\n */\n includes(project: WorkspaceProject, file: string): boolean {\n const name = path.relative(project.analysis.host.root, file).replaceAll(\"\\\\\", \"/\");\n /**\n * Matches this project-relative path, including dotfiles.\n * @param pattern - Include or exclude glob interpreted by minimatch.\n * @returns Whether the normalized path matches the pattern.\n */\n const matches = (pattern: string) =>\n minimatch(name, pattern, {\n dot: true,\n });\n return (\n !skipsDeclaration(project, file) &&\n project.config.files.some(matches) &&\n ![\"**/node_modules/**\", \"**/.git/**\", ...(project.config.exclude ?? [])].some(matches)\n );\n }\n\n /**\n * Checks whether the project lints a stylesheet. Loading the project's CSS graph decides it.\n *\n * @param project - Project whose CSS graph lists its linted stylesheets.\n * @param file - Absolute file path to test.\n * @param editor - When false (the default), requires the original CSS graph to load successfully.\n * When true, retries a failed load with recovered definitions so completion, hover, and colors\n * can still identify stylesheet membership while the CSS is incomplete.\n * @returns Whether the file is the CSS entry or an imported file that the CSS host marks for\n * lint. Returns false for other extensions or when the selected loading mode fails. Ordinary\n * script analysis reports CSS loading failures.\n */\n async lintsStylesheet(project: WorkspaceProject, file: string, editor = false): Promise<boolean> {\n if (!isStylesheet(file)) {\n return false;\n }\n const sources = await project.analysis.stylesheets(editor).catch(() => []);\n return sources.some((source) => sameFile(source, file));\n }\n\n /**\n * Enumerates existing target files independently of dependency traversal.\n *\n * @param project - Project whose files and excludes globs are relative to its host root.\n * @param patterns - Optional additional include globs relative to the same root. An empty list\n * adds no filtering. These patterns cannot expand the configured scope.\n * @param options - Target kinds to add to the configured script targets.\n * @returns Sorted absolute target paths. Unsaved files absent from disk are not enumerated.\n * @throws If filesystem enumeration fails.\n */\n async targets(\n project: WorkspaceProject,\n patterns?: string[],\n options: {\n /** Adds the stylesheets that the project lints, as {@link lintsStylesheet} selects them. */\n stylesheets?: boolean;\n } = {},\n ): Promise<string[]> {\n const filters = patterns?.map((pattern) => {\n if (path.isAbsolute(pattern)) {\n return {\n file: path.normalize(pattern),\n };\n }\n return {\n pattern: pattern.replace(/^(\\.\\/)+/, \"\"),\n };\n });\n const files = (\n await glob(project.config.files, {\n cwd: project.analysis.host.root,\n absolute: true,\n onlyFiles: true,\n dot: true,\n ignore: [\"**/node_modules/**\", \"**/.git/**\", ...(project.config.exclude ?? [])],\n })\n ).filter((file) => !skipsDeclaration(project, file));\n if (options.stylesheets) {\n files.push(...(await project.analysis.stylesheets().catch(() => [])));\n }\n return files\n .filter(\n (file, index) =>\n files.findIndex((other) => sameFile(other, file)) === index &&\n (!filters?.length ||\n filters.some((filter) =>\n filter.file !== undefined\n ? path.normalize(file) === filter.file\n : minimatch(\n path.relative(project.analysis.host.root, file).replaceAll(\"\\\\\", \"/\"),\n filter.pattern!,\n {\n dot: true,\n },\n ),\n )),\n )\n .sort();\n }\n\n /**\n * Answers a question about the design system of each project.\n *\n * @param request - Theme, utility, or variant request.\n * @returns Answers in configuration order.\n * @throws If CSS loading or a plugin fails in any project.\n */\n async designSystem(request: DesignSystemRequest): Promise<\n {\n /** Zero-based index into the configured projects. */\n project: number;\n /** Answer from that project's design system. */\n result: DesignSystemResult;\n }[]\n > {\n const answers = await Promise.all(\n this.projects.map((project) => project.analysis.designSystem(request)),\n );\n return answers.flatMap((result, project) => (result ? [{ project, result }] : []));\n }\n\n /**\n * Keeps editor answers separate when several projects include the same target.\n *\n * @param file - Absolute target path used for independent scope checks.\n * @param request - Operation in the original document's UTF-16 coordinates.\n * @param signal - Optional cancellation forwarded to each project's queued query.\n * @returns Available answers in configuration order, including overlapping project memberships.\n * CSS membership checks allow recovered definitions when the original graph cannot load.\n * Plugin path completion and links also accept CSS files inside a project's root.\n * @throws If a project's editor query fails.\n */\n async query(\n file: string,\n request: EditorRequest,\n signal?: AbortSignal,\n ): Promise<\n {\n /** Zero-based index into the configured projects. */\n project: number;\n /** Absolute configuration path that owns this project. */\n config: string;\n /** Answer tied to the captured original source and design system. */\n result: EditorResult;\n }[]\n > {\n const results: {\n /** Zero-based index into the configured projects. */\n project: number;\n /** Absolute configuration path that owns this project. */\n config: string;\n /** Answer tied to the captured original source and design system. */\n result: EditorResult;\n }[] = [];\n for (const [index, project] of this.projects.entries()) {\n const relative = path.relative(project.analysis.host.root, file);\n const navigation =\n isStylesheet(file) &&\n [\"completion\", \"resolve\", \"links\"].includes(request.kind) &&\n relative !== \"..\" &&\n !relative.startsWith(`..${path.sep}`) &&\n !path.isAbsolute(relative);\n if (\n !this.includes(project, file) &&\n !navigation &&\n !(await this.lintsStylesheet(project, file, true))\n ) {\n continue;\n }\n const result = await project.analysis.query(file, request, signal);\n if (result) {\n results.push({\n project: index,\n config: project.configFile,\n result,\n });\n }\n }\n return results;\n }\n\n /**\n * Updates all hosts because an open file can be a dependency outside their target scope.\n *\n * @param file - File path resolved by each project from the process working directory if relative.\n * @param source - Complete unsaved document text.\n * @param version - Increasing safe integer for the open buffer. Identical repeated updates have no effect.\n * @throws If a project rejects the version. Updates already applied to earlier projects are retained.\n */\n update(file: string, source: string, version: number): void {\n for (const project of this.projects) {\n project.analysis.update(file, source, version);\n }\n this.#openDocuments.add(path.resolve(file));\n }\n\n /**\n * Removes a buffer from every project so later reads use its source provider.\n *\n * @param file - File path resolved in the same way as update. Unknown buffers have no effect.\n */\n closeDocument(file: string): void {\n this.#openDocuments.delete(path.resolve(file));\n for (const project of this.projects) {\n project.analysis.closeDocument(file);\n }\n }\n\n /**\n * Checks whether a change to a file requires a new workspace.\n *\n * @param file - Changed file path.\n * @param reads - Result of `AnalysisProject.reads` for each project, in project order.\n * @returns True for a configuration dependency, and for a tsconfig or package.json that a project\n * read or that lies directly in a project root. Module resolution can read these files without\n * recording them, so the project root is checked as well.\n */\n #reopens(file: string, reads: readonly ReadonlySet<string>[]): boolean {\n if (this.#configurationDependencies.some((dependency) => sameFile(dependency, file))) {\n return true;\n }\n return (\n /(?:^|[/\\\\])(?:tsconfig(?:\\.[^/\\\\]+)?\\.json|package\\.json)$/.test(file) &&\n this.projects.some(\n (project, index) =>\n reads[index].has(sourceKey(file)) ||\n sameFile(path.dirname(path.resolve(file)), project.analysis.host.root),\n )\n );\n }\n\n /**\n * Checks whether the disk content of a file can change a project's analysis.\n *\n * @param index - Project index.\n * @param file - Changed file path.\n * @param reads - Result of `AnalysisProject.reads` for each project, in project order.\n * @returns True when the file has no open buffer and the project read it or its target scope\n * contains it. Scope membership covers a new file that no analysis has read.\n */\n #stale(index: number, file: string, reads: readonly ReadonlySet<string>[]): boolean {\n return (\n ![...this.#openDocuments].some((open) => sameFile(open, file)) &&\n (reads[index].has(sourceKey(file)) || this.includes(this.projects[index], path.resolve(file)))\n );\n }\n\n /**\n * Checks whether file changes can change this workspace's results, without changing any state.\n * Analysis cannot depend on a file that it never read and that lies outside every target scope.\n *\n * @param files - File paths reported by a watch notification. Relative paths use the working\n * directory.\n * @returns Whether `refresh` would request reopening or invalidate a project for these files.\n */\n affects(files: readonly string[]): boolean {\n const reads = this.projects.map((project) => project.analysis.reads());\n return files.some(\n (file) =>\n this.#reopens(file, reads) || this.projects.some((_, i) => this.#stale(i, file, reads)),\n );\n }\n\n /**\n * Checks whether save or watch notifications need a new workspace, and invalidates each project\n * that a change to a closed file can affect.\n *\n * @param files - File paths reported by the notification. Relative paths use the working directory.\n * @returns False when the workspace must reopen, which leaves projects unchanged. Otherwise\n * returns true. This method does not read disk or reopen projects.\n */\n refresh(files: readonly string[]): boolean {\n const reads = this.projects.map((project) => project.analysis.reads());\n if (files.some((file) => this.#reopens(file, reads))) {\n return false;\n }\n for (const [index, project] of this.projects.entries()) {\n if (files.some((file) => this.#stale(index, file, reads))) {\n project.analysis.invalidate();\n }\n }\n return true;\n }\n\n /**\n * Advances every project revision and requests CSS and resolver cache refresh before its next analysis.\n */\n invalidate(): void {\n for (const project of this.projects) {\n project.analysis.invalidate();\n }\n }\n\n /**\n * Analyzes a target separately in every matching project and filters reports to each scope.\n * A project matches a script target in its configured scope and a stylesheet that it lints.\n *\n * @param file - Absolute target path. The file need not exist on disk when an open buffer supplies it.\n * @param signal - Optional cancellation checked by each project's queued analysis.\n * @returns Results in project order, or an empty list when no project includes the target.\n * Dependency information remains available even when its reports lie outside the target scope.\n */\n async analyze(file: string, signal?: AbortSignal): Promise<WorkspaceResult[]> {\n const results: WorkspaceResult[] = [];\n for (const [index, project] of this.projects.entries()) {\n if (this.includes(project, file) || (await this.lintsStylesheet(project, file))) {\n results.push({\n project: index,\n config: project.configFile,\n result: this.scopedResult(project, await project.analysis.analyze(file, signal)),\n });\n }\n }\n return results;\n }\n\n /**\n * Analyzes every selected target, including files unreachable from an application entry, and\n * every stylesheet that a project lints.\n *\n * @param patterns - Optional additional globs relative to each project's root. Empty or omitted\n * filters check every configured target.\n * @returns Scoped results in project order, then sorted target order. Overlapping memberships remain separate.\n * @throws If target enumeration fails. Analysis failures are represented in individual results.\n */\n async lint(patterns?: string[]): Promise<WorkspaceResult[]> {\n const results: WorkspaceResult[] = [];\n for (const [index, project] of this.projects.entries()) {\n const files = await this.targets(project, patterns, { stylesheets: true });\n await project.analysis.prepare(files);\n for (const file of files) {\n results.push({\n project: index,\n config: project.configFile,\n result: this.scopedResult(project, await project.analysis.analyze(file)),\n });\n }\n }\n return results;\n }\n\n /**\n * Prepares targets together in each project that includes them.\n *\n * @param files - Absolute target paths. Files outside a project's target globs are skipped.\n * @returns Completion of preparation. Each target's analysis reports its own source failures.\n */\n async prepare(files: readonly string[]): Promise<void> {\n for (const project of this.projects) {\n await project.analysis.prepare(files.filter((file) => this.includes(project, file)));\n }\n }\n\n /**\n * Keeps dependency context while filtering findings from known sources to the project's target scope.\n *\n * @param project - Project whose host and globs identify owned source documents.\n * @param result - Captured analysis with original document URIs.\n * @returns A copy with filtered reports. Reports for unknown source documents remain available.\n * @throws If a file URI in a report cannot be converted to a path.\n */\n private scopedResult(project: WorkspaceProject, result: AnalysisResult): AnalysisResult {\n return {\n ...result,\n reports: result.reports.filter((report) => {\n const uri = report.primary.location.uri;\n if (uri.startsWith(\"file:\")) {\n const file = fileURLToPath(uri);\n if (project.analysis.host.supports(file)) {\n return this.includes(project, file);\n }\n }\n const source = result.graph?.sources.find((source) => source.document.uri === uri);\n if (!source) {\n return true;\n }\n const file = uri.startsWith(\"file:\") ? fileURLToPath(uri) : source.resolverId;\n return this.includes(project, file);\n }),\n };\n }\n\n /**\n * Closes every project and waits for all cleanup attempts before reporting failures.\n *\n * @returns A promise that resolves after project cleanup.\n * @throws An AggregateError containing all project cleanup failures.\n */\n async close(): Promise<void> {\n const results = await Promise.allSettled(\n this.projects.map((project) => project.analysis.close()),\n );\n const errors = results.flatMap((result) =>\n result.status === \"rejected\" ? [result.reason] : [],\n );\n if (errors.length) {\n throw new AggregateError(errors, \"Failed to close Stillwind analysis hosts\");\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAcA,SAAgB,iBAAiB,MAAc,IAAoB;CACjE,OAAO,SAAS,MAAM,EAAE,CAAC,CAAC,WAAW,MAAM,GAAG;AAChD;;;;;;;;AASA,SAAgB,qBAAqB,MAAc,IAA8B;CAC/E,MAAM,OAAO,cAAc,EAAE;CAC7B,MAAM,EAAE,QAAQ,WAAW,eAAe,IAAI;CAC9C,OAAO;EACL,UAAU,iBAAiB,MAAM,IAAI;EACrC,UAAU;GACR,KAAK,cAAc,IAAI,CAAC,CAAC;GACzB;EACF;EACA,iBAA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;EACH;CACF;;;;;;;CAQA,MAAM,QAAuB;EAI3B,MAAM,UAAS,MAHO,QAAQ,WAC5B,KAAK,SAAS,KAAK,YAAY,QAAQ,SAAS,MAAM,CAAC,CACzD,EAAA,CACuB,SAAS,WAC9B,OAAO,WAAW,aAAa,CAAC,OAAO,MAAM,IAAI,CAAC,CACpD;EACA,IAAI,OAAO,QACT,MAAM,IAAI,eAAe,QAAQ,0CAA0C;CAE/E;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/compilation/filesystem.ts","../src/compilation/finalize.ts","../src/compilation/source-map.ts","../src/css/css-source-map.ts","../src/semantics/node/project.ts","../src/semantics/node/facts.ts","../src/semantics/node/hidden-spawn.ts","../src/semantics/node/checker.ts","../src/semantics/node/decoder.ts","../src/semantics/node/service.ts","../src/project/diagnostic-map.ts","../src/project/analysis/host.ts","../src/project/analysis/project.ts","../src/project/editor.ts","../src/project/plugins.ts","../src/project/stylesheets.ts","../src/project/filesystem.ts","../src/project/workspace.ts"],"sourcesContent":["import { relative } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\n\nimport { cleanModuleId, fileSourceKind, type ModuleDescriptor } from \"./module-source.ts\";\n\n/**\n * Derives a compiler module identity relative to a filesystem root.\n *\n * @param root - Filesystem directory from which the identity is made relative.\n * @param id - Filesystem path to identify. Callers remove resolver queries before using this\n * helper.\n * @returns A relative path with forward slashes. Paths outside the root retain `..` segments. This\n * function does not enforce containment.\n */\nexport function compilerModuleId(root: string, id: string): string {\n return relative(root, id).replaceAll(\"\\\\\", \"/\");\n}\n\n/**\n * Infers parser metadata from a filesystem path and assigns compiler and checker identities.\n *\n * @param root - Project directory used for relative compiler identities.\n * @param id - Absolute source path, optionally followed by a query or fragment suffix.\n * @returns Metadata for the file after removing its query or fragment suffix.\n */\nexport function fileModuleDescriptor(root: string, id: string): ModuleDescriptor {\n const file = cleanModuleId(id);\n const { syntax, format } = fileSourceKind(file);\n return {\n moduleId: compilerModuleId(root, file),\n document: {\n uri: pathToFileURL(file).href,\n format,\n },\n checkerFileName: file,\n projectionFileName: file.replaceAll(\"\\\\\", \"/\"),\n syntax,\n };\n}\n","/**\n * Prepends an optional side-effect stylesheet import to compiled JavaScript.\n *\n * @param code - Compiled JavaScript text. The import is inserted before all existing text.\n * @param stylesheetSpecifier - Module specifier to import. Omission or an empty string leaves the\n * code unchanged.\n * @returns Final JavaScript text with the optional import and its following newline.\n */\nexport function finalizeModule(code: string, stylesheetSpecifier?: string): string {\n return finalizeModuleWithMap(code, stylesheetSpecifier).code;\n}\n\n/**\n * Half-open UTF-16 range removed from the compiled buffer during host finalization. The current\n * finalizer returns no removed ranges.\n */\nexport type FinalizedModuleEdit = {\n /** Inclusive UTF-16 offset in the compiled buffer before finalization. */\n from: number;\n /** Exclusive UTF-16 offset in that same buffer. */\n to: number;\n};\n\n/**\n * Finalizes compiled JavaScript and describes the inserted prefix for source-map generation.\n *\n * @param code - Compiled JavaScript before host finalization.\n * @param stylesheetSpecifier - Optional side-effect import specifier. A falsy value inserts no\n * import.\n * @returns Final code, the exact prefix inserted before it, and an empty list of removed ranges.\n */\nexport function finalizeModuleWithMap(code: string, stylesheetSpecifier?: string) {\n const stylesheetImport = stylesheetSpecifier\n ? `import ${JSON.stringify(stylesheetSpecifier)};\\n`\n : \"\";\n return {\n code: stylesheetImport + code,\n prefix: stylesheetImport,\n removed: [] as FinalizedModuleEdit[],\n };\n}\n","import { resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nimport {\n GenMapping,\n addSegment,\n setSourceContent,\n toEncodedMap,\n type EncodedSourceMap,\n} from \"@jridgewell/gen-mapping\";\nimport remapping, { type SourceMap } from \"@jridgewell/remapping\";\nimport { TraceMap, type SourceMapInput } from \"@jridgewell/trace-mapping\";\n\n/**\n * Traces framework output through a Stillwind transform when embedded source text identifies the\n * transformed input.\n *\n * @param generated - Framework output map.\n * @param original - Map or map chain from the Stillwind-transformed input back to original sources.\n * @param transformedSource - Exact text to match against the generated map's `sourcesContent`.\n * @returns A composed map. Only matching immediate sources are replaced. Other sources retain their\n * mappings.\n * @throws If a supplied source map cannot be decoded or composed.\n */\nexport function composeFrameworkSourceMap(\n generated: SourceMapInput,\n original: SourceMapInput | readonly SourceMapInput[],\n transformedSource: string,\n): SourceMap {\n const traced = new TraceMap(generated);\n const matches = new Set(\n traced.resolvedSources.filter(\n (_source, index) => traced.sourcesContent?.[index] === transformedSource,\n ),\n );\n return remapping(generated, (source, context) =>\n context.depth === 1 && matches.has(source) ? (original as SourceMapInput) : null,\n );\n}\n\n/**\n * Traces a CSS pipeline map through the original map of its carrier resource.\n *\n * @param generated - Pipeline output map, or a map chain accepted by the composition library.\n * @param original - Map or chain from the CSS carrier back to authored sources.\n * @param resource - Absolute carrier path with forward slashes. File URLs are decoded, and relative\n * source paths are resolved against the process working directory before comparison.\n * @returns A composed map that replaces only immediate sources resolving to the carrier path.\n * @throws If a supplied source map cannot be decoded or composed.\n */\nexport function composeCarrierSourceMap(\n generated: SourceMapInput | SourceMapInput[],\n original: SourceMapInput | readonly SourceMapInput[],\n resource: string,\n): SourceMap {\n return remapping(generated, (source, context) =>\n context.depth === 1 &&\n resolve(source.startsWith(\"file:\") ? fileURLToPath(source) : source).replaceAll(\"\\\\\", \"/\") ===\n resource\n ? (original as SourceMapInput)\n : null,\n );\n}\n\n/**\n * Map or ordered map chain from a module's input back to its original sources. Null and undefined\n * mean that no upstream map is available. Each map may be serialized or supplied as an object.\n */\nexport type UpstreamSourceMap = SourceMapInput | readonly SourceMapInput[] | undefined | null;\n\n/**\n * Composes the native output map with the upstream loader map or ordered map chain\n * describing its input. Without upstream, returns the generated object unchanged.\n * Invalid maps or incompatible chains may throw from the mapping library.\n *\n * @param generated - Map from compiled JavaScript back to the input received by Stillwind.\n * @param upstream - Optional map or ordered map chain from that input back to original sources.\n * @returns The generated map unchanged when no upstream map is supplied, otherwise a composed map.\n * @throws If map decoding fails or a supplied map chain is incompatible.\n */\nexport function composeModuleSourceMap(\n generated: EncodedSourceMap,\n upstream: UpstreamSourceMap,\n): EncodedSourceMap | SourceMap {\n return upstream\n ? remapping(\n [JSON.stringify(generated), ...(Array.isArray(upstream) ? upstream : [upstream])],\n () => null,\n )\n : generated;\n}\n\n/**\n * One compiler replacement before host finalization inserts a prefix or removes text.\n * All offsets are absolute UTF-16 code units in the original and compiled buffers.\n * Replacement gaps without expression intervals map to `originalStart`.\n */\nexport interface CompilerMapping {\n /** Inclusive original offset. Equals end for insertion. */\n originalStart: number;\n /** Exclusive original offset, at or after start. */\n originalEnd: number;\n /** Inclusive offset in the complete compiled buffer. */\n generatedStart: number;\n /** Exclusive compiled offset. Equals start for deletion. */\n generatedEnd: number;\n /**\n * Nonempty, nonoverlapping intervals contained in this replacement, sorted by\n * generated start. Source order may differ. Missing/empty means anchor-only mapping.\n */\n expressions?: {\n /** Inclusive original offset. The anchor for a nonexact interval. */\n originalStart: number;\n /** Exclusive original offset of the expression or encoded character. */\n originalEnd: number;\n /** Inclusive compiled offset, before host edits. */\n generatedStart: number;\n /** Exclusive compiled offset, strictly greater than start. */\n generatedEnd: number;\n /** True requires identical text/equal lengths. False anchors all units at original start. */\n exact: boolean;\n }[];\n}\n\n/**\n * Builds a JavaScript source map from compiler replacements and host finalization edits.\n *\n * Unchanged text maps character by character. Replacement text maps to its original start unless an\n * expression interval provides a more precise correspondence. All offsets use UTF-16 code units.\n *\n * @param source - Original source whose text is embedded in the map.\n * @param compiled - Compiler output before the host inserts a prefix or removes intervals.\n * @param id - Source identity used as the map's file and sole source name.\n * @param mappings - Nonoverlapping compiler replacements in generated-start order, with valid\n * original and generated ranges.\n * @param removed - Nonoverlapping ranges removed from `compiled`, in ascending order.\n * @param prefix - Exact text inserted before the retained compiler output. It advances generated\n * positions without receiving original mappings.\n * @returns An encoded version 3 map for the finalized output with original source content.\n */\nexport function moduleSourceMap(\n source: string,\n compiled: string,\n id: string,\n mappings: readonly CompilerMapping[],\n removed: readonly {\n /** Inclusive UTF-16 offset removed from compiled. */\n from: number;\n /** Exclusive UTF-16 offset in the same compiled buffer. */\n to: number;\n }[],\n prefix: string,\n): EncodedSourceMap {\n const map = new GenMapping({ file: id });\n setSourceContent(map, id, source);\n const lines = [0];\n for (let index = 0; index < source.length; index++) {\n if (source[index] === \"\\n\") {\n lines.push(index + 1);\n }\n }\n let line = prefix.split(\"\\n\").length - 1;\n let column = prefix.length - prefix.lastIndexOf(\"\\n\") - 1;\n let editIndex = 0;\n let removedIndex = 0;\n let expressionIndex = 0;\n let delta = 0;\n let originalLine = 0;\n for (let index = 0; index < compiled.length; index++) {\n while (removedIndex < removed.length && removed[removedIndex].to <= index) {\n removedIndex++;\n }\n if (removedIndex < removed.length && removed[removedIndex].from <= index) {\n continue;\n }\n while (editIndex < mappings.length && mappings[editIndex].generatedEnd <= index) {\n const edit = mappings[editIndex++];\n delta = edit.originalEnd - edit.generatedEnd;\n expressionIndex = 0;\n }\n const edit = mappings[editIndex];\n const expressions = edit?.expressions ?? [];\n while (\n expressionIndex < expressions.length &&\n expressions[expressionIndex].generatedEnd <= index\n ) {\n expressionIndex++;\n }\n const expression = expressions[expressionIndex];\n const original =\n expression && expression.generatedStart <= index\n ? expression.originalStart + (expression.exact ? index - expression.generatedStart : 0)\n : edit && edit.generatedStart <= index\n ? edit.originalStart\n : index + delta;\n // A folded record can jump backwards between distant source lines.\n if (\n original < lines[originalLine] ||\n (originalLine + 1 < lines.length && lines[originalLine + 1] <= original)\n ) {\n let low = 0;\n let high = lines.length;\n while (low < high) {\n const middle = (low + high) >>> 1;\n if (lines[middle] <= original) {\n low = middle + 1;\n } else {\n high = middle;\n }\n }\n originalLine = low - 1;\n }\n addSegment(map, line, column, id, originalLine, original - lines[originalLine]);\n if (compiled[index] === \"\\n\") {\n line++;\n column = 0;\n } else {\n column++;\n }\n }\n return toEncodedMap(map);\n}\n","import { isAbsolute, resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\n\nimport {\n GenMapping,\n addSegment,\n setSourceContent,\n toEncodedMap,\n type EncodedSourceMap,\n} from \"@jridgewell/gen-mapping\";\nimport remapping, { type SourceMap } from \"@jridgewell/remapping\";\nimport type { EncodedSourceMap as MutableEncodedSourceMap } from \"@jridgewell/trace-mapping\";\n\nimport { cssBannerPrefix } from \"./banners.ts\";\n\n/**\n * Producer map used to trace native CSS locations from a transformed script or component back to\n * its authored source.\n */\nexport interface CssUpstreamMap {\n /**\n * Producer filesystem identity used as the base for relative map sources. Ordinary query and\n * fragment suffixes may follow its path.\n */\n id: string;\n /** Exact source name in the native CSS map to which this producer map applies. */\n sourceMapSource: string;\n /** JSON text for an encoded version 3 map from producer input to authored sources. */\n map: string;\n}\n\n/**\n * Composes one producer map into the matching immediate source of a CSS map.\n *\n * Relative producer sources are resolved against its resource path and optional source root. Other\n * CSS sources keep their existing mappings.\n *\n * @param map - Encoded CSS map whose source names identify original producer inputs.\n * @param upstream - Optional producer map and the exact CSS source name to replace.\n * @returns The composed map, or the input map unchanged when upstream is absent or lacks a sources\n * array or nonempty mappings.\n * @throws If producer JSON, source URLs, or source-map composition are invalid.\n */\nfunction composeUpstream(\n map: EncodedSourceMap,\n upstream?: CssUpstreamMap,\n): EncodedSourceMap | SourceMap {\n if (!upstream) {\n return map;\n }\n const resource = pathToFileURL(resolve(upstream.id.split(/[?#]/, 1)[0])).href;\n const original = JSON.parse(upstream.map);\n if (!Array.isArray(original.sources) || !original.mappings) {\n return map;\n }\n /**\n * Resolves a map source while retaining its query and fragment.\n * @param source - Absolute path or URL reference. Backslashes are normalized to slashes.\n * @param base - Absolute URL used to resolve relative references.\n * @returns A file URL for an absolute path, or the resolved URL for another reference.\n * @throws If the reference or base cannot form a valid URL.\n */\n const sourceUrl = (source: string, base: string) => {\n const normalized = source.replaceAll(\"\\\\\", \"/\");\n const clean = normalized.split(/[?#]/, 1)[0];\n return isAbsolute(clean)\n ? pathToFileURL(clean).href + normalized.slice(clean.length)\n : new URL(normalized, base).href;\n };\n const base = original.sourceRoot\n ? sourceUrl(original.sourceRoot.replace(/\\/?$/, \"/\"), resource)\n : resource;\n original.sources = original.sources.map((source: string) => sourceUrl(source, base));\n delete original.sourceRoot;\n return remapping(JSON.stringify(map), (source, context) =>\n context.depth === 1 && source === upstream.sourceMapSource ? original : null,\n );\n}\n\n/**\n * Native locations linking generated CSS intervals to authored text. All interval offsets count\n * UTF-8 bytes before resource placeholders are replaced.\n */\nexport interface CssLocations {\n /** Source table indexed by each entry's `source` field. */\n sources: {\n /** Source identity recorded in the emitted version 3 map. */\n sourceMapSource: string;\n /**\n * Authored source text used to derive original lines, UTF-16 columns, and optional\n * `sourcesContent`.\n */\n content: string;\n }[];\n /**\n * Nonoverlapping generated CSS intervals. Rendering sorts them by generated start. Callers must\n * supply valid source indexes and byte boundaries.\n */\n entries: {\n /** Zero-based index into `sources` for the authored interval. */\n source: number;\n /** Inclusive UTF-8 byte offset in generated CSS before resource replacement. */\n generatedStart: number;\n /** Exclusive UTF-8 byte offset in that CSS, at or after `generatedStart`. */\n generatedEnd: number;\n /** Inclusive UTF-8 byte offset in the selected source's content. */\n originalStart: number;\n /** Exclusive UTF-8 byte offset in that content, at or after `originalStart`. */\n originalEnd: number;\n /**\n * True maps matching text byte for byte from `originalStart`. False maps the generated interval\n * to its original start.\n */\n exact: boolean;\n }[];\n}\n\n/** CSS and native source locations before resource URLs and upstream maps are composed. */\nexport interface CssSourceMapInput {\n /** Preserved notices selected for this CSS body. */\n banners?: readonly string[];\n /** Stylesheet text containing any unresolved resource placeholder tokens. */\n css: string;\n /** Native source locations whose generated offsets count UTF-8 bytes in `css`. */\n sourceMap: CssLocations;\n}\n\n/**\n * Rewrites resource placeholders while retaining native UTF-8 source locations.\n *\n * @param output - CSS and native source locations before resource replacement. Source indexes and\n * byte boundaries must be valid for the supplied CSS and authored text.\n * @param replacements - Resource placeholders mapped to escaped URL text.\n * @param upstream - Optional maps from producer input back to its original source, in composition order.\n * @param includeSourcesContent - Whether the inline map retains source text. Defaults to true.\n * @returns Resolved CSS with an inline version 3 map, or an empty string when the input CSS is empty.\n * @throws If an upstream map cannot be decoded, its source URLs are invalid, or composition fails.\n */\nexport function cssWithSourceMap(\n output: CssSourceMapInput,\n replacements: ReadonlyMap<string, string>,\n upstream?: CssUpstreamMap | readonly CssUpstreamMap[],\n includeSourcesContent = true,\n) {\n if (!output.css) {\n return \"\";\n }\n const { css, sourceMap } = output;\n const positions = sourceMap.sources.map(({ content }) => {\n const result = new Map<number, [number, number]>();\n let byte = 0;\n let line = 0;\n let column = 0;\n for (const char of content) {\n result.set(byte, [line, column]);\n byte += Buffer.byteLength(char);\n if (char === \"\\n\") {\n line++;\n column = 0;\n } else {\n column += char.length;\n }\n }\n result.set(byte, [line, column]);\n return result;\n });\n const names = sourceMap.sources.map(({ sourceMapSource }) => sourceMapSource);\n const map = new GenMapping();\n names.forEach((name, index) => setSourceContent(map, name, sourceMap.sources[index].content));\n let result = cssBannerPrefix(output.banners ?? []);\n let byte = 0;\n let line = result.match(/\\r\\n|\\r|\\n/g)?.length ?? 0;\n let column = result.split(\"\\n\").at(-1)!.length;\n let entryIndex = 0;\n const entries = [...sourceMap.entries].sort((a, b) => a.generatedStart - b.generatedStart);\n const edits = [...replacements];\n for (let offset = 0; offset < css.length;) {\n while (entryIndex < entries.length && entries[entryIndex].generatedEnd <= byte) {\n entryIndex++;\n }\n const entry = entries[entryIndex];\n const active = entry && entry.generatedStart <= byte ? entry : undefined;\n const replacement = edits.find(([placeholder]) => css.startsWith(placeholder, offset));\n const originalText = replacement?.[0] ?? String.fromCodePoint(css.codePointAt(offset)!);\n const emitted = replacement?.[1] ?? originalText;\n const position =\n active &&\n positions[active.source].get(\n active.originalStart + (active.exact ? byte - active.generatedStart : 0),\n );\n for (const char of emitted) {\n if (active && position) {\n addSegment(map, line, column, names[active.source], ...position);\n } else {\n addSegment(map, line, column);\n }\n if (char === \"\\n\") {\n line++;\n column = 0;\n } else {\n column += char.length;\n }\n }\n result += emitted;\n byte += Buffer.byteLength(originalText);\n offset += originalText.length;\n }\n return (\n result +\n \"\\n/*# sourceMappingURL=data:application/json;base64,\" +\n Buffer.from(\n JSON.stringify(\n (Array.isArray(upstream) ? upstream : [upstream]).reduce(\n (map, source) => composeUpstream(map, source),\n toEncodedMap(map),\n ),\n (key, value) => (key === \"sourcesContent\" && !includeSourcesContent ? undefined : value),\n ),\n ).toString(\"base64\") +\n \" */\"\n );\n}\n\n/** Stylesheet text and its decoded inline source map, ready for a bundler's CSS pipeline. */\nexport interface DecodedCssSourceMap {\n /** CSS with the recognized trailing inline source-map comment removed. */\n code: string;\n /**\n * Decoded version 3 map with mutable arrays and string source identities, or null when the CSS\n * has no recognized trailing map.\n */\n map:\n | (MutableEncodedSourceMap & {\n /** Source identities indexed by the decoded map's segments. */\n sources: string[];\n })\n | null;\n}\n\n/**\n * Decodes the trailing inline map emitted by `cssWithSourceMap` or a compatible CSS carrier.\n *\n * @param css - Stylesheet text. A recognized map must contain a base64-encoded version 3 JSON map\n * in the trailing comment format emitted by `cssWithSourceMap`.\n * @returns CSS and its decoded map. Without a recognized trailing map, the CSS is unchanged and\n * the map is null. JSON is decoded without validating its source-map fields.\n * @throws If a recognized inline map contains invalid JSON.\n */\nexport function decodeCssSourceMap(css: string): DecodedCssSourceMap {\n const match =\n /\\n\\/\\*# sourceMappingURL=data:application\\/json;base64,([A-Za-z0-9+/=]+) \\*\\/$/.exec(css);\n if (!match) {\n return {\n code: css,\n map: null,\n };\n }\n return {\n code: css.slice(0, match.index),\n map: JSON.parse(Buffer.from(match[1], \"base64\").toString(\"utf8\")) as NonNullable<\n DecodedCssSourceMap[\"map\"]\n >,\n };\n}\n","import { createHash } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport process from \"node:process\";\n\nimport type {\n NativeAssetRecord as AssetRecord,\n NativeIdentity as IdentityId,\n} from \"@stillwind/native\";\n\nimport { TypeFactsError, type TypeFactSource } from \"../backend.ts\";\nimport { CheckerSource, checkerId } from \"../checker-source.ts\";\n\n/**\n * Normalizes filesystem names used as keys in the virtual checker overlay.\n *\n * @param fileName - Absolute or relative filesystem path.\n * @returns An absolute path with forward slashes, lowercased on Windows to match case-insensitive\n * filesystem lookups.\n */\nexport const normalize = (fileName: string) => {\n const name = path.resolve(fileName).replaceAll(\"\\\\\", \"/\");\n return process.platform === \"win32\" ? name.toLowerCase() : name;\n};\n\n/**\n * Virtual project files, checker range mappings, and declaration identities prepared for one\n * collection request.\n */\nexport interface PreparedProject {\n /**\n * Normalized absolute filenames mapped to virtual text, including checker sources, helpers,\n * globals, and project configuration.\n */\n virtualFiles: Map<string, string>;\n /**\n * Checker buffers in source and buffer order, retaining the correspondence to original probes.\n */\n mappings: CheckerSource[];\n /**\n * Serialized identity keys collected from all checker buffers, mapped to their native\n * declarations.\n */\n identities: Map<string, IdentityId>;\n}\n\n/**\n * TypeScript settings inherited by the generated project used for semantic queries.\n */\nexport type TypeScriptProject =\n | {\n /** Selects settings inherited from a consumer tsconfig. */\n readonly kind: \"configured\";\n /** Absolute path to the consumer's tsconfig. */\n readonly configPath: string;\n }\n | {\n /** Selects Stillwind's defaults without a consumer tsconfig. */\n readonly kind: \"isolated\";\n };\n\n/**\n * Fixed filesystem and TypeScript settings shared by collections in one checker service.\n */\nexport interface TypeFactsEnvironment {\n /** Absolute directory used for checker resolution and generated configuration paths. */\n readonly root: string;\n /** Settings inherited by the checker. Isolated projects use Stillwind's compiler defaults. */\n readonly project: TypeScriptProject;\n}\n\n/**\n * Selects the TypeScript environment before starting a checker.\n *\n * @param root - Filesystem project directory, resolved to an absolute path.\n * @param tsconfig - Absolute or root-relative config path. Omission selects an existing root\n * `tsconfig.json`. False selects isolated defaults even when that file exists.\n * @returns Fixed settings without evaluating configuration or starting the checker.\n * @throws If an explicitly selected path is empty or its configuration file does not exist.\n */\nexport function resolveTypeFactsEnvironment(\n root: string,\n tsconfig?: string | false,\n): TypeFactsEnvironment {\n root = path.resolve(root);\n if (typeof tsconfig === \"string\" && !tsconfig.trim()) {\n throw new Error(\"TypeScript configuration path must not be empty\");\n }\n const configPath = path.resolve(root, typeof tsconfig === \"string\" ? tsconfig : \"tsconfig.json\");\n if (typeof tsconfig === \"string\" && !existsSync(configPath)) {\n throw new Error(`TypeScript configuration does not exist: ${configPath}`);\n }\n return {\n root,\n project:\n tsconfig !== false && existsSync(configPath)\n ? {\n kind: \"configured\",\n configPath,\n }\n : {\n kind: \"isolated\",\n },\n };\n}\n\n/**\n * File contents captured for one collection. Ambient declarations override overlays at matching\n * paths. Prepared checker sources and the generated configuration override both maps.\n */\nexport interface TypeFactsInputs {\n /** Absolute paths to replacement text. Files participate only when the checker references them. */\n overlayFiles?: ReadonlyMap<string, string>;\n /** Absolute declaration paths to text. Every supplied declaration becomes a project root file. */\n ambientDeclarations?: ReadonlyMap<string, string>;\n}\n\n/**\n * Builds checker sources and an in-memory project configuration for semantic queries.\n *\n * @param sources - Prepared sources with validated mappings, original probes, and dependency\n * resolutions.\n * @param assetsByModuleId - Native declaration records keyed by compiler module identity.\n * @param shadowTsconfigPath - Absolute filename of the generated in-memory TypeScript project.\n * @param project - Consumer configuration to inherit, or isolated compiler defaults.\n * @param inputs - Captured file replacements and declarations required by this collection.\n * @param configuredDeclarations - Declaration files selected by the consumer's tsconfig.\n * @returns Virtual text and range mappings without writing any files to disk.\n * @throws If checker edits or projection maps are invalid, or an original probe has no\n * checker-buffer correspondence.\n */\nexport function prepareProject(\n sources: readonly TypeFactSource[],\n assetsByModuleId: ReadonlyMap<string, readonly AssetRecord[]>,\n shadowTsconfigPath: string,\n project: TypeScriptProject,\n inputs: TypeFactsInputs,\n configuredDeclarations: readonly string[],\n): PreparedProject {\n const virtualFiles = new Map(\n [...(inputs.overlayFiles ?? []), ...(inputs.ambientDeclarations ?? [])].map(([name, text]) => [\n normalize(name),\n text,\n ]),\n );\n const mappings: CheckerSource[] = [];\n const allIdentities = new Map<string, IdentityId>();\n const globals = new Set<string>();\n const ids = new Map(sources.map((source) => [source.resolverId, checkerId(source)]));\n for (const source of sources) {\n const declarations = source.kind === \"projected\" && source.projection.checkerGlobals;\n if (declarations) {\n const fingerprint = createHash(\"sha256\").update(declarations).digest(\"hex\").slice(0, 16);\n const id = normalize(\n path.join(path.dirname(shadowTsconfigPath), `.stillwind-globals-${fingerprint}.d.ts`),\n );\n virtualFiles.set(id, declarations);\n globals.add(id);\n }\n const syntax = source.kind === \"direct\" ? source.syntax : source.projection.syntax;\n const buffers = source.checkerBuffers ?? [\n {\n source: source.kind === \"direct\" ? source.document.code : source.projection.code,\n language:\n syntax.language === \"tsx\" || syntax.language === \"jsx\"\n ? (\"tsx\" as const)\n : (\"ts\" as const),\n },\n ];\n for (const [index, buffer] of buffers.entries()) {\n const shadow = new CheckerSource(\n source,\n buffer,\n index,\n assetsByModuleId.get(source.moduleId) ?? [],\n ids,\n );\n virtualFiles.set(normalize(shadow.id), shadow.text);\n if (shadow.helperModule) {\n virtualFiles.set(normalize(shadow.helperModule.id), shadow.helperModule.text);\n }\n mappings.push(shadow);\n for (const [key, identity] of shadow.identities) {\n allIdentities.set(key, identity);\n }\n }\n for (const probe of source.probes) {\n if (\n !mappings.some(\n (mapping) =>\n mapping.source === source &&\n [...mapping.probes.values()].some(\n (candidate) => candidate.start === probe.start && candidate.end === probe.end,\n ),\n )\n ) {\n throw new TypeFactsError(\n source.moduleId,\n probe.start,\n probe.end,\n \"checker\",\n \"Cannot map this expression to a checker source\",\n );\n }\n }\n }\n virtualFiles.set(\n normalize(shadowTsconfigPath),\n JSON.stringify({\n ...(project.kind === \"configured\"\n ? {\n extends: project.configPath,\n }\n : {}),\n compilerOptions: {\n allowJs: true,\n checkJs: true,\n ...(project.kind === \"isolated\"\n ? {\n jsx: \"preserve\",\n module: \"esnext\",\n moduleResolution: \"bundler\",\n strict: true,\n target: \"esnext\",\n types: [],\n }\n : {}),\n noEmit: true,\n skipLibCheck: true,\n allowImportingTsExtensions: true,\n },\n files: [\n ...configuredDeclarations,\n ...[...(inputs.ambientDeclarations?.keys() ?? [])].map(normalize),\n ...globals,\n ...mappings.map((mapping) => mapping.id),\n ...new Set(sources.flatMap((source) => source.checkerTypes ?? [])),\n ],\n include: [],\n exclude: [],\n }),\n );\n return {\n virtualFiles,\n mappings,\n identities: allIdentities,\n };\n}\n","import type { NativeTypeFact as TypeFact } from \"@stillwind/native\";\nimport type { Node, SourceFile } from \"typescript-7/unstable/ast\";\nimport { isCallExpression } from \"typescript-7/unstable/ast/is\";\nimport type { Diagnostic, Type } from \"typescript-7/unstable/sync\";\n\nimport { TypeFactsError, type UnverifiedRange } from \"../backend.ts\";\nimport { CheckerSource } from \"../checker-source.ts\";\nimport type { AssetTypeDecoder } from \"./decoder.ts\";\n\n/**\n * Traverses a checker AST in preorder.\n *\n * @param node - Root visited before its descendants.\n * @param callback - Operation called once for the root and each child exposed by `forEachChild`.\n * Thrown errors stop traversal.\n */\nexport function visit(node: Node, callback: (node: Node) => void) {\n callback(node);\n node.forEachChild((child) => visit(child, callback));\n}\n\n/**\n * Flattens a checker diagnostic and its nested message chain for matching and display.\n *\n * @param diagnostic - Checker diagnostic with optional nested messages.\n * @returns Diagnostic text followed recursively by child messages, separated by newlines.\n */\nexport function diagnosticText(diagnostic: Diagnostic): string {\n return [diagnostic.text, ...(diagnostic.messageChain ?? []).map(diagnosticText)].join(\"\\n\");\n}\n\n/**\n * Tests whether a TypeScript argument error belongs to a style producer call.\n * Lowering reports unsupported macro arguments as lints, so these errors do not invalidate the\n * facts of the call. The operands still require valid facts.\n *\n * @param diagnostic - Checker diagnostic for `sourceFile`.\n * @param sourceFile - Checker source file that contains the diagnostic.\n * @param mapping - Producer call ranges of the same source.\n * @returns Whether the diagnostic is an argument error (TS2345 or TS2769) whose innermost\n * enclosing call is a recorded producer call.\n */\nexport function producerArgumentDiagnostic(\n diagnostic: Diagnostic,\n sourceFile: SourceFile,\n mapping: CheckerSource,\n): boolean {\n if (diagnostic.code !== 2345 && diagnostic.code !== 2769) {\n return false;\n }\n let owner: Node | undefined;\n visit(sourceFile, (node) => {\n if (\n isCallExpression(node) &&\n node.getStart(sourceFile) <= diagnostic.pos &&\n node.end >= diagnostic.end &&\n (!owner || node.end - node.getStart(sourceFile) < owner.end - owner.getStart(sourceFile))\n ) {\n owner = node;\n }\n });\n return !!owner && mapping.producers.has(`${owner.getStart(sourceFile)}:${owner.end}`);\n}\n\n/**\n * Decodes the types of checker expressions matched to original semantic probes.\n *\n * @param sourceFile - Final checker AST for the mapped buffer.\n * @param mapping - Original probes indexed by exact checker AST start and end positions.\n * @param decoder - Decoder with asset brands already registered from producer types.\n * @param nodes - Expression nodes from sourceFile, in AST traversal order.\n * @param typesAt - Returns one type per node, in the supplied order. Undefined means no type is available.\n * @param unverified - Optional array to append unavailable original ranges to. Supplying it keeps\n * other facts usable when a probe lacks an expression or a finite declaration type.\n * @returns Facts in AST traversal order with original byte ranges. Known types that do not\n * represent Stillwind assets produce null values. Unresolved recognition-only probes are skipped\n * in both strict and partial queries.\n * @throws If unverified is omitted and a probe has no matching expression or a required type cannot\n * be resolved. Errors from typesAt also propagate.\n */\nexport function factsForSource(\n sourceFile: SourceFile,\n mapping: CheckerSource,\n decoder: AssetTypeDecoder,\n nodes: readonly Node[],\n typesAt: (nodes: readonly Node[]) => readonly (Type | undefined)[],\n unverified?: UnverifiedRange[],\n): TypeFact[] {\n const expressions: Node[] = [];\n const matched = new Set<string>();\n for (const node of nodes) {\n const key = `${node.getStart(sourceFile)}:${node.end}`;\n if (mapping.probes.has(key)) {\n expressions.push(node);\n matched.add(key);\n }\n }\n for (const [key, probe] of mapping.probes) {\n if (!matched.has(key)) {\n const error = new TypeFactsError(\n mapping.source.moduleId,\n probe.start,\n probe.end,\n \"checker\",\n \"Projected expression has no matching checker AST node\",\n );\n if (!unverified) {\n throw error;\n }\n unverified.push({\n moduleId: error.moduleId,\n start: error.start,\n end: error.end,\n reason: error.message,\n });\n }\n }\n\n const types = typesAt(expressions);\n const facts: TypeFact[] = [];\n for (const [index, expression] of expressions.entries()) {\n const probe = mapping.probes.get(`${expression.getStart(sourceFile)}:${expression.end}`)!;\n const type = types[index];\n const decoded = type\n ? decoder.decode(type, probe.recognitionOnly ?? false)\n : { kind: \"unverified\" as const };\n if (decoded.kind !== \"asset\") {\n if (\n decoded.kind === \"unverified\" ||\n (decoded.kind === \"unbranded\" && !probe.recognitionOnly)\n ) {\n if (probe.recognitionOnly) {\n continue;\n }\n const error = new TypeFactsError(\n mapping.source.moduleId,\n probe.start,\n probe.end,\n \"identity\",\n \"Cannot determine a finite set of declaration identities. Preserve the value's inferred type, use an explicit union, or use a generic parameter.\",\n );\n if (!unverified) {\n throw error;\n }\n unverified.push({\n moduleId: error.moduleId,\n start: error.start,\n end: error.end,\n reason: error.message,\n });\n } else {\n facts.push({\n ...probe,\n value: null,\n });\n }\n continue;\n }\n facts.push({\n ...probe,\n value: decoded.value,\n });\n }\n\n return facts;\n}\n","import childProcess from \"node:child_process\";\nimport { syncBuiltinESMExports } from \"node:module\";\n\n/**\n * Runs a function while `child_process.spawn` hides the console windows of new processes.\n *\n * The TypeScript API starts its checker with `spawn` and has no option for `windowsHide`. Under\n * Electron, `Code.exe` is a Windows GUI program that has no console, so Windows opens a visible\n * console for `tsc.exe` unless the spawn call hides it.\n *\n * @param action - Synchronous function that starts processes. Asynchronous work after it returns\n * uses the original `spawn`.\n * @returns The function's return value. `spawn` is restored before the return or the throw.\n * @throws If the function throws.\n */\nexport function withHiddenSpawnWindows<T>(action: () => T): T {\n const { spawn } = childProcess;\n childProcess.spawn = ((command: string, args: readonly string[], options: object) =>\n spawn(command, args, {\n ...options,\n windowsHide: true,\n })) as typeof spawn;\n // ESM imports of `node:child_process` read a copy that only this call updates.\n syncBuiltinESMExports();\n try {\n return action();\n } finally {\n childProcess.spawn = spawn;\n syncBuiltinESMExports();\n }\n}\n","import { existsSync } from \"node:fs\";\nimport path from \"node:path\";\n\nimport type { NativeAssetRecord as AssetRecord } from \"@stillwind/native\";\nimport type { Node, SourceFile } from \"typescript-7/unstable/ast\";\nimport { isExpression } from \"typescript-7/unstable/ast/is\";\nimport {\n API,\n Snapshot,\n type Checker,\n type Diagnostic,\n type Type,\n} from \"typescript-7/unstable/sync\";\n\nimport type { TypeFactSource } from \"../backend.ts\";\nimport type { TypePropertyCache } from \"./decoder.ts\";\nimport { visit } from \"./facts.ts\";\nimport { withHiddenSpawnWindows } from \"./hidden-spawn.ts\";\nimport {\n normalize,\n prepareProject,\n type PreparedProject,\n type TypeFactsEnvironment,\n type TypeFactsInputs,\n type TypeScriptProject,\n} from \"./project.ts\";\n\n/**\n * Cumulative checker lifecycle and filesystem counters for one service. They include recovery\n * attempts and are not reset between collections.\n */\nexport interface TypeScriptFactsStats {\n /** Number of API construction attempts, including starts after invalidation or query failure. */\n starts: number;\n /**\n * Number of snapshot updates that returned a snapshot, including updates followed by a query\n * failure.\n */\n snapshots: number;\n /** Number of snapshot updates made while a previous snapshot was retained. */\n incrementalSnapshots: number;\n /** Number of recovery restarts attempted after a failure other than `TypeFactsError`. */\n restarts: number;\n /** Number of checker read callbacks answered with text from the virtual overlay. */\n overlayReads: number;\n /**\n * Number of checker read callbacks delegated to the filesystem because the overlay had no text. A\n * request does not imply a successful disk read.\n */\n diskReadRequests: number;\n}\n\n/**\n * Owns the Node checker process, snapshots, and answers cached within each snapshot.\n * The analysis service serializes calls and closes the checker after pending work finishes.\n */\nexport class NodeChecker {\n /** Property answers for the current snapshot. Cleared before replacing that snapshot. */\n readonly properties: TypePropertyCache = {\n named: new Map(),\n all: new Map(),\n };\n\n /** Types keyed by filename and AST range within the current snapshot. */\n readonly #queryTypes = new Map<string, Type | undefined>();\n\n /** Expression nodes in AST traversal order, keyed by checker filename. */\n readonly #queryNodes = new Map<string, Node[]>();\n\n /** Syntactic and semantic diagnostics for each checker file in the current snapshot. */\n readonly diagnostics = new Map<string, readonly Diagnostic[]>();\n\n /** Paths observed by disk reads and existence checks, including missing paths and overlay checks. */\n readonly dependencies = new Set<string>();\n\n /**\n * Live cumulative counters updated by this service. Consumers needing a stable report must copy\n * their values.\n */\n readonly stats: TypeScriptFactsStats = {\n starts: 0,\n snapshots: 0,\n incrementalSnapshots: 0,\n restarts: 0,\n overlayReads: 0,\n diskReadRequests: 0,\n };\n\n /** Copy of the selected TypeScript settings, fixed for this service's lifetime. */\n readonly #project: TypeScriptProject;\n\n /** Filesystem root supplied as the checker API working directory. */\n readonly #projectRoot: string;\n\n /**\n * Absolute filename of the in-memory `.stillwind-tsconfig.json`. The service does not write it to\n * disk.\n */\n readonly #shadowTsconfigPath: string;\n\n /** Active checker API instance, replaced after a recoverable collection failure. */\n #api: API;\n\n /**\n * Latest retained checker snapshot, also retained after query failures until the next update,\n * restart, or close.\n */\n #snapshot: Snapshot | undefined;\n\n /**\n * Current normalized filename overlay read dynamically by the checker API filesystem callbacks.\n */\n #virtualFiles = new Map<string, string>();\n\n /**\n * Starts a checker API for a project root without creating its first snapshot.\n *\n * @param environment - Absolute filesystem root and selected TypeScript settings. The checker\n * copies these settings and uses them for its lifetime. Create a new checker to change them.\n * @throws If the checker API cannot start.\n */\n constructor(environment: TypeFactsEnvironment) {\n this.#project = { ...environment.project };\n this.#projectRoot = environment.root;\n this.#shadowTsconfigPath = path.join(environment.root, \".stillwind-tsconfig.json\");\n this.#api = this.#startApi();\n }\n\n /**\n * Builds virtual checker files using the project's TypeScript settings.\n *\n * @param sources - Prepared sources and probes for this request.\n * @param assets - Declarations grouped by compiler module ID.\n * @param inputs - Overlays and ambient declarations used for config reads and checker files.\n * @returns Virtual files, checker mappings, and declaration identities for the supplied sources.\n * @throws If configuration parsing, checker mapping, or declaration preparation fails.\n */\n prepareProject(\n sources: readonly TypeFactSource[],\n assets: ReadonlyMap<string, readonly AssetRecord[]>,\n inputs: TypeFactsInputs,\n ): PreparedProject {\n return prepareProject(\n sources,\n assets,\n this.#shadowTsconfigPath,\n this.#project,\n inputs,\n this.#configuredDeclarations(inputs),\n );\n }\n\n /**\n * Queries types once per expression in the current snapshot.\n *\n * @param checker - Checker that owns the current snapshot.\n * @param nodes - Expression nodes from that snapshot, in the requested order.\n * @returns Types in the same order. Undefined records a missing type. Answers are cached until the snapshot changes.\n * @throws If the checker query fails.\n */\n types(checker: Checker, nodes: readonly Node[]): (Type | undefined)[] {\n const keys = nodes.map((node) => `${node.getSourceFile().fileName}:${node.pos}:${node.end}`);\n const missing = new Map<string, Node>();\n for (const [index, key] of keys.entries()) {\n if (!this.#queryTypes.has(key)) {\n missing.set(key, nodes[index]);\n }\n }\n if (missing.size) {\n const values = checker.getTypeAtLocation([...missing.values()]);\n [...missing.keys()].forEach((key, index) => this.#queryTypes.set(key, values[index]));\n }\n return keys.map((key) => this.#queryTypes.get(key));\n }\n\n /**\n * Finds expression nodes once per file in the current snapshot.\n *\n * @param file - Source file from the current checker snapshot.\n * @returns Cached expression nodes in AST traversal order. Do not mutate the array.\n */\n expressions(file: SourceFile): readonly Node[] {\n let nodes = this.#queryNodes.get(file.fileName);\n if (!nodes) {\n const expressions: Node[] = [];\n visit(file, (node) => {\n if (isExpression(node)) {\n expressions.push(node);\n }\n });\n nodes = expressions;\n this.#queryNodes.set(file.fileName, nodes);\n }\n return nodes;\n }\n\n /**\n * Reads the consumer's declaration roots using the captured configuration overlays. Ordinary\n * source files selected by the consumer remain outside the generated project's root files.\n *\n * @param inputs - File replacements used while parsing the selected configuration.\n * @returns Declaration filenames selected by TypeScript, or an empty list for isolated settings.\n * Restores the overlay used by the retained snapshot before returning or throwing.\n * @throws If TypeScript cannot parse the selected configuration or its inherited files.\n */\n #configuredDeclarations(inputs: TypeFactsInputs): readonly string[] {\n if (this.#project.kind === \"isolated\") {\n return [];\n }\n const previous = this.#virtualFiles;\n this.#virtualFiles = new Map(\n [...(inputs.overlayFiles ?? []), ...(inputs.ambientDeclarations ?? [])].map(\n ([name, text]) => [normalize(name), text],\n ),\n );\n try {\n return this.#api\n .parseConfigFile(this.#project.configPath)\n .fileNames.filter((file) => /\\.d\\.[cm]?ts$/i.test(file));\n } finally {\n this.#virtualFiles = previous;\n }\n }\n\n /**\n * Starts a checker API whose filesystem callbacks consult the current virtual overlay.\n *\n * @returns A new API using the project root, with timing collection enabled. Increments starts\n * before construction. Read callbacks update the filesystem counters.\n * @throws If API construction fails.\n */\n #startApi(): API {\n this.stats.starts += 1;\n return withHiddenSpawnWindows(\n () =>\n new API({\n cwd: this.#projectRoot,\n collectTiming: true,\n fs: {\n directoryExists: (directoryName) => {\n const prefix = normalize(directoryName).replace(/\\/$/, \"\") + \"/\";\n return [...this.#virtualFiles.keys()].some((name) => name.startsWith(prefix))\n ? true\n : undefined;\n },\n fileExists: (fileName) => {\n this.dependencies.add(fileName);\n return this.#virtualFiles.has(normalize(fileName)) ? true : undefined;\n },\n readFile: (fileName) => {\n const overlay = this.#virtualFiles.get(normalize(fileName));\n if (overlay === undefined) {\n this.dependencies.add(fileName);\n this.stats.diskReadRequests += 1;\n } else {\n this.stats.overlayReads += 1;\n }\n return overlay;\n },\n },\n }),\n );\n }\n\n /**\n * Disposes the previous snapshot and API, then replaces the API without clearing virtual files or\n * counters.\n *\n * @throws If cleanup or creation of the replacement API fails.\n */\n restart(): void {\n this.#disposeApi();\n this.#api = this.#startApi();\n }\n\n /**\n * Releases the API and all answers whose objects belong to its snapshot.\n */\n #disposeApi(): void {\n this.#snapshot?.dispose();\n this.#snapshot = undefined;\n this.#clearQueries();\n this.#api.close();\n }\n\n /**\n * Discards query results before replacing a checker snapshot.\n */\n #clearQueries(): void {\n this.properties.named.clear();\n this.properties.all.clear();\n this.#queryTypes.clear();\n this.#queryNodes.clear();\n this.diagnostics.clear();\n }\n\n /**\n * Replaces virtual files and retains the new snapshot after releasing the previous one.\n *\n * @param prepared - Complete normalized virtual project, retained as the new filesystem overlay.\n * @returns The checker project from the new snapshot. Snapshot counters are incremented after update.\n * @throws If snapshot update or disposal fails, or the generated project cannot be opened.\n */\n updateProject(prepared: PreparedProject) {\n const changed: string[] = [];\n const created: string[] = [];\n const deleted: string[] = [];\n for (const [fileName, contents] of prepared.virtualFiles) {\n if (!this.#virtualFiles.has(fileName)) {\n (existsSync(fileName) ? changed : created).push(fileName);\n } else if (this.#virtualFiles.get(fileName) !== contents) {\n changed.push(fileName);\n }\n }\n for (const fileName of this.#virtualFiles.keys()) {\n if (!prepared.virtualFiles.has(fileName)) {\n (existsSync(fileName) ? changed : deleted).push(fileName);\n }\n }\n this.#virtualFiles = prepared.virtualFiles;\n\n if (this.#snapshot && changed.length === 0 && created.length === 0 && deleted.length === 0) {\n const project = this.#snapshot.getProject(this.#shadowTsconfigPath);\n if (project) {\n return project;\n }\n }\n\n this.#clearQueries();\n const next = this.#snapshot\n ? this.#api.updateSnapshot({\n fileChanges: {\n changed,\n created,\n deleted,\n },\n })\n : this.#api.updateSnapshot({\n openProjects: [this.#shadowTsconfigPath],\n });\n this.stats.snapshots += 1;\n if (this.#snapshot) {\n this.stats.incrementalSnapshots += 1;\n }\n this.#snapshot?.dispose();\n this.#snapshot = next;\n const project = next.getProject(this.#shadowTsconfigPath);\n if (!project) {\n throw new Error(\"TypeScript 7 could not open the Stillwind shadow project\");\n }\n return project;\n }\n\n /**\n * Releases the checker process and all objects owned by its snapshot.\n */\n close(): void {\n this.#disposeApi();\n }\n}\n","import type { NativeExportedValue, NativeIdentity, NativeSymbolicValue } from \"@stillwind/native\";\nimport {\n SignatureKind,\n TypeFlags,\n type Checker,\n type Type,\n type Symbol as TypeSymbol,\n} from \"typescript-7/unstable/sync\";\n\n/**\n * Result of decoding a checker type.\n *\n * `nonAsset` covers types whose values cannot be Stillwind assets: primitive types, macro use types,\n * and object types to which no producer type of the snapshot is assignable. `unbranded` covers object types without\n * asset branding to which a producer type is assignable. Such a value is not a macro receiver, but\n * it may hold an asset whose type was widened, so lowering cannot treat it as a confirmed\n * non-asset. Without producer types, every object type without branding is `unbranded`.\n */\ntype DecodedType =\n | {\n kind: \"asset\";\n value: NativeExportedValue;\n }\n | {\n kind: \"nonAsset\" | \"unbranded\" | \"unverified\";\n };\n\n/** Types whose values cannot be Stillwind assets. */\nconst primitiveTypeFlags =\n TypeFlags.StringLike |\n TypeFlags.NumberLike |\n TypeFlags.BigIntLike |\n TypeFlags.BooleanLike |\n TypeFlags.EnumLike |\n TypeFlags.ESSymbolLike |\n TypeFlags.Null |\n TypeFlags.Undefined |\n TypeFlags.Void |\n TypeFlags.Never;\n\n/**\n * Native declaration identity containing its asset kind, declaring module, original byte range, and\n * binding name.\n */\ntype IdentityId = NativeIdentity;\n\n/**\n * Decodes a string-literal identity type or union using the current declaration table.\n *\n * @param type - Checker type of an identity property, or undefined when the property is\n * unavailable.\n * @param identities - Serialized keys mapped to known native declaration identities.\n * @param kind - Asset family that every candidate must belong to.\n * @returns Candidates in type-member order. Returns `\"unknown\"` if the type is absent,\n * nonliteral, or unknown to the table, and `\"mismatch\"` if a candidate belongs to a\n * different asset family.\n */\nfunction knownIdentities(\n type: Type | undefined,\n identities: ReadonlyMap<string, IdentityId>,\n kind: IdentityId[\"kind\"],\n): \"unknown\" | \"mismatch\" | IdentityId[] {\n if (!type) {\n return \"unknown\";\n }\n const types = type.isUnionType() ? type.getTypes() : [type];\n const result: IdentityId[] = [];\n let unknown = false;\n for (const candidate of types) {\n const identity = candidate.isStringLiteralType() ? identities.get(candidate.value) : undefined;\n if (!identity) {\n unknown = true;\n continue;\n }\n if (identity.kind !== kind) {\n return \"mismatch\";\n }\n result.push(identity);\n }\n return unknown ? \"unknown\" : result;\n}\n\n/**\n * Packages known declarations as a finite native symbolic value.\n *\n * @param kind - Asset family shared by the supplied identities.\n * @param identities - Candidate identities retained in their supplied order.\n * @returns A finite symbolic value containing a copied candidate array.\n */\nfunction symbolic(\n kind: IdentityId[\"kind\"],\n identities: readonly IdentityId[],\n): NativeSymbolicValue {\n return {\n kind,\n candidates: {\n kind: \"finite\",\n values: [...identities],\n },\n };\n}\n\n/** Property lookups owned by one checker snapshot. */\nexport type TypePropertyCache = {\n /** Symbols keyed by type ID and property name. Missing properties are cached as undefined. */\n named: Map<string, TypeSymbol | undefined>;\n /** Complete property lists keyed by type ID from the same snapshot. */\n all: Map<number, readonly TypeSymbol[]>;\n};\n\n/**\n * Decodes checker types into native declaration candidates using brand properties discovered from\n * producer modules.\n */\nexport class AssetTypeDecoder {\n /**\n * Checker for the current project snapshot, used to inspect exported types and their properties.\n */\n readonly #checker: Checker;\n /** Shared property lookups. The owning service clears them before replacing the snapshot. */\n readonly #properties: TypePropertyCache;\n /**\n * All declaration keys registered in the current virtual project, mapped to original native\n * identities.\n */\n readonly #identities: ReadonlyMap<string, IdentityId>;\n /** Checker symbol IDs of modules whose exported asset brands have already been inspected. */\n readonly #modules = new Set<number>();\n /** Internal names of discovered unique-symbol brand properties mapped to their asset families. */\n readonly #brands = new Map<string, IdentityId[\"kind\"]>();\n /** Registered producer call types, used to detect object types that may hold a widened asset. */\n readonly #producers: Type[] = [];\n\n /**\n * Creates a decoder for one checker snapshot and declaration table.\n *\n * @param checker - Checker owning all types supplied to this decoder.\n * @param identities - Serialized identity keys inserted into the project's producer calls.\n * @param properties - Property cache for the same checker snapshot. May be shared with other decoders.\n */\n constructor(\n checker: Checker,\n identities: ReadonlyMap<string, IdentityId>,\n properties: TypePropertyCache,\n ) {\n this.#checker = checker;\n this.#identities = identities;\n this.#properties = properties;\n }\n\n /**\n * Looks up a named property once per snapshot, including missing properties.\n *\n * @param type - Type from this decoder's checker snapshot.\n * @param name - Property name to look up.\n * @returns The property symbol, or undefined when absent. Stores the answer in the shared cache.\n */\n #property(type: Type, name: string): TypeSymbol | undefined {\n const key = `${type.id}:${name}`;\n if (!this.#properties.named.has(key)) {\n this.#properties.named.set(key, this.#checker.getPropertyOfType(type, name));\n }\n return this.#properties.named.get(key);\n }\n\n /**\n * Looks up all properties of a type once per snapshot.\n *\n * @param type - Type from this decoder's checker snapshot.\n * @returns The cached property list. Do not mutate it.\n */\n #allProperties(type: Type): readonly TypeSymbol[] {\n let properties = this.#properties.all.get(type.id);\n if (!properties) {\n properties = this.#checker.getPropertiesOfType(type);\n this.#properties.all.set(type.id, properties);\n }\n return properties;\n }\n\n /**\n * Discovers ref, keyframe, view-transition, and stored-variant brands in a producer type's declaring module.\n *\n * @param type - Producer call type from this decoder's checker snapshot. The type is retained for\n * later decoding. Missing alias modules and already inspected modules are skipped. The discovered\n * property names are retained for later decoding.\n */\n register(type: Type): void {\n this.#producers.push(type);\n const module = type.getAliasSymbol()?.getParent();\n if (!module || this.#modules.has(module.id)) {\n return;\n }\n this.#modules.add(module.id);\n for (const [name, kind, brand] of [\n [\"StyleRef\", \"ref\", \"refIdentity\"],\n [\"StyleKeyframes\", \"keyframes\", \"keyframesIdentity\"],\n [\"StyleViewTransition\", \"viewTransition\", \"viewTransitionIdentity\"],\n [\"StyleStoredVariant\", \"storedVariant\", \"storedVariantIdentity\"],\n ] as const) {\n const symbol = this.#checker.getMemberInModuleExports(module, name);\n if (!symbol) {\n continue;\n }\n const declared = this.#checker.getDeclaredTypeOfSymbol(symbol);\n const property = this.#checker\n .getPropertiesOfType(declared)\n .find((property) => property.name.startsWith(`__@${brand}@`));\n if (property) {\n this.#brands.set(property.name, kind);\n }\n }\n }\n\n /**\n * Tests whether a type alias is declared by a registered macro module. Such a type describes a\n * macro use or declaration, not an author's widened asset.\n *\n * @param type - Type from this decoder's checker snapshot.\n * @returns Whether the alias symbol's module was inspected by {@link register}.\n */\n #declaredByMacro(type: Type): boolean {\n const module = type.getAliasSymbol()?.getParent();\n return !!module && this.#modules.has(module.id);\n }\n\n /**\n * Resolves a checker type to finite candidates from a single asset family.\n *\n * @param type - Type of a probed expression from the current checker snapshot.\n * @param recognitionOnly - True skips checks for widened asset types when only macro recognition is needed.\n * @returns Finite candidates, a confirmed non-asset, an object type that may hold a widened\n * asset, or an unverified value whose declarations cannot be determined.\n */\n decode(type: Type, recognitionOnly: boolean): DecodedType {\n if (type.flags & (TypeFlags.Any | TypeFlags.Unknown)) {\n return { kind: \"unverified\" };\n }\n const constituents = type.isUnionType() ? type.getTypes() : [type];\n const values: IdentityId[] = [];\n let family: IdentityId[\"kind\"] | undefined;\n let recognized = false;\n let valid = true;\n let finite = true;\n for (const constituent of constituents) {\n if (constituent.flags & primitiveTypeFlags) {\n valid = false;\n continue;\n }\n let kind: IdentityId[\"kind\"] | undefined;\n let identityType: Type | undefined;\n const style = this.#property(constituent, \"data-__stillwindStyleIdentity\");\n if (style) {\n kind = \"style\";\n identityType = this.#checker.getTypeOfSymbol(style);\n } else {\n for (const brand of this.#allProperties(constituent)) {\n const candidateKind = this.#brands.get(brand.name);\n if (!candidateKind) {\n continue;\n }\n const callable =\n candidateKind === \"viewTransition\" ? this.#property(constituent, \"for\") : undefined;\n const method = callable && this.#checker.getTypeOfSymbol(callable);\n // A stored variant is a branded string without methods, so its brand alone\n // identifies the declaration.\n const declaration =\n candidateKind === \"storedVariant\" ||\n (candidateKind === \"viewTransition\"\n ? method && this.#checker.getSignaturesOfType(method, SignatureKind.Call).length > 0\n : this.#checker.getSignaturesOfType(constituent, SignatureKind.Call).length > 0);\n if (!declaration) {\n continue;\n }\n kind = candidateKind;\n identityType = this.#checker.getTypeOfSymbol(brand);\n if (kind === \"ref\" && identityType) {\n const ref = this.#property(identityType, \"ref\");\n identityType = ref && this.#checker.getTypeOfSymbol(ref);\n }\n break;\n }\n }\n const name = (constituent.getAliasSymbol() ?? constituent.getSymbol())?.name;\n recognized ||=\n !!kind ||\n (!!name && /^Style(?:Result|Ref|Keyframes|ViewTransition|StoredVariant)$/.test(name));\n if (!kind) {\n valid = false;\n continue;\n }\n if (family && family !== kind) {\n valid = false;\n continue;\n }\n family = kind;\n const candidates = knownIdentities(identityType, this.#identities, kind);\n if (candidates === \"mismatch\") {\n valid = false;\n } else if (candidates === \"unknown\") {\n finite = false;\n } else {\n values.push(...candidates);\n }\n }\n if (valid && family === \"style\" && !finite) {\n // A style result with an unknown declaration still has a known runtime form. The\n // compiler merges it as a base without a CSS ordering dependency.\n return {\n kind: \"asset\",\n value: {\n kind: \"styles\",\n value: {\n kind: \"style\",\n candidates: {\n kind: \"universe\",\n },\n },\n },\n };\n }\n if (!valid || !family || values.length === 0) {\n if (recognized) {\n return {\n kind: \"unverified\",\n };\n }\n const widened =\n !recognitionOnly &&\n constituents.some(\n (constituent) =>\n !(constituent.flags & primitiveTypeFlags) &&\n !this.#declaredByMacro(constituent) &&\n (this.#producers.length === 0 ||\n this.#producers.some((producer) =>\n this.#checker.isTypeAssignableTo(producer, constituent),\n )),\n );\n return {\n kind: widened ? \"unbranded\" : \"nonAsset\",\n };\n }\n const kinds = {\n style: \"styles\",\n ref: \"refs\",\n keyframes: \"keyframes\",\n viewTransition: \"viewTransitions\",\n storedVariant: \"storedVariants\",\n } as const;\n return {\n kind: \"asset\",\n value: {\n kind: kinds[family],\n value: symbolic(family, values),\n },\n };\n }\n}\n","import type { NativeAssetRecord, NativeTypeFact } from \"@stillwind/native\";\nimport type { Node } from \"typescript-7/unstable/ast\";\nimport {\n isCallExpression,\n isExportDeclaration,\n isImportDeclaration,\n isSourceFile,\n isStringLiteral,\n} from \"typescript-7/unstable/ast/is\";\n\nimport {\n TypeFactsError,\n type AvailableFacts,\n type TypeFactSource,\n type TypeFactsBackend,\n type UnverifiedRange,\n} from \"../backend.ts\";\nimport { checkerId, withRequestedProbes } from \"../checker-source.ts\";\nimport { NodeChecker, type TypeScriptFactsStats } from \"./checker.ts\";\nimport { AssetTypeDecoder } from \"./decoder.ts\";\nimport { visit, diagnosticText, producerArgumentDiagnostic, factsForSource } from \"./facts.ts\";\nimport {\n normalize,\n type PreparedProject,\n type TypeFactsEnvironment,\n type TypeFactsInputs,\n} from \"./project.ts\";\n\n/**\n * Native declaration record carrying an identity, metadata, and the original-byte range of its\n * producer call.\n */\nexport type AssetRecord = NativeAssetRecord;\n\n/** Semantic value attached to an original UTF-8 expression range for native lowering. */\nexport type TypeFact = NativeTypeFact;\n\n/**\n * Collects declaration facts with a reusable Node checker. Close the service after pending queries finish.\n */\nexport class TypeScriptFactsService implements TypeFactsBackend {\n /** Project inputs retained until setProjectSources replaces them. Queries select a subset. */\n #installed?: {\n sources: readonly TypeFactSource[];\n assets: ReadonlyMap<string, readonly AssetRecord[]>;\n inputs: TypeFactsInputs;\n };\n\n /** Checker buffers prepared from the installed project inputs. */\n #prepared?: PreparedProject;\n\n /**\n * Whether close has been requested. Subsequent collections reject and repeated close calls do\n * nothing.\n */\n #closed = false;\n\n /** Checker process and snapshot caches owned by this service. */\n readonly #checker: NodeChecker;\n\n /** Paths observed by disk reads and existence checks, including missing paths and overlay checks. */\n readonly dependencies: Set<string>;\n\n /**\n * Live cumulative counters updated by this service. Consumers needing a stable report must copy\n * their values.\n */\n readonly stats: TypeScriptFactsStats;\n\n /**\n * Creates a service and starts its checker process without opening a snapshot.\n *\n * @param environment - Fixed project root and TypeScript settings.\n * @throws If the checker process cannot start.\n */\n constructor(environment: TypeFactsEnvironment) {\n this.#checker = new NodeChecker(environment);\n this.dependencies = this.#checker.dependencies;\n this.stats = this.#checker.stats;\n }\n\n /**\n * Keeps project inputs for later queries and clears prepared checker buffers.\n *\n * @param sources - Prepared project sources, retained by reference until replaced.\n * @param assets - Declarations grouped by compiler module ID, retained with the sources.\n * @param inputs - File overlays and ambient declarations. Omission supplies no extra files.\n * Do not mutate these inputs while they are installed. Queries select their own probes and sources.\n */\n setProjectSources(\n sources: readonly TypeFactSource[],\n assets: ReadonlyMap<string, readonly AssetRecord[]>,\n inputs: TypeFactsInputs = {},\n ): void {\n this.#installed = { sources, assets, inputs };\n this.#prepared = undefined;\n }\n\n /**\n * Collects finite declaration candidates for original-coordinate probes.\n *\n * Queries reuse the current snapshot when files have not changed. Mapping, assignment, and\n * identity errors throw TypeFactsError. Other checker failures restart the API and retry once.\n * Only diagnostics about Stillwind declaration contracts affect the result.\n *\n * @param sources - Prepared sources and original-byte probes, with validated projection\n * correspondences where needed.\n * @param assetsByModuleId - Declaration records keyed by compiler module identity.\n * @param inputs - Overlays and ambient declarations for an independent query. Omission supplies none.\n * When project sources are installed, preparation uses their installed inputs instead.\n * @returns Facts keyed by compiler module identity. Facts for the same original range are\n * deduplicated across buffers. Conflicting values throw. Known non-asset types produce null facts.\n * Unresolved recognition-only probes produce no fact.\n * @throws If the service is closed, preparation or checker contracts fail, or the API fails. A\n * failed query retry throws an AggregateError containing both query failures.\n */\n collect(\n sources: readonly TypeFactSource[],\n assetsByModuleId: ReadonlyMap<string, readonly AssetRecord[]>,\n inputs: TypeFactsInputs = {},\n ): Map<string, TypeFact[]> {\n return this.#collect(sources, assetsByModuleId, inputs, false).facts;\n }\n\n /**\n * Collects verified facts, reusing the snapshot when files have not changed.\n *\n * @param sources - Prepared sources and original UTF-8 probes with validated checker correspondences.\n * @param assetsByModuleId - Declaration records grouped by compiler module identity.\n * @param inputs - Overlays and ambient declarations for an independent query. Omission supplies none.\n * When project sources are installed, preparation uses their installed inputs instead.\n * @returns Verified facts and unavailable original ranges. Unavailable queries do not discard\n * facts collected for other expressions.\n * @throws If the service is closed, project preparation fails, facts conflict, or checker restart and retry fail.\n */\n collectAvailable(\n sources: readonly TypeFactSource[],\n assetsByModuleId: ReadonlyMap<string, readonly AssetRecord[]>,\n inputs: TypeFactsInputs = {},\n ): AvailableFacts {\n return this.#collect(sources, assetsByModuleId, inputs, true);\n }\n\n /**\n * Resolves authored imports and exports using module symbols in the selected TypeScript settings.\n *\n * @param sources - Prepared sources whose checker buffers contain the authored module requests.\n * Independent resolution ignores probes. An installed project also prepares its probes for later queries.\n * @param assetsByModuleId - Declaration records used to expose generated helper types.\n * @param inputs - Overlays and ambient declarations for independent resolution. Omission supplies none.\n * An installed project uses the inputs supplied by setProjectSources.\n * @returns Request-to-identity maps grouped by source resolver identity. Prepared checker paths\n * map back to resolver identities. Other resolutions retain checker filenames, including declarations.\n * Requests without a matching module symbol are omitted.\n * @throws If the service is closed, project preparation fails, or checker resolution fails.\n */\n resolveModules(\n sources: readonly TypeFactSource[],\n assetsByModuleId: ReadonlyMap<string, readonly AssetRecord[]>,\n inputs: TypeFactsInputs = {},\n ): Map<string, Map<string, string>> {\n if (this.#closed) {\n throw new Error(\"TypeScript facts service is closed\");\n }\n const inventory = this.#installed?.sources ?? sources;\n const prepared = this.#prepare(sources, assetsByModuleId, inputs, true);\n const project = this.#checker.updateProject(prepared);\n const result = new Map<string, Map<string, string>>();\n for (const mapping of prepared.mappings) {\n const file = project.program.getSourceFile(mapping.id);\n if (!file) {\n continue;\n }\n const resolutions = result.get(mapping.source.resolverId) ?? new Map<string, string>();\n result.set(mapping.source.resolverId, resolutions);\n visit(file, (node) => {\n if (\n !(isImportDeclaration(node) || isExportDeclaration(node)) ||\n !node.moduleSpecifier ||\n !isStringLiteral(node.moduleSpecifier)\n ) {\n return;\n }\n const symbol = project.checker.getSymbolAtLocation(node.moduleSpecifier);\n const declaration = symbol?.declarations.find((declaration) => {\n const node = declaration.resolve(project);\n return (\n node !== undefined && (isSourceFile(node) || node.getSourceFile().isDeclarationFile)\n );\n });\n if (declaration) {\n const fileName = declaration.resolve(project)!.getSourceFile().fileName;\n const original = inventory.find(\n (source) => normalize(checkerId(source)) === normalize(fileName),\n );\n const key = `${node.moduleSpecifier.getStart(file)}:${node.moduleSpecifier.end}`;\n resolutions.set(\n mapping.moduleSpecifiers.get(key) ?? node.moduleSpecifier.text,\n original?.resolverId ?? fileName,\n );\n }\n });\n }\n return result;\n }\n\n /**\n * Prepares one request and retries an unexpected checker failure once with a clean API.\n *\n * @param sources - Prepared sources and original UTF-8 probes.\n * @param assetsByModuleId - Declaration records grouped by compiler identity.\n * @param inputs - Complete overlays and ambient declarations for the request.\n * @param available - Whether unavailable facts are recorded instead of rejecting the request.\n * @returns Collected facts and unavailable ranges from the successful attempt.\n * @throws If preparation fails, a TypeFactsError occurs, restart fails, or both query attempts fail.\n */\n #collect(\n sources: readonly TypeFactSource[],\n assetsByModuleId: ReadonlyMap<string, readonly AssetRecord[]>,\n inputs: TypeFactsInputs,\n available: boolean,\n ): AvailableFacts {\n if (this.#closed) {\n throw new Error(\"TypeScript facts service is closed\");\n }\n if (this.#installed) {\n const updated = withRequestedProbes(this.#installed.sources, sources);\n if (updated !== this.#installed.sources) {\n this.#installed = { ...this.#installed, sources: updated };\n this.#prepared = undefined;\n }\n }\n const full = this.#prepare(sources, assetsByModuleId, inputs);\n const selected = new Set(sources.map((source) => source.resolverId));\n const mappings = full.mappings.filter((mapping) => selected.has(mapping.source.resolverId));\n const prepared = {\n ...full,\n mappings,\n identities: new Map(mappings.flatMap((mapping) => [...mapping.identities])),\n };\n try {\n return this.#collectPrepared(prepared, available);\n } catch (firstError) {\n if (firstError instanceof TypeFactsError) {\n throw firstError;\n }\n this.stats.restarts += 1;\n this.#restartApi();\n try {\n return this.#collectPrepared(prepared, available);\n } catch (retryError) {\n throw new AggregateError(\n [firstError, retryError],\n `TypeScript 7 checker failed before and after a clean restart: ${String(retryError)}`,\n );\n }\n }\n }\n\n /**\n * Reuses prepared project inputs or prepares only the requested sources if project preparation fails.\n *\n * @param sources - Requested sources to use when no project is installed or preparation fails.\n * @param assets - Declarations grouped by module ID for those sources.\n * @param inputs - Overlays and ambient declarations for the requested sources.\n * @param resolutionOnly - True omits probes when preparing only the requested sources for import resolution.\n * @returns Prepared checker files and mappings. Successful project preparation is cached.\n * @throws If the requested sources or their TypeScript configuration cannot be prepared.\n */\n #prepare(\n sources: readonly TypeFactSource[],\n assets: ReadonlyMap<string, readonly AssetRecord[]>,\n inputs: TypeFactsInputs,\n resolutionOnly = false,\n ): PreparedProject {\n if (this.#installed && this.#prepared) {\n return this.#prepared;\n }\n if (this.#installed) {\n try {\n this.#prepared = this.#checker.prepareProject(\n this.#installed.sources,\n this.#installed.assets,\n this.#installed.inputs,\n );\n return this.#prepared;\n } catch {\n // Unrelated invalid checker mappings must not reject a scoped query.\n }\n }\n return this.#checker.prepareProject(\n resolutionOnly ? sources.map((source) => ({ ...source, probes: [] })) : sources,\n assets,\n inputs,\n );\n }\n\n /**\n * Marks the service closed, disposes its retained snapshot, and closes the checker API. Repeated\n * calls return without further work.\n *\n * @throws If snapshot disposal or API cleanup fails.\n */\n close(): void {\n if (this.#closed) {\n return;\n }\n this.#closed = true;\n this.#prepared = undefined;\n this.#checker.close();\n }\n\n /**\n * Discards cached disk contents and the retained snapshot while keeping the selected environment.\n * The next collection opens a new project. Calls after close have no effect.\n *\n * @throws If checker cleanup or restart fails.\n */\n invalidate(): void {\n if (!this.#closed) {\n this.#restartApi();\n }\n }\n\n /**\n * Updates the snapshot and collects facts from the prepared checker buffers.\n *\n * @param prepared - Virtual files, original-coordinate mappings, and serialized declaration identities.\n * @param available - Whether contract failures become unverified ranges where recovery is possible.\n * @returns Deduplicated facts by compiler identity and unverified original UTF-8 ranges.\n * @throws If snapshot update fails, a checker file is missing, facts conflict, or strict collection fails.\n */\n #collectPrepared(prepared: PreparedProject, available: boolean): AvailableFacts {\n const project = this.#checker.updateProject(prepared);\n const unverified: UnverifiedRange[] = [];\n const result = new Map<string, TypeFact[]>();\n const decoder = new AssetTypeDecoder(\n project.checker,\n prepared.identities,\n this.#checker.properties,\n );\n const producers: Node[] = [];\n for (const mapping of prepared.mappings) {\n const file = project.program.getSourceFile(mapping.id);\n if (!file) {\n continue;\n }\n producers.push(\n ...this.#checker\n .expressions(file)\n .filter(\n (node) =>\n isCallExpression(node) && mapping.producers.has(`${node.getStart(file)}:${node.end}`),\n ),\n );\n }\n for (const type of this.#checker.types(project.checker, producers)) {\n if (type) {\n decoder.register(type);\n }\n }\n for (const mapping of prepared.mappings) {\n const sourceFile = project.program.getSourceFile(mapping.id);\n if (!sourceFile) {\n throw new Error(`TypeScript 7 omitted ${mapping.id}`);\n }\n let diagnostics = this.#checker.diagnostics.get(mapping.id);\n if (!diagnostics) {\n diagnostics = [\n ...project.program.getSyntacticDiagnostics(mapping.id),\n ...project.program.getSemanticDiagnostics(mapping.id),\n ];\n this.#checker.diagnostics.set(mapping.id, diagnostics);\n }\n const diagnostic = diagnostics.find(\n (d) =>\n !producerArgumentDiagnostic(d, sourceFile, mapping) &&\n /stillwind\\/v1:|StyleResult|StyleRef|StyleKeyframes|StyleViewTransition|StyleStoredVariant|__stillwindDeclarationIdentity|data-__stillwindStyleIdentity/.test(\n diagnosticText(d),\n ),\n );\n if (diagnostic) {\n const start = mapping.originalOffset(diagnostic.pos) ?? undefined;\n const end = mapping.originalOffset(diagnostic.end, true) ?? undefined;\n const message = diagnosticText(diagnostic).replace(\n /stillwind\\/v1:[A-Za-z0-9_-]+/g,\n \"declaration identity\",\n );\n const error = new TypeFactsError(\n mapping.source.moduleId,\n start,\n end,\n \"assignment\",\n `TS${diagnostic.code}: ${message} Preserve declaration candidates with an explicit union or a generic parameter.`,\n );\n if (!available) {\n throw error;\n }\n unverified.push({ moduleId: error.moduleId, start, end, reason: error.message });\n }\n const facts = factsForSource(\n sourceFile,\n mapping,\n decoder,\n this.#checker.expressions(sourceFile),\n (nodes) => this.#checker.types(project.checker, nodes),\n available ? unverified : undefined,\n );\n const previous = result.get(mapping.source.moduleId) ?? [];\n for (const fact of facts) {\n const existing = previous.find(\n (value) => value.start === fact.start && value.end === fact.end,\n );\n if (existing && JSON.stringify(existing.value) !== JSON.stringify(fact.value)) {\n throw new TypeFactsError(\n mapping.source.moduleId,\n fact.start,\n fact.end,\n \"checker\",\n \"Ambiguous checker results for this original expression\",\n );\n }\n if (!existing) {\n previous.push(fact);\n }\n }\n result.set(mapping.source.moduleId, previous);\n }\n return {\n facts: result,\n unverified,\n };\n }\n\n /**\n * Clears prepared inputs and replaces the checker process after invalidation or query failure.\n */\n #restartApi(): void {\n this.#prepared = undefined;\n this.#checker.restart();\n }\n}\n\n/**\n * Collects facts with a temporary checker service and closes it afterward.\n *\n * @param sources - Prepared sources and their original-byte semantic probes.\n * @param assetsByModuleId - Native declarations keyed by compiler module identity.\n * @param environment - Fixed filesystem root and TypeScript settings for the temporary checker.\n * @param inputs - File replacements and declarations required by this collection.\n * @returns Facts keyed by compiler module identity. The temporary checker is closed before returning.\n * @throws If service startup, fact collection, or cleanup fails.\n */\nexport function collectTypeScriptFacts(\n sources: readonly TypeFactSource[],\n assetsByModuleId: ReadonlyMap<string, readonly AssetRecord[]>,\n environment: TypeFactsEnvironment,\n inputs: TypeFactsInputs = {},\n): Map<string, TypeFact[]> {\n const service = new TypeScriptFactsService(environment);\n try {\n return service.collect(sources, assetsByModuleId, inputs);\n } finally {\n service.close();\n }\n}\n","import path from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\n\nimport {\n TraceMap,\n decodedMappings,\n originalPositionFor,\n sourceContentFor,\n} from \"@jridgewell/trace-mapping\";\nimport {\n fingerprint,\n type BindingLabel,\n type BindingLocation,\n type BindingReport,\n} from \"@stillwind/native\";\n\nimport { cleanModuleId, type PreparedSource } from \"../compilation/index.ts\";\n\n/**\n * Maps reports through upstream loader maps to their original source documents.\n *\n * @param reports - Reports with byte offsets and UTF-16 locations in prepared source documents.\n * @param sources - Prepared sources whose document metadata supplies upstream maps.\n * @param read - Reads original file text when the map has no embedded content, or when a label\n * needs a document-level fallback. Identities passed here are absolute file paths.\n * @returns Reports with original positions and content fingerprints. Unmappable labels become\n * document-scoped. An action is retained only when every edit maps to an unchanged text range.\n * @throws If required source reads or upstream map decoding fail.\n */\nexport async function mapAnalysisReports(\n reports: readonly BindingReport[],\n sources: readonly PreparedSource[],\n read: (id: string) => Promise<string>,\n): Promise<BindingReport[]> {\n const documents = new Map(sources.map((source) => [source.document.uri, source]));\n\n /**\n * Maps a location when both endpoints identify exact segments in the same original file.\n * @param location - Prepared document range with zero-based lines and UTF-16 columns.\n * @param exact - Whether the mapped and prepared ranges must contain identical text.\n * @returns The original location when no upstream map exists, a mapped location, or undefined\n * when endpoints, source identity, bounds, or required text equality cannot be established.\n * @throws If map decoding or a required original file read fails.\n */\n const mapLocation = async (\n location: BindingLocation,\n exact: boolean,\n ): Promise<BindingLocation | undefined> => {\n const source = documents.get(location.uri);\n if (!source?.document.upstreamMap) {\n return location;\n }\n const trace = new TraceMap(\n source.document.upstreamMap,\n path.isAbsolute(cleanModuleId(source.resolverId))\n ? pathToFileURL(cleanModuleId(source.resolverId)).href\n : undefined,\n );\n const start = originalPositionFor(trace, {\n line: location.startLine + 1,\n column: location.startColumn,\n });\n const end = originalPositionFor(trace, {\n line: location.endLine + 1,\n column: location.endColumn,\n });\n const mappings = decodedMappings(trace);\n /**\n * Checks whether a generated position has a segment containing an original source position.\n * @param line - Zero-based generated line.\n * @param column - Zero-based UTF-16 column that must equal a segment start.\n * @returns Whether a matching segment exists, or undefined when the line has no mappings.\n */\n const endpoint = (line: number, column: number) =>\n mappings[line]?.some((segment) => segment.length > 1 && segment[0] === column);\n if (\n !endpoint(location.startLine, location.startColumn) ||\n !endpoint(location.endLine, location.endColumn)\n ) {\n return;\n }\n if (\n !start.source ||\n start.source !== end.source ||\n start.line === null ||\n end.line === null ||\n start.column === null ||\n end.column === null\n ) {\n return;\n }\n const uri = start.source.startsWith(\"file:\")\n ? start.source\n : path.isAbsolute(start.source)\n ? pathToFileURL(start.source).href\n : undefined;\n if (!uri) {\n return;\n }\n const code = sourceContentFor(trace, start.source) ?? (await read(fileURLToPath(uri)));\n /**\n * Converts an original map position to an offset in the captured text.\n * @param line - One-based original line.\n * @param column - Nonnegative UTF-16 column that excludes a trailing carriage return.\n * @returns A UTF-16 offset, or undefined when the line or column exceeds the text bounds.\n */\n const offset = (line: number, column: number) => {\n const lines = code.split(\"\\n\");\n if (line < 1 || line > lines.length || column > lines[line - 1].replace(/\\r$/, \"\").length) {\n return;\n }\n return lines.slice(0, line - 1).reduce((sum, text) => sum + text.length + 1, 0) + column;\n };\n const startUtf16 = offset(start.line, start.column);\n const endUtf16 = offset(end.line!, end.column!);\n if (\n startUtf16 === undefined ||\n endUtf16 === undefined ||\n endUtf16 < startUtf16 ||\n (exact &&\n code.slice(startUtf16, endUtf16) !==\n source.document.code.slice(location.startUtf16, location.endUtf16))\n ) {\n return;\n }\n return {\n uri,\n revision: fingerprint(code),\n start: Buffer.byteLength(code.slice(0, startUtf16)),\n end: Buffer.byteLength(code.slice(0, endUtf16)),\n startUtf16,\n endUtf16,\n startLine: start.line - 1,\n startColumn: start.column,\n endLine: end.line! - 1,\n endColumn: end.column!,\n };\n };\n\n /**\n * Maps a label or limits it to document scope when its range cannot be mapped.\n * @param value - Label in a prepared document. The input object is not mutated.\n * @returns A copied label. A readable file fallback receives a current fingerprint and zero range.\n * @throws If map decoding or a required file read fails.\n */\n const label = async (value: BindingLabel): Promise<BindingLabel> => {\n const mapped = await mapLocation(value.location, false);\n if (mapped) {\n return {\n ...value,\n location: mapped,\n };\n }\n const source = documents.get(value.location.uri);\n const file = source && cleanModuleId(source.resolverId);\n if (file && path.isAbsolute(file)) {\n const code = await read(file);\n return {\n ...value,\n scope: \"document\",\n location: {\n ...value.location,\n uri: pathToFileURL(file).href,\n revision: fingerprint(code),\n start: 0,\n end: 0,\n startUtf16: 0,\n endUtf16: 0,\n startLine: 0,\n endLine: 0,\n startColumn: 0,\n endColumn: 0,\n },\n };\n }\n return {\n ...value,\n scope: \"document\",\n };\n };\n\n return Promise.all(\n reports.map(async (report) => {\n const actions: BindingReport[\"actions\"] = [];\n for (const action of report.actions) {\n const edits = await Promise.all(\n action.edits.map(async (edit) => {\n const location = await mapLocation(edit.location, true);\n return (\n location && {\n ...edit,\n location,\n }\n );\n }),\n );\n if (edits.every((edit) => edit !== undefined)) {\n actions.push({\n ...action,\n edits,\n });\n }\n }\n return {\n ...report,\n primary: await label(report.primary),\n related: await Promise.all(report.related.map(label)),\n actions,\n };\n }),\n );\n}\n","import path from \"node:path\";\nimport process from \"node:process\";\nimport { fileURLToPath } from \"node:url\";\n\nimport type { BaseConfig, PreviewOptions } from \"@stillwind/config\";\nimport {\n NativeProjectSession,\n type BindingReport,\n type NativeDesignSystemLoader,\n} from \"@stillwind/native\";\n\nimport type { CompilerHost } from \"../../compilation/index.ts\";\nimport {\n attachPlugins,\n isStylesheet,\n loadCssGraph,\n loadEditorCssGraph,\n pluginLoader,\n type CssHost,\n type CssPluginInputs,\n type EditorCssGraph,\n type PluginRuntime,\n} from \"../../css/index.ts\";\nimport type { DesignSystemContext } from \"../../editor/index.ts\";\nimport type { TypeFactsEnvironment } from \"../../semantics/index.ts\";\nimport { compilerOptions, cssEntrypoint } from \"../options.ts\";\nimport { StylesheetEditor } from \"../stylesheet-editor.ts\";\n\n/**\n * Loads compiler inputs and CSS for one Node analysis project. AnalysisProject serializes calls\n * and installs captured document contents before asking this backend to resolve or load modules.\n */\nexport interface AnalysisHost extends CompilerHost {\n /** Absolute project directory used for identities and CSS paths. */\n root: string;\n /**\n * Compiler and preview settings fixed for this host's lifetime. Relative CSS and tsconfig paths\n * use root.\n */\n config: BaseConfig & {\n preview?: PreviewOptions;\n };\n /** CSS resolution and reads using the same captured document buffers as source loading. */\n css: CssHost;\n /** Fixed TypeScript settings selected when this host opens. */\n readonly typeFactsEnvironment: TypeFactsEnvironment;\n /** False disables additional semantic queries for this project. */\n readonly typeFacts?: false;\n /**\n * Checks whether a resolved target can be analyzed by this host.\n *\n * @param id - Full resolver identity of the target.\n * @returns Whether load can supply supported source for the identity.\n */\n supports(id: string): boolean;\n /**\n * Replaces all buffers used by subsequent source and CSS reads.\n *\n * @param documents - Absolute file paths to captured text. Missing entries use backend reads.\n * @returns A promise that resolves when subsequent reads can use the supplied snapshot.\n * @throws If the backend cannot install the supplied buffers.\n */\n setDocuments(documents: ReadonlyMap<string, string>): Promise<void>;\n /**\n * Discards backend caches before the next transaction. Must not overlap resolution or loads.\n *\n * @returns A promise that resolves when cached reads and resolutions have been invalidated.\n * @throws If backend invalidation fails.\n */\n invalidate(): Promise<void>;\n /**\n * Releases backend resources. The caller first waits for pending host operations.\n *\n * @returns A promise for cleanup completion.\n * @throws If backend cleanup fails.\n */\n close(): Promise<void>;\n}\n\n/**\n * Loads CSS and tracks the host dependencies that require a fresh design system.\n */\nexport class AnalysisCss {\n /** Files read by CSS or plugins. Open-buffer changes to these files reload CSS. */\n readonly #dependencies = new Set<string>();\n\n /** Delegates CSS operations to the host and records watched dependencies. */\n readonly #css: CssHost;\n\n /** CSS loader retained until a CSS update or explicit invalidation. */\n #loader?: NativeDesignSystemLoader;\n\n /** Session that uses the retained loader. Replaced when CSS changes. */\n #session?: NativeProjectSession;\n\n /** Query-only CSS graph, rebuilt after CSS changes and kept separate from strict analysis. */\n #editorCss?: EditorCssGraph;\n\n /** Identities that the retained loader marked for stylesheet lint, in load order. */\n #lintSources: string[] = [];\n\n /**\n * Plugin runtime of the retained loader. A CSS update keeps it as the previous runtime of the\n * next load, so definitions of unchanged plugins survive.\n */\n #plugins?: PluginRuntime;\n\n /** Host operations are called only inside the project's serialized transactions. */\n readonly #host: AnalysisHost;\n\n /**\n * Wraps CSS watching without loading files.\n * @param host - Host owned by the analysis project. Calls retain the host as their receiver.\n */\n constructor(host: AnalysisHost) {\n this.#host = host;\n this.#css = {\n resolve: (specifier, importer) => host.css.resolve(specifier, importer),\n read: (id) => host.css.read(id),\n documentUri: (id) => host.css.documentUri(id),\n sourceMapSource: (id) => host.css.sourceMapSource(id),\n plugins: host.css.plugins,\n lint: host.css.lint?.bind(host.css),\n watch: (id) => {\n this.#dependencies.add(id);\n host.css.watch(id);\n },\n };\n }\n\n /** Current strict loader, or undefined before loading or after invalidation. */\n get loader(): NativeDesignSystemLoader | undefined {\n return this.#loader;\n }\n\n /** Session that uses the strict loader, or undefined until load succeeds. */\n get session(): NativeProjectSession | undefined {\n return this.#session;\n }\n\n /** Plugin runtime of the latest successful load. Kept across CSS changes for reuse. */\n get plugins(): PluginRuntime | undefined {\n return this.#plugins;\n }\n\n /** Stylesheets marked for lint by the last strict load, in load order. */\n get lintSources(): readonly string[] {\n return this.#lintSources;\n }\n\n /**\n * Checks whether an open-buffer edit requires reloading CSS.\n *\n * @param id - Absolute path of the changed document.\n * @returns Whether it is a stylesheet or a dependency watched by CSS or a plugin.\n */\n affects(id: string): boolean {\n return isStylesheet(id) || [...this.#dependencies].some((file) => sameFile(file, id));\n }\n\n /** Returns the files that CSS or plugins have read. */\n get dependencies(): ReadonlySet<string> {\n return this.#dependencies;\n }\n\n /**\n * Discards loaders and the native session while keeping plugins available for the next load.\n */\n invalidate(): void {\n this.#loader = undefined;\n this.#session = undefined;\n this.#editorCss = undefined;\n }\n\n /**\n * Discards a failed plugin runtime and the loaders that depend on it before individual analysis retries.\n */\n discardPlugins(): void {\n this.invalidate();\n this.#plugins = undefined;\n }\n\n /**\n * Loads the configured CSS graph once until CSS invalidation clears it.\n *\n * @returns The retained loader with compiler options applied.\n * @throws If resolving, reading, or loading the CSS graph fails.\n */\n async load(): Promise<NativeDesignSystemLoader> {\n if (!this.#loader) {\n const css = path.resolve(this.#host.root, cssEntrypoint(this.#host.config));\n const loaded = await loadCssGraph(\n css,\n compilerOptions(this.#host.config),\n this.#css,\n undefined,\n undefined,\n this.#pluginInputs(),\n );\n this.#loader = loaded.loader;\n this.#lintSources = loaded.lintSources;\n this.#plugins = loaded.plugins;\n this.#session = new NativeProjectSession(\n this.#loader,\n false,\n \"development\",\n this.#host.config.naming,\n );\n attachPlugins(this.#session, this.#plugins, this.#plugins?.generation);\n }\n return this.#loader;\n }\n\n /**\n * Loads the design system for questions that read no source file.\n *\n * @returns A query over the definitions of the latest plugin load, and the plugin runtime.\n * @throws If resolving, reading, or loading the CSS graph fails.\n */\n async designSystem(): Promise<Pick<DesignSystemContext, \"query\" | \"plugins\">> {\n const loader = await this.load();\n return {\n query: (pluginLoader(this.#session!) ?? loader).editorQuery(),\n plugins: this.#plugins,\n };\n }\n\n /**\n * Selects the plugins of the project's CSS graph.\n *\n * @returns Configured plugins, the project root, and the runtime of the last load.\n */\n #pluginInputs(): CssPluginInputs {\n return {\n plugins: this.#host.config.plugins,\n tailwind: this.#host.config.tailwind,\n important: this.#host.config.important,\n root: this.#host.root,\n previous: this.#plugins,\n };\n }\n\n /**\n * Loads a query graph from original CSS or recovered definitions, without publishing its reports.\n *\n * @returns The cached editor graph, reusing the strict loader when available. Otherwise, a failed\n * original load is retried with recovered definitions. CSS invalidation clears this cache.\n * @throws If neither the original nor the recovered CSS graph can be resolved, read, and loaded.\n */\n async editor(): Promise<EditorCssGraph> {\n if (!this.#editorCss) {\n if (this.#loader) {\n this.#editorCss = {\n loader: this.#loader,\n resources: [],\n lintSources: this.#lintSources,\n recovered: false,\n plugins: this.#plugins,\n };\n } else {\n this.#editorCss = await loadEditorCssGraph(\n path.resolve(this.#host.root, cssEntrypoint(this.#host.config)),\n compilerOptions(this.#host.config),\n this.#css,\n this.#pluginInputs(),\n );\n }\n }\n return this.#editorCss;\n }\n\n /**\n * Creates a strict stylesheet editor and its lint reports.\n *\n * @param entry - Absolute stylesheet path in this host.\n * @returns Reports for that document and an editor using the same CSS definitions.\n * @throws If CSS loading, source reading, or plugin catalog loading fails.\n */\n async stylesheet(\n entry: string,\n ): Promise<{ reports: BindingReport[]; snapshot: StylesheetEditor }> {\n const loader = await this.load();\n const reports = loader.stylesheetReports().filter((report) => {\n const uri = report.primary.location.uri;\n return uri.startsWith(\"file:\")\n ? sameFile(fileURLToPath(uri), entry)\n : uri === this.#host.css.documentUri(entry);\n });\n return {\n reports,\n snapshot: new StylesheetEditor(\n entry,\n await this.#host.css.read(entry),\n reports,\n loader.editorQuery(),\n this.#host.config,\n (await this.#plugins?.catalog()) ?? [],\n this.#plugins,\n ),\n };\n }\n\n /**\n * Creates an editor from original CSS, or from recovered definitions when strict loading fails.\n *\n * @param entry - Absolute stylesheet path. Files outside the linted CSS graph are skipped.\n * @returns The editor and whether recovery was needed, or undefined outside the graph.\n * @throws If CSS recovery, source reading, or plugin catalog loading fails.\n */\n async editorSnapshot(\n entry: string,\n ): Promise<{ snapshot: StylesheetEditor; recovered: boolean } | undefined> {\n const graph = await this.editor();\n if (!graph.lintSources.some((source) => sameFile(source, entry))) {\n return undefined;\n }\n const reports = graph.recovered\n ? []\n : graph.loader\n .stylesheetReports()\n .filter((report) => report.primary.location.uri === this.#host.css.documentUri(entry));\n return {\n recovered: graph.recovered,\n snapshot: new StylesheetEditor(\n entry,\n await this.#host.css.read(entry),\n reports,\n graph.loader.editorQuery(),\n this.#host.config,\n (await graph.plugins?.catalog()) ?? [],\n graph.plugins,\n ),\n };\n }\n}\n\n/**\n * Compares file paths as the host filesystem does.\n *\n * @param a - File path resolved against the process working directory when relative.\n * @param b - File path resolved in the same way.\n * @returns Whether both paths name the same file, ignoring case on Windows.\n */\nexport function sameFile(a: string, b: string): boolean {\n /**\n * Normalizes a path for comparison.\n *\n * @param file - File path.\n * @returns The absolute path, lowercased on Windows.\n */\n const key = (file: string) =>\n process.platform === \"win32\" ? path.resolve(file).toLowerCase() : path.resolve(file);\n return key(a) === key(b);\n}\n","import path from \"node:path\";\n\nimport type { BindingReport } from \"@stillwind/native\";\n\nimport { analyzeModule, type ModuleAnalysis } from \"../../compilation/index.ts\";\nimport { CompilationProject, sourceKey } from \"../../compilation/project.ts\";\nimport { isStylesheet } from \"../../css/index.ts\";\nimport { queryPluginPaths } from \"../../css/plugins/paths.ts\";\nimport { prepareSourcePlugins } from \"../../css/plugins/session.ts\";\nimport {\n EditorSnapshot,\n queryDesignSystem,\n type DesignSystemRequest,\n type DesignSystemResult,\n type EditorRequest,\n type EditorResult,\n} from \"../../editor/index.ts\";\nimport {\n TypeScriptFactsService,\n type TypeFactsBackend,\n type TypeScriptFactsStats,\n} from \"../../semantics/index.ts\";\nimport { mapAnalysisReports } from \"../diagnostic-map.ts\";\nimport { StylesheetEditor } from \"../stylesheet-editor.ts\";\nimport { AnalysisCss, type AnalysisHost } from \"./host.ts\";\n\n/**\n * Result of an unpublished analysis at one project revision.\n */\nexport interface AnalysisResult {\n /** Entry resolver identity supplied to analyze. */\n entry: string;\n /** Project change counter captured when analysis was queued. */\n revision: number;\n /**\n * Complete describes available analysis inputs, even if reports contain compiler errors.\n * Incomplete retains partial findings or an exception. Stale and cancelled omit reports and graph.\n */\n status: \"complete\" | \"incomplete\" | \"stale\" | \"cancelled\";\n /** Findings mapped to original document URIs and zero-based UTF-16 positions. */\n reports: BindingReport[];\n /** Observed semantic graph, including dependency status and unavailable facts. Omitted on discard or early failure. */\n graph?: ModuleAnalysis;\n /** Caught exception as text. Compiler reports alone do not populate this field. */\n error?: string;\n}\n\n/**\n * Owns open buffers, checker queries, and serialized analysis for one host.\n */\nexport class AnalysisProject {\n /** Prepared sources shared by analyses of different entries. */\n readonly #compilation = new CompilationProject();\n\n /** CSS state and dependencies owned by this project. */\n readonly #css: AnalysisCss;\n\n /** Owned host. The project serializes its operations and closes it during cleanup. */\n readonly host: AnalysisHost;\n\n /** Optional factory used once when semantic analysis first needs a backend. */\n readonly #backend?: () => TypeFactsBackend;\n\n /** Unsaved original buffers keyed by absolute path and captured before each queued operation. */\n readonly #documents = new Map<\n string,\n {\n /** Complete original document text. */\n source: string;\n /** Last accepted safe integer version while the path is open. */\n version: number;\n }\n >();\n\n /** Editor snapshots retained by entry identity until their project revision changes. */\n readonly #editors = new Map<\n string,\n {\n /** Project change counter represented by this snapshot. */\n revision: number;\n /** Immutable view used for editor queries: a script graph or one linted stylesheet. */\n snapshot: EditorSnapshot | StylesheetEditor;\n /** True when CSS definitions were recovered and structural edits require strict analysis. */\n recovered?: boolean;\n }\n >();\n\n /** Lazily selected custom or Node semantic backend owned by this project. */\n #semantics?: TypeFactsBackend;\n\n /** Change counter used to discard pending analyses and editor answers. */\n #revision = 0;\n\n /** Serializes transactions and absorbs failures before subsequent work. */\n #queue: Promise<unknown> = Promise.resolve();\n\n /** Node backend retained separately to expose checker statistics. */\n #facts?: TypeScriptFactsService;\n\n /** Requests backend invalidation before the next transaction. */\n #dirty = true;\n\n /** Requests replacement of the cached CSS loader. */\n #cssDirty = true;\n\n /** Requests semantic disk-cache invalidation after an external change. */\n #diskDirty = true;\n\n /** Prevents transactions from producing new results during cleanup. */\n #closed = false;\n\n /**\n * Takes ownership of a backend without loading CSS or starting a checker.\n *\n * @param host - Initialized backend whose TypeScript environment uses the same root. Release\n * this project with `close` when its analysis services are no longer needed.\n * @param backend - Optional lazy semantic backend factory. Omission selects the Node checker.\n */\n constructor(host: AnalysisHost, backend?: () => TypeFactsBackend) {\n this.host = host;\n this.#css = new AnalysisCss(host);\n this.#backend = backend;\n }\n\n /**\n * Reads counters from the owned Node checker without exposing its mutable statistics object.\n * @returns A copy of the counters, or undefined before checker creation or with a custom backend.\n */\n get checkerStats(): TypeScriptFactsStats | undefined {\n return this.#facts && { ...this.#facts.stats };\n }\n\n /**\n * Stores an unsaved buffer. Changed text advances the revision and makes pending results stale.\n *\n * @param id - File path resolved from the process working directory when relative.\n * @param source - Complete original document text.\n * @param version - Safe integer greater than the open buffer's version. An identical buffer and\n * version have no effect. Identical text with a newer version updates only the version.\n * A document can restart its version sequence after closeDocument.\n * @throws If the version is invalid or does not increase for a changed open buffer.\n */\n update(id: string, source: string, version: number): void {\n id = path.resolve(id);\n const previous = this.#documents.get(id);\n if (previous?.version === version && previous.source === source) {\n return;\n }\n if (!Number.isSafeInteger(version) || (previous && previous.version >= version)) {\n throw new Error(\"Analysis document versions must increase\");\n }\n this.#documents.set(id, {\n source,\n version,\n });\n if (previous?.source === source) {\n return;\n }\n if (this.#compilation.source(id)?.document.code !== source) {\n this.#compilation.invalidate(id);\n }\n this.#revision++;\n this.#dirty = true;\n this.#cssDirty ||= this.#css.affects(id);\n }\n\n /**\n * Removes an unsaved buffer and advances the revision when one existed.\n *\n * @param id - File path, resolved in the same way as update. Later reads use the host's source\n * provider. Unknown paths have no effect.\n */\n closeDocument(id: string): void {\n id = path.resolve(id);\n if (this.#documents.delete(id)) {\n this.#compilation.invalidate(id);\n this.#revision++;\n this.#dirty = true;\n this.#cssDirty ||= this.#css.affects(id);\n }\n }\n\n /**\n * Lists the files that analysis has observed, for comparison with paths in watch notifications.\n *\n * @returns Keys from `sourceKey` for prepared sources, files that CSS or plugins read, and paths\n * that the checker read or tested, including missing paths. A custom semantic backend contributes\n * nothing.\n */\n reads(): Set<string> {\n return new Set([\n ...this.#compilation.sourceKeys(),\n ...[...this.#css.dependencies, ...(this.#facts?.dependencies ?? [])].map(sourceKey),\n ]);\n }\n\n /** Makes pending results stale. The next transaction rebuilds CSS and backend caches. */\n invalidate(): void {\n this.#compilation.invalidate();\n this.#revision++;\n this.#dirty = true;\n this.#cssDirty = true;\n this.#diskDirty = true;\n }\n\n /**\n * Lists the stylesheets that this project lints, using the document contents captured when this\n * method is called.\n *\n * @param editor - When false (the default), loads the original CSS and rejects invalid input.\n * When true, retries a failed load with recovered definitions so incomplete CSS can still\n * determine membership for completion, hover, and colors.\n * @returns Identities of the CSS entry and the imported files that the CSS host marks for lint,\n * in load order. Package CSS is excluded unless the host marks it. Returns an empty list\n * if the captured buffers become outdated before loading starts.\n * @throws If the project is closed, installing buffers or invalidating caches fails, or the\n * selected CSS loading mode fails.\n */\n stylesheets(editor = false): Promise<string[]> {\n const revision = this.#revision;\n const documents = new Map([...this.#documents].map(([id, document]) => [id, document.source]));\n const task = this.#queue.then(async () => {\n if (this.#closed) {\n throw new Error(\"Analysis project is closed\");\n }\n if (!(await this.#installDocuments(documents, revision))) {\n return [];\n }\n\n if (editor) {\n return [...(await this.#css.editor()).lintSources];\n }\n await this.#css.load();\n return [...this.#css.lintSources];\n });\n this.#queue = task.catch(() => {});\n return task;\n }\n\n /**\n * Queues analysis using the document contents and revision captured when this method is called.\n *\n * @param entry - Full resolver identity of a supported target, or of a stylesheet that\n * {@link stylesheets} lists. A stylesheet's reports are its stylesheet lint findings, and its\n * result has no graph. Membership filtering is performed by AnalysisWorkspace, not by this\n * project.\n * @param signal - Optional cancellation checked before and after queued work. Cancellation\n * discards results without interrupting a checker query that has already started.\n * @returns Reports for the entry and demanded semantic dependencies. Host failures appear as\n * incomplete results with error text. Unavailable semantic information appears in the graph's\n * unverified ranges. Stale and cancelled results omit reports and graphs.\n */\n analyze(entry: string, signal?: AbortSignal): Promise<AnalysisResult> {\n const revision = this.#revision;\n const documents = new Map([...this.#documents].map(([id, document]) => [id, document.source]));\n const task = this.#queue.then(async (): Promise<AnalysisResult> => {\n const before = this.#discardReason(revision, signal);\n if (before) {\n return discardedResult(entry, revision, before);\n }\n const result = await this.#analyzeSnapshot(entry, revision, documents);\n const after = this.#discardReason(revision, signal);\n return after ? discardedResult(entry, revision, after) : result;\n });\n\n this.#queue = task.catch(() => {});\n return task;\n }\n\n /**\n * Loads targets together and prepares plugin candidates using the current buffers.\n *\n * @param entries - Full resolver IDs. The workspace must apply project membership rules first.\n * @returns Completion of preparation. Closed or outdated requests stop without publishing results.\n * Loading and plugin failures are left for each target's analysis to report. A failed plugin\n * runtime is discarded before retrying.\n */\n prepare(entries: readonly string[]): Promise<void> {\n const revision = this.#revision;\n const documents = new Map([...this.#documents].map(([id, document]) => [id, document.source]));\n const task = this.#queue.then(async () => {\n if (this.#closed || this.#discardReason(revision)) {\n return;\n }\n try {\n if (!(await this.#installDocuments(documents, revision))) {\n return;\n }\n\n const loader = await this.#css.load();\n if (this.#discardReason(revision)) {\n return;\n }\n await this.#compilation.prepare(entries, this.host, this.#css.session!);\n await prepareSourcePlugins(this.#css.session!, loader, this.#compilation.texts());\n } catch {\n this.#css.discardPlugins();\n // Scoped analysis reports loading and preparation failures for their original targets.\n }\n });\n this.#queue = task.catch(() => {});\n return task;\n }\n\n /**\n * Queries the captured analysis for an entry. Buffer changes or cancellation discard its answer.\n * CSS completion, hover, resolution, and colors can load recovered definitions for incomplete\n * input. CSS sorting and lint fixes require the original graph to load successfully.\n * Plugin path completion and links read captured CSS inside the project root without loading\n * its graph or executing plugins.\n *\n * @param entry - Full resolver identity. The workspace applies target membership filtering.\n * @param request - Operation with offsets in the original UTF-16 document.\n * @param signal - Optional cancellation checked before and after queued work.\n * @returns The current editor answer, or undefined after closure, cancellation, a revision change,\n * failed entry analysis, or a semantic CSS query outside the graph's stylesheets marked for lint.\n * @throws If preparing a CSS query fails or the editor query rejects a candidate or preview.\n */\n query(\n entry: string,\n request: EditorRequest,\n signal?: AbortSignal,\n ): Promise<EditorResult | undefined> {\n const revision = this.#revision;\n const documents = new Map([...this.#documents].map(([id, document]) => [id, document.source]));\n const task = this.#queue.then(async () => {\n if (this.#closed || this.#discardReason(revision, signal)) {\n return undefined;\n }\n if (isStylesheet(entry) && [\"completion\", \"resolve\", \"links\"].includes(request.kind)) {\n if (!(await this.#installDocuments(documents, revision, signal))) {\n return undefined;\n }\n const text = await this.host.css.read(entry).catch(() => undefined);\n if (text === undefined) {\n return undefined;\n }\n const navigation = await queryPluginPaths(entry, text, request, {\n root: this.host.root,\n names: this.host.config.plugins?.map((plugin) => plugin.name) ?? [],\n host: this.host.css.plugins,\n documentUri: (id) => this.host.css.documentUri(id),\n });\n if (navigation) {\n return this.#discardReason(revision, signal) ? undefined : navigation;\n }\n }\n const structural = request.kind === \"sort\" || request.kind === \"fixes\";\n if (structural && this.#editors.get(entry)?.recovered) {\n this.#editors.delete(entry);\n }\n if (this.#editors.get(entry)?.revision !== revision) {\n if (\n isStylesheet(entry) &&\n [\"completion\", \"hover\", \"resolve\", \"colors\", \"colorPresentation\"].includes(request.kind)\n ) {\n if (!(await this.#installDocuments(documents, revision, signal))) {\n return undefined;\n }\n const editor = await this.#css.editorSnapshot(entry);\n if (!editor) {\n return undefined;\n }\n this.#editors.set(entry, {\n revision,\n ...editor,\n });\n } else {\n await this.#analyzeSnapshot(entry, revision, documents);\n }\n }\n const snapshot = this.#editors.get(entry)?.snapshot;\n await snapshot?.prepare(entry, request);\n const result = snapshot?.query(entry, request);\n return this.#discardReason(revision, signal) ? undefined : result;\n });\n this.#queue = task.catch(() => {});\n return task;\n }\n\n /**\n * Answers a question about the design system, using the current buffers.\n *\n * @param request - Theme, utility, or variant request.\n * @returns The answer, or undefined when the captured buffers become outdated.\n * @throws If the project is closed, CSS loading fails, or a plugin fails.\n */\n designSystem(request: DesignSystemRequest): Promise<DesignSystemResult | undefined> {\n const revision = this.#revision;\n const documents = new Map([...this.#documents].map(([id, document]) => [id, document.source]));\n const task = this.#queue.then(async () => {\n if (this.#closed) {\n throw new Error(\"Analysis project is closed\");\n }\n if (!(await this.#installDocuments(documents, revision))) {\n return undefined;\n }\n return queryDesignSystem(\n {\n ...(await this.#css.designSystem()),\n annotations: this.host.config.preview,\n },\n request,\n );\n });\n this.#queue = task.catch(() => {});\n return task;\n }\n\n /**\n * Marks the project closed, discards pending results, and waits for queued work before cleanup.\n * Repeated calls return without requesting further cleanup.\n *\n * @throws If checker or backend cleanup fails.\n * @returns A promise that resolves after queued analysis and cleanup. Repeated calls made after\n * closure starts return immediately. They do not wait for the first call's cleanup.\n */\n async close(): Promise<void> {\n if (this.#closed) {\n return;\n }\n\n this.#closed = true;\n this.#editors.clear();\n this.#revision++;\n await this.#queue;\n\n const results = await Promise.allSettled([\n Promise.resolve().then(() => this.#semantics?.close()),\n Promise.resolve().then(() => this.host.close()),\n ]);\n const errors = results.flatMap((result) =>\n result.status === \"rejected\" ? [result.reason] : [],\n );\n if (errors.length) {\n throw new AggregateError(errors, \"Failed to close Stillwind analysis services\");\n }\n }\n\n /**\n * Determines whether a captured operation can still publish its result.\n *\n * @param revision - Change counter captured when the operation was queued.\n * @param signal - Optional request cancellation, which takes precedence over staleness.\n * @returns The discard status, or undefined while the capture remains current.\n */\n #discardReason(revision: number, signal?: AbortSignal): \"cancelled\" | \"stale\" | undefined {\n if (signal?.aborted) {\n return \"cancelled\";\n }\n if (revision !== this.#revision) {\n return \"stale\";\n }\n return undefined;\n }\n\n /**\n * Installs captured buffers, refreshes caches, and retains an editor snapshot after compilation.\n *\n * @param entry - Supported full resolver identity to analyze.\n * @param revision - Change counter associated with the captured documents.\n * @param documents - Independent map of open absolute paths to original text.\n * @returns Findings mapped to original documents. Host failures become incomplete results with error text.\n */\n async #analyzeSnapshot(\n entry: string,\n revision: number,\n documents: ReadonlyMap<string, string>,\n ): Promise<AnalysisResult> {\n const result: AnalysisResult = { entry, revision, status: \"incomplete\", reports: [] };\n try {\n if (this.#closed) {\n throw new Error(\"Analysis project is closed\");\n }\n if (!(await this.#installDocuments(documents, revision))) {\n return result;\n }\n if (isStylesheet(entry)) {\n const stylesheet = await this.#css.stylesheet(entry);\n result.reports = stylesheet.reports;\n result.status = \"complete\";\n this.#editors.set(entry, {\n revision,\n snapshot: stylesheet.snapshot,\n });\n return result;\n }\n if (!this.host.supports?.(entry)) {\n throw new Error(`The ${this.host.constructor.name} host cannot analyze ${entry}`);\n }\n await this.#css.load();\n const loader = this.#css.loader!;\n const session = this.#css.session!;\n const graph = await analyzeModule(\n session,\n () => this.#semanticBackend(),\n entry,\n this.host,\n {\n overlayFiles: documents,\n },\n revision === this.#revision ? this.#compilation : undefined,\n );\n result.graph = structuredClone(graph);\n result.reports = await mapAnalysisReports(\n graph.batches.flatMap((batch) => batch.reports),\n graph.sources,\n (id) => this.host.read(id),\n );\n const editor = new EditorSnapshot(\n graph,\n session,\n loader,\n this.host.config,\n (await this.#css.plugins?.catalog()) ?? [],\n this.#css.plugins,\n );\n result.reports.push(...editor.reports());\n this.#editors.set(entry, {\n revision,\n snapshot: editor,\n });\n result.status = analysisComplete(graph) ? \"complete\" : \"incomplete\";\n } catch (error) {\n result.error = error instanceof Error ? error.message : String(error);\n if (error instanceof Error && \"reports\" in error && Array.isArray(error.reports)) {\n result.reports = error.reports as BindingReport[];\n }\n }\n return result;\n }\n\n /**\n * Installs captured buffers and refreshes caches before work continues.\n *\n * @param documents - Original buffers captured with the supplied revision.\n * @param revision - Revision that owns this queued operation.\n * @param signal - Optional cancellation checked between host operations.\n * @returns Whether the operation can continue with these buffers after cache refresh.\n * @throws If installing buffers or refreshing host or checker caches fails.\n */\n async #installDocuments(\n documents: ReadonlyMap<string, string>,\n revision: number,\n signal?: AbortSignal,\n ): Promise<boolean> {\n await this.host.setDocuments(documents);\n if (this.#discardReason(revision, signal)) {\n return false;\n }\n await this.#resetCaches();\n return !this.#discardReason(revision, signal);\n }\n\n /**\n * Consumes dirty flags and invalidates semantic, CSS, and host caches as requested.\n *\n * @returns Completion of required invalidation, or no work when the project is clean.\n * @throws If semantic or host invalidation fails.\n */\n async #resetCaches(): Promise<void> {\n if (!this.#dirty) {\n return;\n }\n this.#dirty = false;\n if (this.#diskDirty) {\n this.#diskDirty = false;\n await this.#semantics?.invalidate();\n }\n if (this.#cssDirty) {\n this.#cssDirty = false;\n this.#css.invalidate();\n }\n await this.host.invalidate();\n }\n\n /**\n * Lazily selects the custom backend or creates the Node checker with fixed project settings.\n *\n * @returns The owned backend, or undefined when type facts are disabled.\n * @throws If backend creation fails.\n */\n #semanticBackend(): TypeFactsBackend | undefined {\n if (this.host.typeFacts === false) {\n return undefined;\n }\n if (!this.#semantics) {\n const backend = this.#backend?.();\n if (backend) {\n this.#semantics = backend;\n } else {\n this.#facts = new TypeScriptFactsService(this.host.typeFactsEnvironment);\n this.#semantics = this.#facts;\n }\n }\n return this.#semantics;\n }\n}\n\n/**\n * Creates a result that carries no reports or graph after a capture becomes unusable.\n *\n * @param entry - Requested resolver identity.\n * @param revision - Change counter captured when the request was queued.\n * @param status - Reason the capture was discarded.\n * @returns An empty analysis result preserving request identity and revision.\n */\nfunction discardedResult(\n entry: string,\n revision: number,\n status: \"stale\" | \"cancelled\",\n): AnalysisResult {\n return {\n entry,\n revision,\n status,\n reports: [],\n };\n}\n\n/**\n * Checks whether all demanded semantic inputs were available, independently of compiler error reports.\n *\n * @param graph - Observed graph returned by compilation.\n * @returns Whether no ranges are unverified and no dependency is unresolved or unsupported.\n */\nfunction analysisComplete(graph: ModuleAnalysis): boolean {\n return (\n graph.unverified.length === 0 &&\n !graph.dependencies.some(\n (dependency) => dependency.status === \"unresolved\" || dependency.status === \"unsupported\",\n )\n );\n}\n","import {\n NativeProjectSession,\n type BindingOutput,\n type NativeDesignSystemLoader,\n} from \"@stillwind/native\";\n\nimport { cleanModuleId, compileModule, type CompilerHost } from \"../compilation/index.ts\";\nimport type { LoadedCssGraph } from \"../css/css.ts\";\nimport { attachPlugins } from \"../css/plugins/session.ts\";\nimport {\n TypeScriptFactsService,\n resolveTypeFactsEnvironment,\n type TypeFactsEnvironment,\n type TypeScriptFactsStats,\n} from \"../semantics/index.ts\";\n\n/** Versioned source buffer that can replace a filesystem read during editor analysis. */\nexport interface EditorDocument {\n /**\n * Resolver identity of the document. Editor operations remove query and fragment suffixes for\n * ordinary file IDs.\n */\n id: string;\n /**\n * Safe integer, including negative values, that must increase for each update while this\n * document stays open.\n */\n version: number;\n /** Current unsaved document text supplied to source preparation and compilation. */\n source: string;\n}\n\n/**\n * Result of analyzing one document against a captured editor revision, with any previously\n * successful preview.\n */\nexport interface EditorAnalysis {\n /** Copy of the entry buffer captured when analysis started. */\n document: EditorDocument;\n /**\n * Project change counter captured at analysis start. Any document update, close of an open\n * document, or invalidation advances it.\n */\n revision: number;\n /** Observed coverage: the result includes only dependencies demanded by this analysis. */\n coverage: \"observed\";\n /**\n * Success means usable code without compiler errors or deny-level lint. Partial retains an\n * incomplete or rejected result. Stale means the project revision changed. Cancelled means the\n * signal was aborted. Stale and cancelled results omit output.\n */\n status: \"success\" | \"partial\" | \"stale\" | \"cancelled\";\n /**\n * Current compilation output, including reports for partial results when available. Stale or\n * cancelled analysis removes this field.\n */\n output?: BindingOutput;\n /**\n * Caught exception message. Compiler reports returned in collect mode do not populate this field.\n */\n error?: string;\n /**\n * Distinct dependency resolver identities observed by the compilation, in first observation\n * order, including those observed before failure.\n */\n dependencies: string[];\n /**\n * Copy of checker counters when this analysis needed type facts. Omitted when no checker was\n * created.\n */\n checkerStats?: TypeScriptFactsStats;\n /**\n * Successful preview retained for this document when analysis started. Failed, stale, or\n * cancelled attempts do not replace the stored success.\n */\n previousSuccess?: {\n /** Document version that produced the retained preview. */\n version: number;\n /** Project revision captured by the successful analysis. */\n revision: number;\n /** Successful compiler output retained for editor preview. */\n output: BindingOutput;\n };\n}\n\n/** Versioned, unpublished previews. Each request owns its compiler session. */\nexport class EditorProject {\n /**\n * Open unsaved buffers keyed by cleaned resolver identity. Analysis captures a map of these\n * buffers before asynchronous work.\n */\n readonly #documents = new Map<string, EditorDocument>();\n /**\n * Most recent successful output for each cleaned document identity, retained across later\n * unsuccessful attempts.\n */\n readonly #successes = new Map<string, NonNullable<EditorAnalysis[\"previousSuccess\"]>>();\n /**\n * Project change counter used to reject results whose source or dependencies changed during\n * analysis.\n */\n #revision = 0;\n\n /** Filesystem root used to initialize the type-facts service when an analysis needs it. */\n readonly root: string;\n /**\n * Dependency resolver and source metadata operations. Open buffers override its reader during\n * analysis.\n */\n readonly host: CompilerHost;\n /**\n * Factory that must return a completed design-system loader suitable for a new compiler session\n * on every analysis, or a loaded CSS graph whose plugins define dynamic candidates.\n */\n readonly designSystem: () =>\n | NativeDesignSystemLoader\n | Pick<LoadedCssGraph, \"loader\" | \"plugins\">;\n /** Fixed checker settings reused by independent analyses and retained without rereading tsconfig. */\n readonly #typeFactsEnvironment: TypeFactsEnvironment;\n\n /**\n * Creates an editor project without opening documents or creating a checker.\n *\n * @param root - Filesystem project root used for checker resolution.\n * @param host - Source descriptors, dependency resolver, and reader used by analysis.\n * @param designSystem - Factory returning a loaded design system, or a loaded CSS graph with its\n * plugins, for each independent analysis.\n * @param typeFactsEnvironment - Fixed checker settings whose root matches this project. Omission\n * selects an existing root tsconfig or isolated defaults.\n */\n constructor(\n root: string,\n host: CompilerHost,\n designSystem: () => NativeDesignSystemLoader | Pick<LoadedCssGraph, \"loader\" | \"plugins\">,\n typeFactsEnvironment = resolveTypeFactsEnvironment(root),\n ) {\n this.root = root;\n this.host = host;\n this.designSystem = designSystem;\n this.#typeFactsEnvironment = typeFactsEnvironment;\n }\n\n /**\n * Stores an unsaved buffer and advances the project revision.\n *\n * @param document - Buffer with a safe integer version greater than the current version for its\n * cleaned identity. A copy is stored.\n * @throws If the version is not a safe integer or does not increase for an open document.\n */\n update(document: EditorDocument): void {\n const id = cleanModuleId(document.id);\n const previous = this.#documents.get(id);\n if (\n !Number.isSafeInteger(document.version) ||\n (previous && document.version <= previous.version)\n ) {\n throw new Error(\"Editor document versions must increase monotonically\");\n }\n this.#documents.set(id, { ...document, id });\n this.#revision += 1;\n }\n\n /**\n * Removes an open buffer and its retained successful preview.\n *\n * @param id - Document identity, cleaned in the same way as `update`. Removing an open buffer\n * advances the revision. An unknown identity has no effect.\n */\n close(id: string): void {\n id = cleanModuleId(id);\n if (this.#documents.delete(id)) {\n this.#revision += 1;\n }\n this.#successes.delete(id);\n }\n\n /**\n * Advances the revision after disk dependencies or the design system change, making in-progress\n * analysis stale.\n */\n invalidate(): void {\n this.#revision += 1;\n }\n\n /**\n * Compiles an open document with the unsaved buffers captured at analysis start.\n *\n * The analysis owns a new compiler session and closes any checker it creates. Dependency reads\n * prefer captured open buffers. Compiler diagnostics are collected. Other failures become the\n * returned error text. Stale or cancelled work retains neither current output nor a new\n * successful preview.\n *\n * @param id - Identity of an open document. Ordinary query and fragment suffixes are removed.\n * @param signal - Optional cancellation signal checked around asynchronous dependency operations\n * and before returning.\n * @returns A promise for the versioned result, observed dependencies, optional checker counters,\n * and the success retained when analysis started.\n * @throws If the document is not open. Cleanup failures can also reject the promise.\n */\n async analyze(id: string, signal?: AbortSignal): Promise<EditorAnalysis> {\n id = cleanModuleId(id);\n const document = this.#documents.get(id);\n if (!document) {\n throw new Error(`Editor document is not open: ${id}`);\n }\n const revision = this.#revision;\n const overlays = new Map(this.#documents);\n const dependencies = new Set<string>();\n const result: EditorAnalysis = {\n document: { ...document },\n revision,\n coverage: \"observed\",\n status: \"partial\",\n dependencies: [],\n previousSuccess: this.#successes.get(id),\n };\n /**\n * Requires this analysis to retain the captured project revision and an active signal.\n * @throws If cancellation or a newer project revision makes this analysis obsolete.\n */\n const assertActive = () => {\n if (signal?.aborted) {\n throw new Error(\"Editor analysis cancelled\");\n }\n if (revision !== this.#revision) {\n throw new Error(\"Editor analysis superseded\");\n }\n };\n let facts: TypeScriptFactsService | undefined;\n try {\n assertActive();\n const design = this.designSystem();\n const graph =\n \"loader\" in design\n ? design\n : {\n loader: design,\n plugins: undefined,\n };\n const session = new NativeProjectSession(graph.loader, false);\n attachPlugins(session, graph.plugins);\n const output = await compileModule(\n session,\n () => {\n facts ??= new TypeScriptFactsService(this.#typeFactsEnvironment);\n return facts;\n },\n document.source,\n id,\n {\n describe: (dependency) => this.host.describe(dependency),\n resolve: async (...args) => {\n assertActive();\n const resolved = await this.host.resolve(...args);\n assertActive();\n return resolved;\n },\n read: async (dependency) => {\n assertActive();\n const source =\n overlays.get(cleanModuleId(dependency))?.source ?? (await this.host.read(dependency));\n assertActive();\n return source;\n },\n watch: (dependency) => dependencies.add(dependency),\n warn: () => {},\n },\n {\n diagnostics: \"collect\",\n typeFactsInputs: {\n overlayFiles: new Map([...overlays].map(([id, value]) => [id, value.source])),\n },\n },\n );\n assertActive();\n result.output = output;\n const denied = output?.lintFindings.some(\n (finding) => output.lintSettings[finding.rule] === \"deny\",\n );\n if (output?.code != null && output.diagnostics.length === 0 && !denied) {\n result.status = \"success\";\n this.#successes.set(id, {\n version: document.version,\n revision,\n output,\n });\n }\n } catch (error) {\n result.error = error instanceof Error ? error.message : String(error);\n } finally {\n if (facts) {\n result.checkerStats = {\n ...facts.stats,\n };\n }\n facts?.close();\n result.dependencies = [...dependencies];\n }\n if (signal?.aborted || revision !== this.#revision) {\n result.status = signal?.aborted ? \"cancelled\" : \"stale\";\n delete result.output;\n }\n return result;\n }\n}\n","import { readFile, readdir, stat } from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\n\nimport type { PluginDirectoryEntry } from \"@stillwind/config\";\nimport { evaluateModule } from \"@stillwind/config/node\";\n\nimport { defaultPluginExport, type LoadedPlugin, type PluginHost } from \"../css/plugins/host.ts\";\nimport { completePluginPaths } from \"../css/plugins/paths.ts\";\n\n/**\n * Lists disk children for plugin completion and plugin directory reads, following\n * directory symlinks.\n * @param id - Absolute directory to enumerate without loading its scripts.\n * @returns Immediate entries in filesystem order. Broken symlinks are treated as files.\n * @throws If the directory cannot be read.\n */\nexport async function readPluginDirectory(id: string): Promise<PluginDirectoryEntry[]> {\n return Promise.all(\n (await readdir(id, { withFileTypes: true })).map(async (entry) => ({\n name: entry.name,\n directory:\n entry.isDirectory() ||\n (entry.isSymbolicLink() &&\n (await stat(path.join(id, entry.name))\n .then((value) => value.isDirectory())\n .catch(() => false))),\n })),\n );\n}\n\n/**\n * Plugin files evaluated from a relative or absolute `@plugin` path, keyed by entry path. Each entry\n * records the text of its bundled local files, so a load reuses the plugin only while every text is\n * unchanged.\n */\nconst files = new Map<\n string,\n {\n /** Text of each bundled local file when the plugin was evaluated. */\n sources: ReadonlyMap<string, string>;\n /** Files that the evaluation observed, including resolved packages. */\n dependencies: readonly string[];\n /** Plugin that the entry exports by default. */\n plugin: LoadedPlugin;\n }\n>();\n\n/**\n * Loads plugin packages and plugin files with Node module resolution from the stylesheet that\n * contains the `@plugin` statement, and reads files from the filesystem.\n *\n * A package specifier is imported with Node's module cache, so a changed package takes effect only\n * in a new process. A relative or absolute path is bundled with its local imports and evaluated\n * again after any of those files changes.\n */\nexport const nodePluginHost: PluginHost = {\n complete: (prefix, importer, root) =>\n completePluginPaths(prefix, importer, root, {\n read: (id) => readFile(id, \"utf8\"),\n directory: readPluginDirectory,\n }),\n async load(specifier, importer, watch) {\n const resolved = createRequire(importer).resolve(specifier);\n if (!specifier.startsWith(\".\") && !path.isAbsolute(specifier)) {\n return defaultPluginExport(await import(pathToFileURL(resolved).href), specifier);\n }\n let cached = files.get(resolved);\n if (\n !cached ||\n !(await Promise.all(\n [...cached.sources].map(async ([file, text]) =>\n readFile(file, \"utf8\").then(\n (current) => current === text,\n () => false,\n ),\n ),\n ).then((results) => results.every(Boolean)))\n ) {\n const { exported, dependencies, sources } = await evaluateModule(resolved);\n cached = {\n sources,\n dependencies,\n plugin: defaultPluginExport(\n {\n default: exported,\n },\n specifier,\n ),\n };\n files.set(resolved, cached);\n }\n for (const dependency of cached.dependencies) {\n watch(dependency);\n }\n return cached.plugin;\n },\n async resolve(specifier, importer) {\n try {\n return createRequire(importer).resolve(specifier);\n } catch {\n return undefined;\n }\n },\n async read(path) {\n return await readFile(path, \"utf8\");\n },\n list: readPluginDirectory,\n};\n","import path from \"node:path\";\n\nimport { ResolverFactory } from \"oxc-resolver\";\n\n/**\n * Creates a resolver for stylesheet imports. It selects `.css` files, the `style` export\n * condition, and the `style` package field, as CSS tooling resolves packages such as\n * `tw-animate-css`.\n *\n * @returns A new resolver with its own cache.\n */\nexport function stylesheetResolver(): ResolverFactory {\n return new ResolverFactory({\n extensions: [\".css\"],\n conditionNames: [\"style\", \"import\", \"default\"],\n mainFields: [\"style\", \"main\"],\n });\n}\n\n/**\n * Creates a stylesheet package resolver for hosts whose own resolver selects JavaScript entries.\n *\n * @returns A function that resolves a specifier from an importing file to a path, or to\n * undefined when the specifier does not resolve.\n */\nexport function createStylesheetResolver(): (\n specifier: string,\n importer: string,\n) => Promise<string | undefined> {\n const resolver = stylesheetResolver();\n return async (specifier, importer) =>\n (await resolver.async(path.dirname(importer), specifier)).path;\n}\n","import { readFile, stat } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport process from \"node:process\";\nimport { pathToFileURL } from \"node:url\";\n\nimport { captureProjectConfig, type AnalysisProjectConfig } from \"@stillwind/config\";\nimport { resolveProjectConfig } from \"@stillwind/config/node\";\nimport { ResolverFactory } from \"oxc-resolver\";\n\nimport { fileModuleDescriptor } from \"../compilation/index.ts\";\nimport { completePluginPaths, pluginDirectory } from \"../css/plugins/paths.ts\";\nimport { resolveTypeFactsEnvironment } from \"../semantics/index.ts\";\nimport type { AnalysisHost } from \"./analysis/host.ts\";\nimport { nodePluginHost, readPluginDirectory } from \"./plugins.ts\";\nimport { stylesheetResolver } from \"./stylesheets.ts\";\n\n/**\n * Creates a Node analysis host with captured buffers, source providers, and CSS resolution.\n * Custom source resolution takes precedence over identities supplied by the semantic backend.\n *\n * @param config - One evaluated project. Custom source and projection callbacks receive the\n * buffers installed by setDocuments. Prepared inputs bypass custom projection preparation.\n * @param directory - Configuration directory used to resolve a relative project root.\n * @returns An owned host with fixed TypeScript settings. CSS and checker creation remain lazy.\n * @throws If TypeScript settings cannot be selected or the CSS resolver cannot be initialized.\n */\nexport function createFileSystemAnalysisHost(\n config: AnalysisProjectConfig,\n directory: string,\n): AnalysisHost {\n config = captureProjectConfig(config);\n const resolvedConfig = resolveProjectConfig(config, directory);\n const root = resolvedConfig.root!;\n const typeFactsEnvironment = resolveTypeFactsEnvironment(root, resolvedConfig.tsconfig);\n const cssResolver = stylesheetResolver();\n const frameworkResolver = new ResolverFactory({\n extensions: [\".astro\", \".svelte\", \".vue\"],\n conditionNames: [\"import\", \"default\"],\n tsconfig:\n typeFactsEnvironment.project.kind === \"configured\"\n ? {\n configFile: typeFactsEnvironment.project.configPath,\n references: \"auto\",\n }\n : undefined,\n });\n\n let documents: ReadonlyMap<string, string> = new Map();\n let buffers: ReadonlyMap<string, string> = new Map();\n\n /**\n * Normalizes paths for lookup in the captured buffer map.\n *\n * @param id - File path resolved against the process working directory when relative.\n * @returns An absolute path, lowercased on Windows to share keys across case variations.\n */\n const documentKey = (id: string) =>\n process.platform === \"win32\" ? path.resolve(id).toLowerCase() : path.resolve(id);\n\n /**\n * Reads a captured buffer before falling back to the physical file.\n *\n * @param id - File path accepted by the Node filesystem.\n * @returns Captured text when present, otherwise UTF-8 file text.\n * @throws If the required physical file cannot be read.\n */\n const read = (id: string) =>\n Promise.resolve(buffers.get(documentKey(id)) ?? readFile(id, \"utf8\"));\n\n /**\n * Lists a directory with the open buffers inside it, so that an unsaved file appears as an entry.\n *\n * @param id - Absolute directory path.\n * @returns Disk and buffered entries, each listed once.\n * @throws If neither the disk nor the buffers contain the directory.\n */\n const list = async (id: string) => {\n const buffered = pluginDirectory(documents, id, process.platform !== \"win32\");\n const entries = [\n ...(await readPluginDirectory(id).catch((error: unknown) => {\n if (!buffered.length) {\n throw error;\n }\n return [];\n })),\n ...buffered,\n ];\n return [\n ...new Map(\n entries.map((entry) => [\n process.platform === \"win32\" ? entry.name.toLowerCase() : entry.name,\n entry,\n ]),\n ).values(),\n ];\n };\n\n /**\n * Selects script and framework sources eligible for default analysis.\n *\n * @param id - File path tested case-insensitively by extension.\n * @returns Whether the path has a supported extension and is not a TypeScript declaration file.\n */\n const supports = (id: string) =>\n /\\.(?:[cm]?[jt]sx?|vue|svelte|astro)$/i.test(id) && !/\\.d\\.[cm]?ts$/i.test(id);\n\n return {\n root,\n config: resolvedConfig,\n typeFactsResolution: true,\n typeFacts: config.typeFacts,\n typeFactsEnvironment,\n supports: (id) =>\n config.sources?.kind === \"custom\" ? config.sources.supports(id) : supports(id),\n describe: (id) => fileModuleDescriptor(root, id),\n read,\n load: async (id) => {\n const context = { root, documents };\n const input =\n config.sources?.kind === \"custom\"\n ? await config.sources.load(id, context)\n : {\n resolverId: id,\n ...fileModuleDescriptor(root, id),\n document: {\n ...fileModuleDescriptor(root, id).document,\n code: await read(id),\n },\n };\n return !(\"kind\" in input) && config.projection?.kind === \"custom\"\n ? config.projection.prepare(input)\n : input;\n },\n resolve: async (specifier, importer) => {\n if (config.sources?.kind === \"custom\") {\n const id = await config.sources.resolve?.(specifier, importer, { root, documents });\n return id\n ? {\n id,\n }\n : null;\n }\n if (/\\.(?:vue|svelte|astro)$/i.test(specifier)) {\n if (specifier.startsWith(\".\") || path.isAbsolute(specifier)) {\n const id = path.resolve(path.dirname(importer), specifier);\n if (buffers.has(documentKey(id))) {\n return {\n id,\n };\n }\n }\n const id = (await frameworkResolver.async(path.dirname(importer), specifier)).path;\n return id\n ? {\n id,\n }\n : null;\n }\n return null;\n },\n watch: () => {},\n warn: () => {},\n css: {\n resolve: async (specifier, importer) => {\n const result = await cssResolver.async(path.dirname(importer), specifier);\n if (!result.path) {\n throw new Error(`Cannot resolve CSS ${specifier} from ${importer}: ${result.error}`);\n }\n return result.path;\n },\n read,\n documentUri: (id) => pathToFileURL(id).href,\n sourceMapSource: (id) => pathToFileURL(id).href,\n watch: () => {},\n plugins: {\n ...nodePluginHost,\n read,\n /**\n * Resolves a plugin file request, preferring open buffers for a relative or absolute\n * path so that an unsaved plugin file resolves.\n *\n * @param specifier - Package specifier or path.\n * @param importer - Stylesheet that contains the statement.\n * @returns A buffered or existing file, or undefined when the request does not resolve\n * to a file.\n */\n async resolve(specifier, importer) {\n if (specifier.startsWith(\".\") || path.isAbsolute(specifier)) {\n const base = path.resolve(path.dirname(importer), specifier);\n for (const suffix of [\"\", \".js\", \".json\", \"/index.js\"]) {\n const candidate = base + suffix;\n if (buffers.has(documentKey(candidate))) {\n return candidate;\n }\n }\n }\n const resolved = await nodePluginHost.resolve(specifier, importer);\n return resolved &&\n (await stat(resolved)\n .then((value) => value.isFile())\n .catch(() => false))\n ? resolved\n : undefined;\n },\n list,\n complete: (prefix, importer, projectRoot) =>\n completePluginPaths(prefix, importer, projectRoot, {\n read,\n directory: (id) => list(id).catch(() => []),\n }),\n },\n },\n setDocuments: async (next) => {\n documents = next;\n buffers = new Map([...next].map(([id, text]) => [documentKey(id), text]));\n },\n invalidate: async () => {\n cssResolver.clearCache();\n frameworkResolver.clearCache();\n },\n close: async () => {},\n };\n}\n","import path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nimport { captureProjectConfig, type CapturedProjectConfig } from \"@stillwind/config\";\nimport { loadConfiguration } from \"@stillwind/config/node\";\nimport { minimatch } from \"minimatch\";\nimport { glob } from \"tinyglobby\";\n\nimport { sourceKey } from \"../compilation/project.ts\";\nimport { isStylesheet } from \"../css/index.ts\";\nimport type {\n DesignSystemRequest,\n DesignSystemResult,\n EditorRequest,\n EditorResult,\n} from \"../editor/index.ts\";\nimport { sameFile } from \"./analysis/host.ts\";\nimport { AnalysisProject, type AnalysisResult } from \"./analysis/project.ts\";\nimport { createFileSystemAnalysisHost } from \"./filesystem.ts\";\n\n/** A project's configuration and results, retained independently when scopes overlap. */\nexport interface WorkspaceProject {\n /** Evaluated project settings. Relative root and scope globs use configFile's directory and host root. */\n readonly config: CapturedProjectConfig;\n /** Absolute path of the configuration that owns this project. */\n readonly configFile: string;\n /** Owned analysis state. Buffers outside this project's target scope can still be dependencies. */\n readonly analysis: AnalysisProject;\n}\n\n/** Analysis results for one explicitly enumerated target in one project. */\nexport interface WorkspaceResult {\n /** Zero-based index into the workspace's projects array. */\n project: number;\n /** Absolute configuration path used to group this result. */\n config: string;\n /** Captured result whose reports have been filtered to this project's configured scope. */\n result: AnalysisResult;\n}\n\n/**\n * Recognizes a declaration file that a target glob such as `*.ts` selects by accident. Other files\n * that the host cannot analyze stay in scope, so their analysis reports the wrong `files` entry.\n *\n * @param project - Project whose host decides what it can analyze.\n * @param file - Absolute file path.\n * @returns Whether the file is a declaration file that the host cannot analyze.\n */\nfunction skipsDeclaration(project: WorkspaceProject, file: string): boolean {\n return /.d.[cm]?ts$/i.test(file) && !project.analysis.host.supports(file);\n}\n\n/** Owns every project in one evaluated configuration and keeps overlapping scopes independent. */\nexport class AnalysisWorkspace {\n /** Absolute paths with open buffers, including paths outside the configured target globs. */\n readonly #openDocuments = new Set<string>();\n /** Configuration files and imports whose changes require reopening this workspace. */\n readonly #configurationDependencies: readonly string[];\n /** Absolute path evaluated when this workspace opened. Reopen the workspace to apply configuration changes. */\n readonly configFile: string;\n /** Fixed project records in configuration order. Each analysis service owns mutable state. */\n readonly projects: readonly WorkspaceProject[];\n\n /**\n * Retains the evaluated configuration and takes ownership of its initialized projects.\n *\n * @param configFile - Absolute configuration path.\n * @param projects - Successfully opened hosts in configuration order.\n * @param dependencies - Absolute configuration and import paths recorded during evaluation.\n */\n private constructor(\n configFile: string,\n projects: WorkspaceProject[],\n dependencies: readonly string[],\n ) {\n this.configFile = configFile;\n this.projects = projects;\n this.#configurationDependencies = dependencies;\n }\n\n /**\n * Evaluates configuration and opens every project, closing earlier hosts if initialization fails.\n *\n * @param configFile - Trusted configuration path. Relative paths use the process working directory.\n * @returns A workspace that owns its project hosts. Close it when replacing the configuration.\n * @throws If configuration evaluation or project initialization fails.\n */\n static async open(configFile: string): Promise<AnalysisWorkspace> {\n configFile = path.resolve(configFile);\n const { config, dependencies } = await loadConfiguration(configFile);\n const projects: WorkspaceProject[] = [];\n try {\n for (const supplied of config.projects) {\n const project = captureProjectConfig(supplied);\n const host = createFileSystemAnalysisHost(project, path.dirname(configFile));\n projects.push({\n config: project,\n configFile,\n analysis: new AnalysisProject(host),\n });\n }\n return new AnalysisWorkspace(configFile, projects, dependencies);\n } catch (error) {\n await Promise.allSettled(projects.map((project) => project.analysis.close()));\n throw error;\n }\n }\n\n /**\n * Matches target scope independently of whether the source exists on disk.\n *\n * @param project - Project whose root, include globs, and exclusions define membership.\n * @param file - Absolute file path to test.\n * @returns Whether the path matches files without matching excludes, node_modules, or .git. A\n * declaration file that the host cannot analyze is outside the scope.\n * Dependency traversal does not use this filter.\n */\n includes(project: WorkspaceProject, file: string): boolean {\n const name = path.relative(project.analysis.host.root, file).replaceAll(\"\\\\\", \"/\");\n /**\n * Matches this project-relative path, including dotfiles.\n * @param pattern - Include or exclude glob interpreted by minimatch.\n * @returns Whether the normalized path matches the pattern.\n */\n const matches = (pattern: string) =>\n minimatch(name, pattern, {\n dot: true,\n });\n return (\n !skipsDeclaration(project, file) &&\n project.config.files.some(matches) &&\n ![\"**/node_modules/**\", \"**/.git/**\", ...(project.config.exclude ?? [])].some(matches)\n );\n }\n\n /**\n * Checks whether the project lints a stylesheet. Loading the project's CSS graph decides it.\n *\n * @param project - Project whose CSS graph lists its linted stylesheets.\n * @param file - Absolute file path to test.\n * @param editor - When false (the default), requires the original CSS graph to load successfully.\n * When true, retries a failed load with recovered definitions so completion, hover, and colors\n * can still identify stylesheet membership while the CSS is incomplete.\n * @returns Whether the file is the CSS entry or an imported file that the CSS host marks for\n * lint. Returns false for other extensions or when the selected loading mode fails. Ordinary\n * script analysis reports CSS loading failures.\n */\n async lintsStylesheet(project: WorkspaceProject, file: string, editor = false): Promise<boolean> {\n if (!isStylesheet(file)) {\n return false;\n }\n const sources = await project.analysis.stylesheets(editor).catch(() => []);\n return sources.some((source) => sameFile(source, file));\n }\n\n /**\n * Enumerates existing target files independently of dependency traversal.\n *\n * @param project - Project whose files and excludes globs are relative to its host root.\n * @param patterns - Optional additional include globs relative to the same root. An empty list\n * adds no filtering. These patterns cannot expand the configured scope.\n * @param options - Target kinds to add to the configured script targets.\n * @returns Sorted absolute target paths. Unsaved files absent from disk are not enumerated.\n * @throws If filesystem enumeration fails.\n */\n async targets(\n project: WorkspaceProject,\n patterns?: string[],\n options: {\n /** Adds the stylesheets that the project lints, as {@link lintsStylesheet} selects them. */\n stylesheets?: boolean;\n } = {},\n ): Promise<string[]> {\n const filters = patterns?.map((pattern) => {\n if (path.isAbsolute(pattern)) {\n return {\n file: path.normalize(pattern),\n };\n }\n return {\n pattern: pattern.replace(/^(\\.\\/)+/, \"\"),\n };\n });\n const files = (\n await glob(project.config.files, {\n cwd: project.analysis.host.root,\n absolute: true,\n onlyFiles: true,\n dot: true,\n ignore: [\"**/node_modules/**\", \"**/.git/**\", ...(project.config.exclude ?? [])],\n })\n ).filter((file) => !skipsDeclaration(project, file));\n if (options.stylesheets) {\n files.push(...(await project.analysis.stylesheets().catch(() => [])));\n }\n return files\n .filter(\n (file, index) =>\n files.findIndex((other) => sameFile(other, file)) === index &&\n (!filters?.length ||\n filters.some((filter) =>\n filter.file !== undefined\n ? path.normalize(file) === filter.file\n : minimatch(\n path.relative(project.analysis.host.root, file).replaceAll(\"\\\\\", \"/\"),\n filter.pattern!,\n {\n dot: true,\n },\n ),\n )),\n )\n .sort();\n }\n\n /**\n * Answers a question about the design system of each project.\n *\n * @param request - Theme, utility, or variant request.\n * @returns Answers in configuration order.\n * @throws If CSS loading or a plugin fails in any project.\n */\n async designSystem(request: DesignSystemRequest): Promise<\n {\n /** Zero-based index into the configured projects. */\n project: number;\n /** Answer from that project's design system. */\n result: DesignSystemResult;\n }[]\n > {\n const answers = await Promise.all(\n this.projects.map((project) => project.analysis.designSystem(request)),\n );\n return answers.flatMap((result, project) => (result ? [{ project, result }] : []));\n }\n\n /**\n * Keeps editor answers separate when several projects include the same target.\n *\n * @param file - Absolute target path used for independent scope checks.\n * @param request - Operation in the original document's UTF-16 coordinates.\n * @param signal - Optional cancellation forwarded to each project's queued query.\n * @returns Available answers in configuration order, including overlapping project memberships.\n * CSS membership checks allow recovered definitions when the original graph cannot load.\n * Plugin path completion and links also accept CSS files inside a project's root.\n * @throws If a project's editor query fails.\n */\n async query(\n file: string,\n request: EditorRequest,\n signal?: AbortSignal,\n ): Promise<\n {\n /** Zero-based index into the configured projects. */\n project: number;\n /** Absolute configuration path that owns this project. */\n config: string;\n /** Answer tied to the captured original source and design system. */\n result: EditorResult;\n }[]\n > {\n const results: {\n /** Zero-based index into the configured projects. */\n project: number;\n /** Absolute configuration path that owns this project. */\n config: string;\n /** Answer tied to the captured original source and design system. */\n result: EditorResult;\n }[] = [];\n for (const [index, project] of this.projects.entries()) {\n const relative = path.relative(project.analysis.host.root, file);\n const navigation =\n isStylesheet(file) &&\n [\"completion\", \"resolve\", \"links\"].includes(request.kind) &&\n relative !== \"..\" &&\n !relative.startsWith(`..${path.sep}`) &&\n !path.isAbsolute(relative);\n if (\n !this.includes(project, file) &&\n !navigation &&\n !(await this.lintsStylesheet(project, file, true))\n ) {\n continue;\n }\n const result = await project.analysis.query(file, request, signal);\n if (result) {\n results.push({\n project: index,\n config: project.configFile,\n result,\n });\n }\n }\n return results;\n }\n\n /**\n * Updates all hosts because an open file can be a dependency outside their target scope.\n *\n * @param file - File path resolved by each project from the process working directory if relative.\n * @param source - Complete unsaved document text.\n * @param version - Increasing safe integer for the open buffer. Identical repeated updates have no effect.\n * @throws If a project rejects the version. Updates already applied to earlier projects are retained.\n */\n update(file: string, source: string, version: number): void {\n for (const project of this.projects) {\n project.analysis.update(file, source, version);\n }\n this.#openDocuments.add(path.resolve(file));\n }\n\n /**\n * Removes a buffer from every project so later reads use its source provider.\n *\n * @param file - File path resolved in the same way as update. Unknown buffers have no effect.\n */\n closeDocument(file: string): void {\n this.#openDocuments.delete(path.resolve(file));\n for (const project of this.projects) {\n project.analysis.closeDocument(file);\n }\n }\n\n /**\n * Checks whether a change to a file requires a new workspace.\n *\n * @param file - Changed file path.\n * @param reads - Result of `AnalysisProject.reads` for each project, in project order.\n * @returns True for a configuration dependency, and for a tsconfig or package.json that a project\n * read or that lies directly in a project root. Module resolution can read these files without\n * recording them, so the project root is checked as well.\n */\n #reopens(file: string, reads: readonly ReadonlySet<string>[]): boolean {\n if (this.#configurationDependencies.some((dependency) => sameFile(dependency, file))) {\n return true;\n }\n return (\n /(?:^|[/\\\\])(?:tsconfig(?:\\.[^/\\\\]+)?\\.json|package\\.json)$/.test(file) &&\n this.projects.some(\n (project, index) =>\n reads[index].has(sourceKey(file)) ||\n sameFile(path.dirname(path.resolve(file)), project.analysis.host.root),\n )\n );\n }\n\n /**\n * Checks whether the disk content of a file can change a project's analysis.\n *\n * @param index - Project index.\n * @param file - Changed file path.\n * @param reads - Result of `AnalysisProject.reads` for each project, in project order.\n * @returns True when the file has no open buffer and the project read it or its target scope\n * contains it. Scope membership covers a new file that no analysis has read.\n */\n #stale(index: number, file: string, reads: readonly ReadonlySet<string>[]): boolean {\n return (\n ![...this.#openDocuments].some((open) => sameFile(open, file)) &&\n (reads[index].has(sourceKey(file)) || this.includes(this.projects[index], path.resolve(file)))\n );\n }\n\n /**\n * Checks whether file changes can change this workspace's results, without changing any state.\n * Analysis cannot depend on a file that it never read and that lies outside every target scope.\n *\n * @param files - File paths reported by a watch notification. Relative paths use the working\n * directory.\n * @returns Whether `refresh` would request reopening or invalidate a project for these files.\n */\n affects(files: readonly string[]): boolean {\n const reads = this.projects.map((project) => project.analysis.reads());\n return files.some(\n (file) =>\n this.#reopens(file, reads) || this.projects.some((_, i) => this.#stale(i, file, reads)),\n );\n }\n\n /**\n * Checks whether save or watch notifications need a new workspace, and invalidates each project\n * that a change to a closed file can affect.\n *\n * @param files - File paths reported by the notification. Relative paths use the working directory.\n * @returns False when the workspace must reopen, which leaves projects unchanged. Otherwise\n * returns true. This method does not read disk or reopen projects.\n */\n refresh(files: readonly string[]): boolean {\n const reads = this.projects.map((project) => project.analysis.reads());\n if (files.some((file) => this.#reopens(file, reads))) {\n return false;\n }\n for (const [index, project] of this.projects.entries()) {\n if (files.some((file) => this.#stale(index, file, reads))) {\n project.analysis.invalidate();\n }\n }\n return true;\n }\n\n /**\n * Advances every project revision and requests CSS and resolver cache refresh before its next analysis.\n */\n invalidate(): void {\n for (const project of this.projects) {\n project.analysis.invalidate();\n }\n }\n\n /**\n * Analyzes a target separately in every matching project and filters reports to each scope.\n * A project matches a script target in its configured scope and a stylesheet that it lints.\n *\n * @param file - Absolute target path. The file need not exist on disk when an open buffer supplies it.\n * @param signal - Optional cancellation checked by each project's queued analysis.\n * @returns Results in project order, or an empty list when no project includes the target.\n * Dependency information remains available even when its reports lie outside the target scope.\n */\n async analyze(file: string, signal?: AbortSignal): Promise<WorkspaceResult[]> {\n const results: WorkspaceResult[] = [];\n for (const [index, project] of this.projects.entries()) {\n if (this.includes(project, file) || (await this.lintsStylesheet(project, file))) {\n results.push({\n project: index,\n config: project.configFile,\n result: this.scopedResult(project, await project.analysis.analyze(file, signal)),\n });\n }\n }\n return results;\n }\n\n /**\n * Analyzes every selected target, including files unreachable from an application entry, and\n * every stylesheet that a project lints.\n *\n * @param patterns - Optional additional globs relative to each project's root. Empty or omitted\n * filters check every configured target.\n * @returns Scoped results in project order, then sorted target order. Overlapping memberships remain separate.\n * @throws If target enumeration fails. Analysis failures are represented in individual results.\n */\n async lint(patterns?: string[]): Promise<WorkspaceResult[]> {\n const results: WorkspaceResult[] = [];\n for (const [index, project] of this.projects.entries()) {\n const files = await this.targets(project, patterns, { stylesheets: true });\n await project.analysis.prepare(files);\n for (const file of files) {\n results.push({\n project: index,\n config: project.configFile,\n result: this.scopedResult(project, await project.analysis.analyze(file)),\n });\n }\n }\n return results;\n }\n\n /**\n * Prepares targets together in each project that includes them.\n *\n * @param files - Absolute target paths. Files outside a project's target globs are skipped.\n * @returns Completion of preparation. Each target's analysis reports its own source failures.\n */\n async prepare(files: readonly string[]): Promise<void> {\n for (const project of this.projects) {\n await project.analysis.prepare(files.filter((file) => this.includes(project, file)));\n }\n }\n\n /**\n * Keeps dependency context while filtering findings from known sources to the project's target scope.\n *\n * @param project - Project whose host and globs identify owned source documents.\n * @param result - Captured analysis with original document URIs.\n * @returns A copy with filtered reports. Reports for unknown source documents remain available.\n * @throws If a file URI in a report cannot be converted to a path.\n */\n private scopedResult(project: WorkspaceProject, result: AnalysisResult): AnalysisResult {\n return {\n ...result,\n reports: result.reports.filter((report) => {\n const uri = report.primary.location.uri;\n if (uri.startsWith(\"file:\")) {\n const file = fileURLToPath(uri);\n if (project.analysis.host.supports(file)) {\n return this.includes(project, file);\n }\n }\n const source = result.graph?.sources.find((source) => source.document.uri === uri);\n if (!source) {\n return true;\n }\n const file = uri.startsWith(\"file:\") ? fileURLToPath(uri) : source.resolverId;\n return this.includes(project, file);\n }),\n };\n }\n\n /**\n * Closes every project and waits for all cleanup attempts before reporting failures.\n *\n * @returns A promise that resolves after project cleanup.\n * @throws An AggregateError containing all project cleanup failures.\n */\n async close(): Promise<void> {\n const results = await Promise.allSettled(\n this.projects.map((project) => project.analysis.close()),\n );\n const errors = results.flatMap((result) =>\n result.status === \"rejected\" ? [result.reason] : [],\n );\n if (errors.length) {\n throw new AggregateError(errors, \"Failed to close Stillwind analysis hosts\");\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAcA,SAAgB,iBAAiB,MAAc,IAAoB;CACjE,OAAO,SAAS,MAAM,EAAE,CAAC,CAAC,WAAW,MAAM,GAAG;AAChD;;;;;;;;AASA,SAAgB,qBAAqB,MAAc,IAA8B;CAC/E,MAAM,OAAO,cAAc,EAAE;CAC7B,MAAM,EAAE,QAAQ,WAAW,eAAe,IAAI;CAC9C,OAAO;EACL,UAAU,iBAAiB,MAAM,IAAI;EACrC,UAAU;GACR,KAAK,cAAc,IAAI,CAAC,CAAC;GACzB;EACF;EACA,iBAAiB;EACjB,oBAAoB,KAAK,WAAW,MAAM,GAAG;EAC7C;CACF;AACF;;;;;;;;;;ACPA,SAAgB,sBAAsB,MAAc,qBAA8B;CAChF,MAAM,mBA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