@stillwind/host 0.0.0-stage → 0.1.0-rc.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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browser.js","names":[],"sources":["../src/semantics/browser/facts.ts","../src/semantics/browser/program.ts","../src/semantics/browser/service.ts","../src/browser/project.ts"],"sourcesContent":["import type { NativeExportedValue, NativeIdentity } from \"@stillwind/native\";\nimport ts from \"typescript-6\";\n\nimport { CheckerSource } from \"../checker-source.ts\";\n\n/**\n * Visits an AST in parent-first order.\n *\n * @param node - Root of the subtree to traverse.\n * @param callback - Operation invoked for the root and every child node. Exceptions propagate.\n */\nexport function visit(node: ts.Node, callback: (node: ts.Node) => void): void {\n callback(node);\n node.forEachChild((child) => visit(child, callback));\n}\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/**\n * Tests whether a type alias is declared in one of `files`.\n *\n * @param type - Checker type to inspect.\n * @param files - Declaration file names of the macro module.\n * @returns Whether the first declaration of the alias symbol belongs to `files`.\n */\nfunction declaredBy(type: ts.Type, files: ReadonlySet<string>): boolean {\n const file = type.aliasSymbol?.declarations?.[0]?.getSourceFile().fileName;\n return file !== undefined && files.has(file);\n}\n\n/** Types whose values cannot be Stillwind assets. */\nconst primitiveTypeFlags =\n ts.TypeFlags.StringLike |\n ts.TypeFlags.NumberLike |\n ts.TypeFlags.BigIntLike |\n ts.TypeFlags.BooleanLike |\n ts.TypeFlags.EnumLike |\n ts.TypeFlags.ESSymbolLike |\n ts.TypeFlags.Null |\n ts.TypeFlags.Undefined |\n ts.TypeFlags.Void |\n ts.TypeFlags.Never;\n\n/**\n * Decodes a checker type into finite declarations from one registered asset family.\n *\n * @param checker - Checker that owns type and location.\n * @param type - Probed type, including unions of declaration candidates.\n * @param location - AST node used to obtain property types.\n * @param identities - Serialized keys mapped to declarations inserted into this snapshot.\n * @param brands - Checker symbol names registered from asset producers and mapped to their families.\n * @param producers - Producer call types of this snapshot, used to detect object types that may hold\n * a widened asset.\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 */\nexport function decode(\n checker: ts.TypeChecker,\n type: ts.Type,\n location: ts.Node,\n identities: ReadonlyMap<string, NativeIdentity>,\n brands: ReadonlyMap<string, NativeIdentity[\"kind\"]>,\n producers: readonly ts.Type[],\n recognitionOnly: boolean,\n): DecodedType {\n if (type.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) {\n return {\n kind: \"unverified\",\n };\n }\n\n let family: NativeIdentity[\"kind\"] | undefined;\n let recognized = false;\n let valid = true;\n let finite = true;\n\n const values: NativeIdentity[] = [];\n for (const member of type.isUnion() ? type.types : [type]) {\n let kind: NativeIdentity[\"kind\"] | undefined;\n let identityType: ts.Type | undefined;\n for (const property of checker.getPropertiesOfType(member)) {\n if (property.name === \"data-__stillwindStyleIdentity\") {\n kind = \"style\";\n } else if (\n brands.get(property.name) === \"ref\" &&\n checker.getSignaturesOfType(member, ts.SignatureKind.Call).length\n ) {\n kind = \"ref\";\n } else if (\n brands.get(property.name) === \"keyframes\" &&\n checker.getSignaturesOfType(member, ts.SignatureKind.Call).length\n ) {\n kind = \"keyframes\";\n } else if (brands.get(property.name) === \"viewTransition\") {\n const method = checker.getPropertyOfType(member, \"for\");\n if (\n method &&\n checker.getSignaturesOfType(\n checker.getTypeOfSymbolAtLocation(method, location),\n ts.SignatureKind.Call,\n ).length\n ) {\n kind = \"viewTransition\";\n }\n }\n\n if (kind) {\n identityType = checker.getTypeOfSymbolAtLocation(property, location);\n if (kind === \"ref\") {\n const ref = checker.getPropertyOfType(identityType, \"ref\");\n identityType = ref && checker.getTypeOfSymbolAtLocation(ref, location);\n }\n break;\n }\n }\n\n const name = (member.aliasSymbol ?? member.getSymbol())?.name;\n recognized ||=\n !!kind || (!!name && /^Style(?:Result|Ref|Keyframes|ViewTransition)$/.test(name));\n if (!kind || (family && kind !== family)) {\n valid = false;\n continue;\n }\n family = kind;\n if (!identityType) {\n finite = false;\n continue;\n }\n\n for (const candidate of identityType.isUnion() ? identityType.types : [identityType]) {\n const identity = candidate.isStringLiteral() ? identities.get(candidate.value) : undefined;\n if (!identity) {\n finite = false;\n continue;\n }\n if (identity.kind !== kind) {\n valid = false;\n continue;\n }\n values.push(identity);\n }\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\n if (!valid || !family || !values.length) {\n if (recognized) {\n return {\n kind: \"unverified\",\n };\n }\n const members = type.isUnion() ? type.types : [type];\n const macroFiles = new Set(\n producers.flatMap((producer) => {\n const file = producer.aliasSymbol?.declarations?.[0]?.getSourceFile().fileName;\n return file === undefined ? [] : [file];\n }),\n );\n const widened =\n !recognitionOnly &&\n members.some(\n (member) =>\n !(member.flags & primitiveTypeFlags) &&\n !declaredBy(member, macroFiles) &&\n (producers.length === 0 ||\n producers.some((producer) => checker.isTypeAssignableTo(producer, member))),\n );\n return {\n kind: widened ? \"unbranded\" : \"nonAsset\",\n };\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: {\n kind: family,\n candidates: {\n kind: \"finite\",\n values,\n },\n },\n },\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: ts.Diagnostic,\n sourceFile: ts.SourceFile,\n mapping: CheckerSource,\n): boolean {\n if ((diagnostic.code !== 2345 && diagnostic.code !== 2769) || diagnostic.start === undefined) {\n return false;\n }\n const start = diagnostic.start;\n const end = start + (diagnostic.length ?? 0);\n let owner: ts.Node | undefined;\n visit(sourceFile, (node) => {\n if (\n ts.isCallExpression(node) &&\n node.getStart(sourceFile) <= start &&\n node.end >= 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","import { fingerprint, type NativeAssetRecord } from \"@stillwind/native\";\nimport { minimatch } from \"minimatch\";\nimport * as path from \"pathe\";\nimport ts from \"typescript-6\";\n\nimport { TypeFactsError, type SemanticInputs, type TypeFactSource } from \"../backend.ts\";\nimport { checkerId, CheckerSource } from \"../checker-source.ts\";\n\n/**\n * Supplies complete virtual files and TypeScript settings for a browser checker.\n */\nexport interface BrowserCheckerOptions {\n /** Absolute virtual project path. Paths use forward slashes. */\n root: string;\n /** Files include package metadata, declarations, standard libraries, and source documents. */\n files: ReadonlyMap<string, string>;\n /** Selected virtual tsconfig path. False uses isolated defaults. */\n tsconfig?: string | false;\n}\n\n/**\n * Maintains the TypeScript program over a browser workspace's virtual files.\n */\nexport class BrowserProgram {\n /** Root, settings, and dependency files used when preparing checker inputs. */\n readonly #options: BrowserCheckerOptions;\n\n /** Language service reused while snapshots and project versions change. */\n #service?: ts.LanguageService;\n\n /** Current captured inventory with overlays, checker buffers, and helper declarations applied. */\n #files = new Map<string, string>();\n\n /** Per-file change counters exposed as language-service script versions. */\n #versions = new Map<string, number>();\n\n /** Effective TypeScript options from the virtual tsconfig and enforced checker settings. */\n #compilerOptions: ts.CompilerOptions = {};\n\n /** Checker buffers and ambient declaration filenames selected as current project roots. */\n #roots: string[] = [];\n\n /** Advances when file text, roots, or compiler options change. */\n #revision = 0;\n\n /** Serialized compiler options and root filenames, used to detect settings changes. */\n #settings = \"\";\n\n /**\n * Creates a checker without loading its sources.\n *\n * After changing dependency files, call invalidate before preparing another program.\n * Do not change files while a query is running.\n *\n * @param options - Virtual root, complete dependency files, and optional tsconfig selection.\n */\n constructor(options: BrowserCheckerOptions) {\n this.#options = options;\n }\n\n /**\n * Builds checker buffers and updates the language service from the supplied files.\n *\n * @param sources - Sources with original UTF-8 probes and any framework checker buffers.\n * @param assets - Declarations grouped by module ID, used to mark producer calls.\n * @param inputs - Overlays and ambient declarations applied over the configured files.\n * @returns The updated program and mappings between original sources and checker buffers.\n * @throws If a probe cannot be mapped, tsconfig is invalid, or the language service has no program.\n */\n prepare(\n sources: readonly TypeFactSource[],\n assets: ReadonlyMap<string, readonly NativeAssetRecord[]>,\n inputs: SemanticInputs,\n ): { program: ts.Program; mappings: CheckerSource[] } {\n const files = new Map([\n ...this.#options.files,\n ...(inputs.overlayFiles ?? []),\n ...(inputs.ambientDeclarations ?? []),\n ]);\n const mappings: CheckerSource[] = [];\n const ids = new Map(sources.map((source) => [source.resolverId, checkerId(source)]));\n const extraRoots = new Set<string>(inputs.ambientDeclarations?.keys());\n for (const source of sources) {\n if (source.kind === \"projected\" && source.projection.checkerGlobals) {\n const id = path.join(\n this.#options.root,\n `.stillwind-globals-${fingerprint(source.projection.checkerGlobals)}.d.ts`,\n );\n files.set(id, source.projection.checkerGlobals);\n extraRoots.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 mapping = new CheckerSource(\n source,\n buffer,\n index,\n assets.get(source.moduleId) ?? [],\n ids,\n );\n files.set(mapping.id, mapping.text);\n mappings.push(mapping);\n if (mapping.helperModule) {\n files.set(mapping.helperModule.id, mapping.helperModule.text);\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 for (const id of source.checkerTypes ?? []) {\n extraRoots.add(id);\n }\n }\n const structureChanged =\n files.size !== this.#files.size || [...files.keys()].some((id) => !this.#files.has(id));\n const resolutionChanged =\n structureChanged ||\n [...files].some(([id, text]) => /\\.json$/i.test(id) && this.#files.get(id) !== text);\n let changed = structureChanged;\n for (const [id, text] of files) {\n if (this.#files.get(id) !== text) {\n changed = true;\n this.#versions.set(id, (this.#versions.get(id) ?? 0) + 1);\n }\n }\n this.#files = files;\n const configPath = path.resolve(this.#options.root, this.#options.tsconfig || \"tsconfig.json\");\n let configured: ts.ParsedCommandLine | undefined;\n if (this.#options.tsconfig !== false && files.has(configPath)) {\n const config = ts.readConfigFile(configPath, (id) => files.get(id));\n if (config.error) {\n throw new Error(ts.flattenDiagnosticMessageText(config.error.messageText, \"\\n\"));\n }\n configured = ts.parseJsonConfigFileContent(\n config.config,\n {\n useCaseSensitiveFileNames: true,\n fileExists: (id) => files.has(id),\n readFile: (id) => files.get(id),\n readDirectory: (directory, extensions, excludes, includes, depth) =>\n [...files.keys()].filter(\n (id) =>\n id.startsWith(directory + \"/\") &&\n (!extensions || extensions.some((ext) => id.endsWith(ext))) &&\n (depth === undefined ||\n path.relative(directory, id).split(\"/\").length - 1 <= depth) &&\n (includes ?? [\"**/*\"]).some((pattern) => matchesFile(directory, id, pattern)) &&\n !(excludes ?? []).some((pattern) => matchesFile(directory, id, pattern)),\n ),\n },\n path.dirname(configPath),\n );\n const error = configured.errors.find((item) => item.code !== 18003);\n if (error) {\n throw new Error(ts.flattenDiagnosticMessageText(error.messageText, \"\\n\"));\n }\n } else if (typeof this.#options.tsconfig === \"string\") {\n throw new Error(`TypeScript configuration does not exist: ${configPath}`);\n }\n this.#compilerOptions = {\n target: ts.ScriptTarget.ESNext,\n module: ts.ModuleKind.ESNext,\n moduleResolution: ts.ModuleResolutionKind.Bundler,\n jsx: ts.JsxEmit.Preserve,\n strict: true,\n types: [],\n ...configured?.options,\n allowJs: true,\n checkJs: true,\n allowImportingTsExtensions: true,\n noEmit: true,\n skipLibCheck: true,\n };\n this.#roots = [\n ...new Set([\n ...mappings.map((mapping) => mapping.id),\n ...extraRoots,\n ...(configured?.fileNames.filter((id) => /\\.d\\.[cm]?ts$/.test(id)) ?? []),\n ]),\n ];\n const settings = JSON.stringify([this.#compilerOptions, this.#roots]);\n if (changed || settings !== this.#settings) {\n this.#revision++;\n }\n this.#settings = settings;\n if (resolutionChanged) {\n this.invalidate();\n }\n if (!this.#service) {\n /**\n * Infers a virtual directory from the captured files beneath it.\n * @param directory - Absolute virtual directory with an optional trailing slash.\n * @returns Whether at least one file key starts with the directory prefix.\n */\n const directoryExists = (directory: string) =>\n [...this.#files.keys()].some((id) => id.startsWith(directory.replace(/\\/$/, \"\") + \"/\"));\n this.#service = ts.createLanguageService({\n getCompilationSettings: () => this.#compilerOptions,\n getScriptFileNames: () => this.#roots,\n getScriptVersion: (id) => String(this.#versions.get(id) ?? 0),\n getProjectVersion: () => String(this.#revision),\n getScriptSnapshot: (id) => {\n const text = this.#files.get(id);\n return text === undefined ? undefined : ts.ScriptSnapshot.fromString(text);\n },\n getCurrentDirectory: () => this.#options.root,\n getDefaultLibFileName: () => \"/node_modules/typescript/lib/lib.esnext.full.d.ts\",\n fileExists: (id) => this.#files.has(id),\n readFile: (id) => this.#files.get(id),\n directoryExists,\n getDirectories: (directory) => [\n ...new Set(\n [...this.#files.keys()]\n .filter((id) => id.startsWith(directory + \"/\"))\n .map((id) => id.slice(directory.length + 1).split(\"/\", 1)[0]),\n ),\n ],\n useCaseSensitiveFileNames: () => true,\n });\n }\n\n const program = this.#service.getProgram();\n if (!program) {\n throw new Error(\"Browser checker could not open the Stillwind project\");\n }\n\n return {\n program,\n mappings,\n };\n }\n\n /**\n * Discards the language service after file or configuration changes.\n */\n invalidate(): void {\n this.#service?.dispose();\n this.#service = undefined;\n }\n}\n\n/**\n * Applies tsconfig file and directory patterns to paths in the virtual filesystem.\n *\n * @param directory - Absolute virtual base directory.\n * @param id - Absolute virtual file path.\n * @param pattern - Absolute or directory-relative glob. A plain directory name expands to its descendants.\n * @returns Whether the relative path matches, including dot-prefixed segments.\n */\nfunction matchesFile(directory: string, id: string, pattern: string): boolean {\n const name = path.relative(directory, id);\n const glob = path.isAbsolute(pattern) ? path.relative(directory, pattern) : pattern;\n const expanded = !/[?*]/.test(glob) && !/\\.[^/]+$/.test(glob) ? `${glob}/**/*` : glob;\n return minimatch(name, expanded, { dot: true });\n}\n","import type { NativeAssetRecord, NativeIdentity, NativeTypeFact } from \"@stillwind/native\";\nimport ts from \"typescript-6\";\n\nimport {\n TypeFactsError,\n type AvailableFacts,\n type SemanticInputs,\n type TypeFactsBackend,\n type TypeFactSource,\n type UnverifiedRange,\n} from \"../backend.ts\";\nimport { checkerId, CheckerSource, withRequestedProbes } from \"../checker-source.ts\";\nimport { decode, producerArgumentDiagnostic, visit } from \"./facts.ts\";\nimport { BrowserProgram, type BrowserCheckerOptions } from \"./program.ts\";\n\n/**\n * Answers declaration probes with the browser TypeScript checker.\n */\nexport class BrowserTypeFactsService implements TypeFactsBackend {\n /** Program and language service owned by this backend. */\n readonly #program: BrowserProgram;\n\n /** Prevents preparing further requests after cleanup. */\n #closed = false;\n\n /** Project inputs retained until {@link setProjectSources} replaces them. Queries select a subset. */\n #installed?: {\n sources: readonly TypeFactSource[];\n assets: ReadonlyMap<string, readonly NativeAssetRecord[]>;\n inputs: SemanticInputs;\n };\n\n /** Program and source mappings prepared from the installed project inputs. */\n #prepared?: {\n program: ts.Program;\n mappings: CheckerSource[];\n };\n\n /**\n * Creates a service without loading its sources.\n *\n * @param options - Virtual files and fixed TypeScript settings. Call invalidate after changing dependency files.\n */\n constructor(options: BrowserCheckerOptions) {\n this.#program = new BrowserProgram(options);\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 NativeAssetRecord[]>,\n inputs: SemanticInputs = {},\n ): void {\n this.#installed = {\n sources,\n assets,\n inputs,\n };\n this.#prepared = undefined;\n }\n\n /**\n * Collects finite declaration candidates and rejects unavailable required queries.\n *\n * @param sources - Prepared sources with probes in original UTF-8 coordinates.\n * @param assets - Declaration records grouped by compiler module identity.\n * @param inputs - Overlays and ambient declarations for an independent query. Omission supplies none.\n * An installed project uses the inputs supplied by {@link setProjectSources}.\n * @returns Facts keyed by compiler identity, deduplicated by original range across checker buffers.\n * Known non-asset types produce null facts. Unresolved recognition-only probes produce no fact.\n * @throws If the service is closed, preparation fails, or checker contracts cannot be verified.\n */\n collect(\n sources: readonly TypeFactSource[],\n assets: ReadonlyMap<string, readonly NativeAssetRecord[]>,\n inputs?: SemanticInputs,\n ): Map<string, NativeTypeFact[]> {\n return this.#collect(sources, assets, inputs, false).facts;\n }\n\n /**\n * Collects usable facts while retaining unavailable original ranges for analysis.\n *\n * @param sources - Prepared sources with original UTF-8 probes and checker correspondences.\n * @param assets - Declaration records grouped by compiler module identity.\n * @param inputs - Overlays and ambient declarations for an independent query. Omission supplies none.\n * An installed project uses the inputs supplied by {@link setProjectSources}.\n * @returns Verified facts and unverified ranges without discarding other expressions' answers.\n * @throws If the service is closed, preparation fails, or checker results conflict for one original range.\n */\n collectAvailable(\n sources: readonly TypeFactSource[],\n assets: ReadonlyMap<string, readonly NativeAssetRecord[]>,\n inputs?: SemanticInputs,\n ): AvailableFacts {\n return this.#collect(sources, assets, inputs, true);\n }\n\n /**\n * Resolves authored imports and exports from module symbols in the virtual checker.\n * When project sources are installed, resolves imports for the whole installed project.\n *\n * @param sources - Prepared sources whose checker buffers contain module requests.\n * @param assets - Declaration records used to prepare checker identities and helpers.\n * @param inputs - Overlays and ambient declarations for independent resolution. Omission supplies none.\n * An installed project uses the inputs supplied by {@link setProjectSources}.\n * @returns Maps from importing resolver identity to specifier and resolved identity. Unmatched requests are omitted.\n * @throws If the service is closed or checker preparation fails.\n */\n resolveModules(\n sources: readonly TypeFactSource[],\n assets: ReadonlyMap<string, readonly NativeAssetRecord[]>,\n inputs?: SemanticInputs,\n ): Map<string, Map<string, string>> {\n const { program, mappings } = this.#prepare(sources, assets, inputs);\n\n const result = new Map<string, Map<string, string>>();\n const checker = program.getTypeChecker();\n for (const mapping of mappings) {\n const file = program.getSourceFile(mapping.id);\n if (!file) {\n continue;\n }\n\n const resolutions = new Map<string, string>();\n result.set(mapping.source.resolverId, resolutions);\n visit(file, (node) => {\n if (\n !(ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) ||\n !node.moduleSpecifier ||\n !ts.isStringLiteral(node.moduleSpecifier)\n ) {\n return;\n }\n const symbol = checker.getSymbolAtLocation(node.moduleSpecifier);\n const declaration = symbol?.declarations?.find(\n (item) => ts.isSourceFile(item) || item.getSourceFile().isDeclarationFile,\n );\n if (declaration) {\n const filename = declaration.getSourceFile().fileName;\n resolutions.set(\n mapping.moduleSpecifiers.get(\n `${node.moduleSpecifier.getStart(file)}:${node.moduleSpecifier.end}`,\n ) ?? node.moduleSpecifier.text,\n (this.#installed?.sources ?? sources).find((source) => checkerId(source) === filename)\n ?.resolverId ?? filename,\n );\n }\n });\n }\n\n return result;\n }\n\n /**\n * Discards the language service after file or configuration changes.\n */\n invalidate(): void {\n this.#program.invalidate();\n this.#prepared = undefined;\n }\n\n /**\n * Releases the checker. Subsequent queries reject.\n */\n close(): void {\n this.#closed = true;\n this.invalidate();\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 * @returns The current checker program and source mappings. Successful project preparation is cached.\n * @throws If the service is closed or the requested sources cannot be prepared.\n */\n #prepare(\n sources: readonly TypeFactSource[],\n assets: ReadonlyMap<string, readonly NativeAssetRecord[]>,\n inputs: SemanticInputs = {},\n ): { program: ts.Program; mappings: CheckerSource[] } {\n if (this.#closed) {\n throw new Error(\"Browser checker is closed\");\n }\n\n if (this.#prepared) {\n return this.#prepared;\n }\n if (this.#installed) {\n try {\n this.#prepared = this.#program.prepare(\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.#program.prepare(sources, assets, inputs);\n }\n\n /**\n * Decodes current checker expressions and enforces finite declaration identities for probes.\n *\n * @param sources - Prepared sources with validated checker correspondences.\n * @param assets - Native declarations keyed by compiler identity.\n * @param inputs - Overlays and ambient declarations for this snapshot.\n * @param available - Whether unavailable queries are recorded instead of thrown.\n * @returns Facts grouped by compiler identity and original UTF-8 ranges that could not be verified.\n * @throws If preparation fails, checker results conflict, or strict mode encounters unavailable facts.\n */\n #collect(\n sources: readonly TypeFactSource[],\n assets: ReadonlyMap<string, readonly NativeAssetRecord[]>,\n inputs: SemanticInputs | undefined,\n available: boolean,\n ): AvailableFacts {\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 prepared = this.#prepare(sources, assets, inputs);\n const { program } = prepared;\n const selected = new Set(sources.map((source) => source.resolverId));\n const mappings = prepared.mappings.filter((mapping) => selected.has(mapping.source.resolverId));\n const identities = new Map(mappings.flatMap((mapping) => [...mapping.identities]));\n const checker = program.getTypeChecker();\n const facts = new Map<string, NativeTypeFact[]>();\n const unverified: UnverifiedRange[] = [];\n const brands = new Map<string, NativeIdentity[\"kind\"]>();\n const producers: ts.Type[] = [];\n for (const mapping of mappings) {\n const file = program.getSourceFile(mapping.id);\n if (!file) {\n continue;\n }\n visit(file, (node) => {\n const kind = mapping.producers.get(`${node.getStart(file)}:${node.end}`);\n if (!kind) {\n return;\n }\n producers.push(checker.getTypeAtLocation(node));\n if (kind === \"style\") {\n return;\n }\n const prefix = {\n ref: \"refIdentity\",\n keyframes: \"keyframesIdentity\",\n viewTransition: \"viewTransitionIdentity\",\n }[kind];\n const property = checker\n .getPropertiesOfType(checker.getTypeAtLocation(node))\n .find((item) => item.name.startsWith(`__@${prefix}@`));\n if (property) {\n brands.set(property.name, kind);\n }\n });\n }\n /**\n * Records an unverifiable use when partial facts are allowed.\n *\n * @param error - Failure with the original module identity and UTF-8 range, when available.\n * @throws The supplied error when this collection requires complete facts.\n */\n const unavailable = (error: TypeFactsError) => {\n if (!available) {\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 for (const mapping of mappings) {\n const file = program.getSourceFile(mapping.id);\n if (!file) {\n throw new Error(`Browser checker omitted ${mapping.id}`);\n }\n const diagnostic = [\n ...program.getSyntacticDiagnostics(file),\n ...program.getSemanticDiagnostics(file),\n ].find(\n (item) =>\n !producerArgumentDiagnostic(item, file, mapping) &&\n /stillwind\\/v1:|StyleResult|StyleRef|StyleKeyframes|StyleViewTransition|__stillwindDeclarationIdentity|data-__stillwindStyleIdentity/.test(\n ts.flattenDiagnosticMessageText(item.messageText, \"\\n\"),\n ),\n );\n if (diagnostic) {\n const start = mapping.originalOffset(diagnostic.start ?? 0) ?? undefined;\n const end =\n mapping.originalOffset((diagnostic.start ?? 0) + (diagnostic.length ?? 0), true) ??\n undefined;\n unavailable(\n new TypeFactsError(\n mapping.source.moduleId,\n start,\n end,\n \"assignment\",\n `TS${diagnostic.code}: ${ts.flattenDiagnosticMessageText(diagnostic.messageText, \"\\n\")} Preserve declaration candidates with an explicit union or a generic parameter.`,\n ),\n );\n }\n const matched = new Set<string>();\n const values = facts.get(mapping.source.moduleId) ?? [];\n visit(file, (node) => {\n if (!ts.isExpression(node)) {\n return;\n }\n const key = `${node.getStart(file)}:${node.end}`;\n const probe = mapping.probes.get(key);\n if (!probe) {\n return;\n }\n matched.add(key);\n const type = checker.getTypeAtLocation(node);\n const decoded = decode(\n checker,\n type,\n node,\n identities,\n brands,\n producers,\n probe.recognitionOnly ?? false,\n );\n if (\n decoded.kind === \"asset\" ||\n decoded.kind === \"nonAsset\" ||\n (decoded.kind === \"unbranded\" && probe.recognitionOnly)\n ) {\n const value = decoded.kind === \"asset\" ? decoded.value : null;\n const existing = values.find(\n (item) => item.start === probe.start && item.end === probe.end,\n );\n if (existing && JSON.stringify(existing.value) !== JSON.stringify(value)) {\n throw new TypeFactsError(\n mapping.source.moduleId,\n probe.start,\n probe.end,\n \"checker\",\n \"Ambiguous checker results for this original expression\",\n );\n }\n if (!existing) {\n values.push({\n ...probe,\n value,\n });\n }\n } else if (!probe.recognitionOnly) {\n unavailable(\n 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 );\n }\n });\n for (const [key, probe] of mapping.probes) {\n if (!matched.has(key)) {\n unavailable(\n 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 );\n }\n }\n facts.set(mapping.source.moduleId, values);\n }\n return {\n facts,\n unverified,\n };\n }\n}\n","import { captureProjectConfig, type AnalysisProjectConfig } from \"@stillwind/config\";\nimport {\n NativeProjectSession,\n type BindingRejectedIdentifier,\n type BindingReport,\n type NativeCssResource,\n type NativeDesignSystemLoader,\n} from \"@stillwind/native\";\nimport { dirname, relative, resolve } from \"pathe\";\n\nimport { analyzeModule } from \"../compilation/compiler.ts\";\nimport type { CompilerHost } from \"../compilation/host.ts\";\nimport { fileSourceKind } from \"../compilation/module-source.ts\";\nimport { CompilationProject } from \"../compilation/project.ts\";\nimport type { ModuleAnalysis } from \"../compilation/request.ts\";\nimport { finalizeCss } from \"../css/banners.ts\";\nimport {\n isStylesheet,\n loadCssGraph,\n loadEditorCssGraph,\n type CssHost,\n type EditorCssGraph,\n} from \"../css/css.ts\";\nimport type { PluginHost } from \"../css/plugins/host.ts\";\nimport { completePluginPaths, pluginDirectory, queryPluginPaths } from \"../css/plugins/paths.ts\";\nimport type { PluginRuntime } from \"../css/plugins/runtime.ts\";\nimport { attachPlugins, prepareSourcePlugins } from \"../css/plugins/session.ts\";\nimport { EditorSnapshot, type EditorRequest, type EditorResult } from \"../editor/index.ts\";\nimport { compilerOptions, cssEntrypoint } from \"../project/options.ts\";\nimport { StylesheetEditor } from \"../project/stylesheet-editor.ts\";\nimport { BrowserTypeFactsService } from \"../semantics/browser/service.ts\";\nimport { resolveVirtualModule } from \"./resolution.ts\";\n\n/** Files and evaluated configuration captured for one browser project. */\nexport interface BrowserProjectOptions {\n /** Absolute virtual directory used for relative compiler identities. */\n root: string;\n /** Evaluated project settings. Paths use the virtual workspace. */\n config: AnalysisProjectConfig;\n /** Original sources, package files, and declarations captured for this project revision. */\n files: ReadonlyMap<string, string>;\n /**\n * Maps an absolute virtual path to its original workspace URI.\n * @param id - Decoded virtual source path.\n * @returns URI used for diagnostic locations and source-map names.\n */\n documentUri?(id: string): string;\n /**\n * Loads plugin packages and plugin files for `@plugin` statements. Omission limits the project\n * to the plugins of its configuration.\n */\n plugins?: PluginHost;\n}\n\n/** Rendered browser CSS and the naming fallbacks observed during its assembly. */\nexport interface BrowserStylesheetOutput {\n /** CSS after local resources are embedded. */\n css: string;\n /** Generator rejection records without source locations, in request order. */\n rejectedNames: BindingRejectedIdentifier[];\n}\n\n/** One module's carrier and its ordered template fragments. */\nexport interface BrowserModuleCss extends BrowserStylesheetOutput {\n /** Fragments in stylesheet occurrence order, with their content fingerprints. */\n parts: {\n /** Content fingerprint supplied by the native emission plan. */\n key: string;\n /** Preserved notices required by this fragment. */\n banners?: readonly string[];\n /** Fragment CSS including enclosing conditions, after local resources are embedded. */\n css: string;\n }[];\n}\n\ntype ReadonlyData<T> = T extends object\n ? {\n readonly [K in keyof T]: ReadonlyData<T[K]>;\n }\n : T;\n\n/** Analysis records shared by cache reads. Use structuredClone() to obtain editable records. */\nexport type BrowserModuleAnalysis = ReadonlyData<ModuleAnalysis>;\n\n/** Owns the design system, semantic checker, and compiler artifacts for one captured inventory. */\nexport class BrowserProject {\n /** Editor views retained for each analyzed entry in the captured inventory. */\n readonly #editors = new Map<string, EditorSnapshot | StylesheetEditor>();\n /** Owned configuration records and callbacks fixed for this project's lifetime. */\n readonly #options: BrowserProjectOptions;\n /** Copy of the original inventory used by source, CSS, and checker reads. */\n readonly #files: Map<string, string>;\n /** Owned checker for the captured virtual inventory. */\n readonly #facts: BrowserTypeFactsService;\n /** Prepared sources shared by analyses of different entries. */\n readonly #compilation = new CompilationProject();\n /** Virtual paths read by CSS or plugins. Changes to these files reload CSS. */\n readonly #cssDependencies = new Set<string>();\n /** Lazily loaded CSS graph shared by all entry analyses. */\n #loader?: NativeDesignSystemLoader;\n /** Original or recovered CSS graph retained for queries. Sorting and fixes require original CSS. */\n #editorCss?: EditorCssGraph;\n /** Native session retaining successful compiler artifacts across entry analyses. */\n #session?: NativeProjectSession;\n /** Serializes analyses and permits subsequent work after a failure. */\n #queue: Promise<unknown> = Promise.resolve();\n /** Prevents new analyses and suppresses editor answers after closure starts. */\n #closed = false;\n /** Resource placeholders supplied by the loaded CSS graph. */\n #resources: NativeCssResource[] = [];\n /** Paths that the loaded CSS graph marks for stylesheet lint, in load order. */\n #lintSources: string[] = [];\n /** Plugin runtime of the retained loader. */\n #plugins?: PluginRuntime;\n /** Analysis graphs keyed by full entry identity, invalidated when native artifacts are removed. */\n readonly #cache = new Map<string, BrowserModuleAnalysis>();\n\n /**\n * Copies the files and configuration without loading CSS or compiling sources.\n *\n * @param options - Captured files and configuration. Use replaceFiles between transactions to change sources.\n */\n constructor(options: BrowserProjectOptions) {\n this.#options = {\n ...options,\n config: captureProjectConfig(options.config),\n };\n this.#files = new Map(options.files);\n this.#facts = new BrowserTypeFactsService({\n root: options.root,\n files: this.#files,\n tsconfig: options.config.tsconfig,\n });\n }\n\n /**\n * Selects the document identity shared by compiler reports and CSS maps.\n *\n * @param file - Absolute path in the virtual filesystem.\n * @returns The configured URI, or the path prefixed with `file://`.\n */\n #documentUri(file: string): string {\n return this.#options.documentUri?.(file) ?? `file://${file}`;\n }\n\n /**\n * Reads captured text without accessing the physical filesystem.\n *\n * @param file - Exact path key in the virtual filesystem.\n * @returns The text currently stored under that key.\n * @throws If the virtual file is absent.\n */\n async #read(file: string): Promise<string> {\n const text = this.#files.get(file);\n if (text === undefined) {\n throw new Error(`Virtual file does not exist: ${file}`);\n }\n return text;\n }\n\n /**\n * Loads the configured CSS graph once and creates the native session that uses it.\n *\n * @returns The retained loader.\n * @throws If resolving, reading, or loading the CSS graph fails.\n */\n async #designSystem(): Promise<NativeDesignSystemLoader> {\n if (!this.#loader) {\n const { config, root } = this.#options;\n const loaded = await loadCssGraph(\n resolve(root, cssEntrypoint(config)),\n compilerOptions(config),\n this.#cssHost(),\n undefined,\n undefined,\n {\n plugins: config.plugins,\n tailwind: config.tailwind,\n important: config.important,\n root,\n },\n );\n this.#loader = loaded.loader;\n this.#resources = loaded.resources;\n this.#lintSources = loaded.lintSources;\n this.#plugins = loaded.plugins;\n this.#session = new NativeProjectSession(this.#loader, false, \"development\", config.naming);\n attachPlugins(this.#session, this.#plugins);\n }\n return this.#loader;\n }\n\n /**\n * Creates CSS loader operations backed by this project's captured virtual inventory.\n *\n * @returns A host that resolves style imports and uses document URIs for diagnostics and maps.\n * Its reads reject missing files, and its resolver rejects unresolved imports. Observed paths\n * determine when replacement files reload CSS.\n */\n #cssHost(): CssHost {\n /**\n * Selects the document identity of a virtual stylesheet.\n *\n * @param file - Absolute virtual path.\n * @returns The configured document URI.\n */\n const uri = (file: string) => this.#documentUri(file);\n return {\n resolve: async (specifier, importer) => {\n const resolved = resolveVirtualModule(this.#files, specifier, importer, \"style\");\n if (!resolved) {\n throw new Error(`Cannot resolve CSS ${specifier} from ${importer}`);\n }\n return resolved;\n },\n read: (file) => this.#read(file),\n documentUri: uri,\n sourceMapSource: uri,\n watch: (id) => {\n this.#cssDependencies.add(id);\n },\n plugins: {\n load: async (specifier, importer, watch) => {\n if (!this.#options.plugins) {\n throw new Error(`This host cannot load plugin ${specifier}`);\n }\n return this.#options.plugins.load(specifier, importer, watch);\n },\n resolve: async (specifier, importer) =>\n resolveVirtualModule(this.#files, specifier, importer) ??\n (await this.#options.plugins?.resolve(specifier, importer)),\n read: async (id) =>\n this.#files.get(id) ??\n (this.#options.plugins ? this.#options.plugins.read(id) : this.#read(id)),\n list: async (id) => {\n const entries = pluginDirectory(this.#files, id);\n if (!entries.length) {\n if (this.#options.plugins?.list) {\n return this.#options.plugins.list(id);\n }\n throw new Error(`Directory ${id} does not exist`);\n }\n return entries;\n },\n },\n };\n }\n\n /**\n * Reports stylesheet lint for the CSS files that this project lints.\n *\n * @returns Linted virtual paths in load order, and the reports whose primary location is one of\n * them.\n * @throws If the project is closed or the CSS graph cannot be loaded.\n */\n stylesheetLint(): Promise<{\n /** Virtual paths of the CSS entry and the imported files marked for lint. */\n sources: string[];\n /** Stylesheet lint reports with original document locations. */\n reports: BindingReport[];\n }> {\n if (this.#closed) {\n return Promise.reject(new Error(\"Browser project is closed\"));\n }\n const task = this.#queue.then(async () => {\n const loader = await this.#designSystem();\n return {\n sources: [...this.#lintSources],\n reports: loader.stylesheetReports(),\n };\n });\n this.#queue = task.catch(() => {});\n return task;\n }\n\n /**\n * Creates compiler operations that read the current virtual files.\n *\n * @param onModule - Optional callback for each module the compiler attempts to analyze.\n * @returns A host using this project's configuration, files, and custom source provider.\n * Its reads reject missing files. Its resolver returns null for unresolved requests.\n */\n #host(onModule?: (moduleId: string) => void): CompilerHost {\n const { config, root } = this.#options;\n const uri = (file: string) => this.#documentUri(file);\n const read = (file: string) => this.#read(file);\n /**\n * Describes a virtual file for compilation and checker preparation.\n *\n * @param file - Absolute virtual path whose extension selects its source format.\n * @returns Metadata with project-relative module and projection names and an absolute checker path.\n */\n const descriptor = (file: string) => ({\n moduleId: relative(root, file),\n checkerFileName: file,\n projectionFileName: relative(root, file),\n document: {\n uri: uri(file),\n format: fileSourceKind(file).format,\n },\n syntax: fileSourceKind(file).syntax,\n });\n\n return {\n onModule,\n describe: descriptor,\n read,\n typeFactsResolution: config.typeFacts !== false,\n supports: (file) =>\n config.sources?.kind === \"custom\"\n ? config.sources.supports(file)\n : /\\.[cm]?[jt]sx?$/.test(file) && !/\\.d\\.[cm]?ts$/.test(file),\n load: async (file) => {\n const input =\n config.sources?.kind === \"custom\"\n ? await config.sources.load(file, {\n root,\n documents: this.#files,\n })\n : {\n resolverId: file,\n ...descriptor(file),\n document: {\n ...descriptor(file).document,\n code: await read(file),\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 const custom =\n config.sources?.kind === \"custom\" && config.sources.resolve\n ? await config.sources.resolve(specifier, importer, {\n root,\n documents: this.#files,\n })\n : null;\n if (custom) {\n return {\n id: custom,\n };\n }\n const resolved =\n specifier.startsWith(\".\") || specifier.startsWith(\"/\")\n ? resolveVirtualModule(this.#files, specifier, importer, \"source\")\n : null;\n return resolved\n ? {\n id: resolved,\n }\n : null;\n },\n watch: () => {},\n warn: () => {},\n };\n }\n\n /**\n * Replaces virtual files after earlier operations finish and clears cached analysis and editor results.\n * Source edits keep CSS loaded. CSS dependencies, package metadata, and file additions or deletions\n * cause the next operation to reload CSS.\n *\n * @param files - All replacement files, copied before the update is queued.\n * @returns Completion of the update. Unchanged files have no effect.\n * @throws If the project is closed when the update runs.\n */\n replaceFiles(files: ReadonlyMap<string, string>): Promise<void> {\n const captured = new Map(files);\n const task = this.#queue.then(() => {\n if (this.#closed) {\n throw new Error(\"Browser project is closed\");\n }\n const changed = new Set(\n [...this.#files.keys(), ...captured.keys()].filter(\n (id) => this.#files.get(id) !== captured.get(id),\n ),\n );\n if (!changed.size) {\n return;\n }\n const resolutionChanged = [...changed].some(\n (id) => /\\.json$/i.test(id) || this.#files.has(id) !== captured.has(id),\n );\n this.#compilation.invalidate(changed);\n this.#files.clear();\n for (const [id, text] of captured) {\n this.#files.set(id, text);\n }\n this.#cache.clear();\n this.#editors.clear();\n if (\n resolutionChanged ||\n [...changed].some((id) => isStylesheet(id) || this.#cssDependencies.has(id))\n ) {\n this.#loader = undefined;\n this.#editorCss = undefined;\n this.#session = undefined;\n this.#plugins = undefined;\n this.#resources = [];\n this.#lintSources = [];\n this.#cssDependencies.clear();\n }\n });\n this.#queue = task.catch(() => {});\n return task;\n }\n\n /**\n * Loads target sources together and prepares their plugin candidates for later analysis.\n *\n * @param ids - Full virtual resolver IDs of the targets.\n * @returns Completion of preparation, or no work after closure. Loading and plugin failures are\n * left for each target's analysis to report. A failed plugin runtime is discarded before retrying.\n */\n prepare(ids: readonly string[]): Promise<void> {\n const task = this.#queue.then(async () => {\n if (this.#closed) {\n return;\n }\n try {\n const loader = await this.#designSystem();\n await this.#compilation.prepare(ids, this.#host(), this.#session!);\n await prepareSourcePlugins(this.#session!, loader, this.#compilation.texts());\n } catch {\n this.#loader = undefined;\n this.#session = undefined;\n this.#plugins = undefined;\n // Entry analysis reports failures with its own source and project identity.\n }\n });\n this.#queue = task.catch(() => {});\n return task;\n }\n\n /**\n * Analyzes and transforms an entry with its demanded semantic dependencies.\n *\n * @param id - Absolute virtual source path, including any query selecting distinct source.\n * @returns Readonly reports, code, and dependency coverage, shared by cache reads.\n * @throws If the project is closed, CSS loading fails, or compilation fails.\n */\n analyze(id: string): Promise<BrowserModuleAnalysis> {\n if (this.#closed) {\n return Promise.reject(new Error(\"Browser project is closed\"));\n }\n\n const task = this.#queue.then(async () => {\n const cached = this.#cache.get(id);\n if (cached) {\n return cached;\n }\n\n const { config } = this.#options;\n await this.#designSystem();\n const attempted = new Set<string>();\n const host = this.#host((id) => attempted.add(id));\n let result: ModuleAnalysis;\n try {\n result = await analyzeModule(\n this.#session!,\n () => (config.typeFacts === false ? undefined : this.#facts),\n id,\n host,\n {\n overlayFiles: this.#files,\n },\n this.#compilation,\n );\n } catch (error) {\n this.#invalidate(attempted);\n throw error;\n }\n if (result.generation === \"blocked\") {\n // A rejected native transaction can remove previously compiled dependencies.\n this.#invalidate(attempted);\n }\n result.sources = structuredClone(result.sources);\n const editor = new EditorSnapshot(\n result,\n this.#session!,\n this.#loader!,\n config,\n (await this.#plugins?.catalog()) ?? [],\n this.#plugins,\n );\n for (const report of editor.reports()) {\n const batch =\n result.batches.find((batch) =>\n batch.reports.some((item) => item.primary.location.uri === report.primary.location.uri),\n ) ?? result.batches[0];\n if (batch) {\n batch.reports.push(report);\n }\n }\n this.#editors.set(id, editor);\n const published: BrowserModuleAnalysis = result;\n this.#cache.set(id, published);\n return published;\n });\n\n this.#queue = task.catch(() => {});\n\n return task;\n }\n\n /**\n * Returns document CSS for successfully compiled graphs. automatic:false includes\n * only shared base CSS. Local text resources become data URLs; remote URLs retain\n * their authored values.\n *\n * @returns Document CSS and naming fallbacks, or empty CSS and reports before session creation.\n * @throws If an emitted local resource is absent from the captured files.\n */\n css(): BrowserStylesheetOutput {\n if (!this.#session) {\n return {\n css: \"\",\n rejectedNames: [],\n };\n }\n if (this.#options.config.automatic === false) {\n const output = this.#session.baseCss();\n return {\n css: this.#replaceResources(output.css, this.#resources),\n rejectedNames: output.rejectedNames,\n };\n }\n const plan = this.#session.planStylesheet({\n modules: this.#modules(),\n coverage: {\n kind: \"observed\",\n },\n placement: \"document\",\n });\n return {\n css: this.#replaceResources(finalizeCss(plan), [\n ...this.#resources,\n ...plan.resources.map((resource) => ({\n ...resource,\n sourceName: resource.moduleId,\n })),\n ]),\n rejectedNames: plan.rejectedNames,\n };\n }\n\n /**\n * Queries a captured source graph or a stylesheet in the project's CSS graph.\n * CSS completion, hover, resolution, and colors retry failed graph loads with recovered\n * definitions. CSS sorting and lint fixes require the original graph to load successfully.\n * Plugin path completion and links read captured files inside the project root without\n * loading the CSS graph or executing plugins.\n * Script queries first analyze their entry.\n *\n * @param id - Absolute virtual entry path, including a query that selects distinct source.\n * @param request - Operation with original UTF-16 offsets for that source.\n * @returns The editor answer, or undefined when no snapshot is available, the CSS graph\n * does not mark the stylesheet for a semantic query, or closure suppresses a pending answer.\n * @throws If a script query starts after closure, or if entry analysis, CSS graph loading,\n * source reading, or the editor query fails.\n */\n async query(id: string, request: EditorRequest): Promise<EditorResult | undefined> {\n if (isStylesheet(id)) {\n const task = this.#queue.then(async () => {\n if (this.#closed) {\n return undefined;\n }\n if (!this.#files.has(id)) {\n return undefined;\n }\n const navigation = await queryPluginPaths(id, await this.#read(id), request, {\n root: this.#options.root,\n names: this.#options.config.plugins?.map((plugin) => plugin.name) ?? [],\n documentUri: (file) => this.#documentUri(file),\n host: {\n resolve: async (specifier, importer) =>\n (await this.#options.plugins?.resolve(specifier, importer)) ??\n resolveVirtualModule(this.#files, specifier, importer),\n complete: async (prefix, importer, root) => [\n ...(await completePluginPaths(prefix, importer, root, {\n read: (file) => this.#read(file),\n directory: async (directory) => pluginDirectory(this.#files, directory),\n })),\n ...((await this.#options.plugins?.complete?.(prefix, importer, root)) ?? []),\n ],\n },\n });\n if (navigation) {\n return this.#closed ? undefined : navigation;\n }\n if (request.kind === \"sort\" || request.kind === \"fixes\") {\n await this.#designSystem();\n if (this.#editorCss?.recovered) {\n this.#editorCss = undefined;\n for (const [source, editor] of this.#editors) {\n if (editor instanceof StylesheetEditor) {\n this.#editors.delete(source);\n }\n }\n }\n }\n if (!this.#editorCss) {\n this.#editorCss = this.#loader\n ? {\n loader: this.#loader,\n resources: this.#resources,\n lintSources: this.#lintSources,\n recovered: false,\n plugins: this.#plugins,\n }\n : await loadEditorCssGraph(\n resolve(this.#options.root, cssEntrypoint(this.#options.config)),\n compilerOptions(this.#options.config),\n this.#cssHost(),\n );\n }\n if (!this.#editorCss.lintSources.includes(id) || this.#closed) {\n return undefined;\n }\n if (!this.#editors.has(id)) {\n const reports = this.#editorCss.recovered\n ? []\n : this.#editorCss.loader\n .stylesheetReports()\n .filter((report) => report.primary.location.uri === this.#documentUri(id));\n this.#editors.set(\n id,\n new StylesheetEditor(\n id,\n await this.#read(id),\n reports,\n this.#editorCss.loader.editorQuery(),\n this.#options.config,\n (await this.#editorCss.plugins?.catalog()) ?? [],\n this.#editorCss.plugins,\n ),\n );\n }\n const editor = this.#editors.get(id);\n await editor?.prepare(id, request);\n return this.#closed ? undefined : editor?.query(id, request);\n });\n this.#queue = task.catch(() => {});\n return task;\n }\n\n await this.analyze(id);\n if (this.#closed) {\n return undefined;\n }\n const editor = this.#editors.get(id);\n if (editor instanceof EditorSnapshot) {\n await editor.prepare(id, request);\n }\n return editor?.query(id, request);\n }\n\n /**\n * Returns CSS values keyed by absolute source path for explicit stillwind/module-css imports.\n * Parts preserve stylesheet occurrence order and include their content fingerprints.\n *\n * @returns A new map of module CSS records. No session produces an empty map.\n * @throws If an emitted local resource is absent from the captured files.\n */\n cssValues(): ReadonlyMap<string, BrowserModuleCss> {\n const values = new Map<string, BrowserModuleCss>();\n if (!this.#session) {\n return values;\n }\n for (const id of this.#modules()) {\n const plan = this.#session.planStylesheet({\n modules: [id],\n coverage: { kind: \"observed\" },\n placement: \"carrier\",\n });\n const resources = [\n ...this.#resources,\n ...plan.resources.map((resource) => ({\n ...resource,\n sourceName: resource.moduleId,\n })),\n ];\n values.set(resolve(this.#options.root, id), {\n css: this.#replaceResources(finalizeCss(plan), resources),\n rejectedNames: plan.rejectedNames,\n parts: plan.parts.map((part) => ({\n banners: part.banners,\n key: part.key,\n css: this.#replaceResources(part.css, resources),\n })),\n });\n }\n return values;\n }\n\n /**\n * Collects modules with generated code from retained successful graphs.\n *\n * @returns Distinct compiler identities in first graph occurrence order.\n */\n #modules(): string[] {\n return [\n ...new Set(\n [...this.#cache.values()]\n .filter((graph) => graph.generation === \"complete\")\n .flatMap((graph) =>\n graph.modules.filter((module) => module.code !== null).map((module) => module.moduleId),\n ),\n ),\n ];\n }\n\n /**\n * Removes cached graphs and editor snapshots affected by a rejected native transaction.\n *\n * @param modules - Compiler identities attempted by that transaction, including dependencies.\n */\n #invalidate(modules: ReadonlySet<string>): void {\n for (const [id, graph] of this.#cache) {\n if (\n modules.has(graph.entry) ||\n graph.sources.some((source) => modules.has(source.moduleId))\n ) {\n this.#cache.delete(id);\n this.#editors.delete(id);\n }\n }\n }\n\n /**\n * Replaces emitted CSS placeholders with authored remote URLs or embedded local text.\n *\n * @param css - Generated CSS containing zero or more resource placeholders.\n * @param resources - Placeholder records with source names relative to the project root or absolute.\n * @returns CSS with JSON-escaped URL contents. SVG uses image/svg+xml and other local text uses text/plain.\n * @throws If a referenced local file is absent from the captured inventory.\n */\n #replaceResources(\n css: string,\n resources: readonly {\n /** Exact emitted token to replace in CSS. */\n placeholder: string;\n /** Authored URL, resolved relative to its source when it is local. */\n specifier: string;\n /** Source path whose directory determines local resource resolution. */\n sourceName: string;\n }[],\n ): string {\n for (const resource of resources) {\n if (!css.includes(resource.placeholder)) {\n continue;\n }\n let url = resource.specifier;\n if (!/^(?:[a-z][a-z\\d+.-]*:|\\/\\/|#)/i.test(url)) {\n const file = resolve(dirname(resolve(this.#options.root, resource.sourceName)), url);\n const source = this.#files.get(file);\n if (source === undefined) {\n throw new Error(`Browser CSS resource is missing: ${file}`);\n }\n const mime = file.endsWith(\".svg\") ? \"image/svg+xml\" : \"text/plain\";\n url = `data:${mime};charset=utf-8,${encodeURIComponent(source)}`;\n }\n css = css.replaceAll(resource.placeholder, JSON.stringify(url).slice(1, -1));\n }\n return css;\n }\n\n /**\n * Prevents new analyses, waits for queued work, and releases the checker, snapshots, and native session.\n *\n * @returns Completion of project cleanup.\n */\n async close(): Promise<void> {\n this.#closed = true;\n await this.#queue;\n this.#facts.close();\n this.#editors.clear();\n this.#session = undefined;\n this.#loader = undefined;\n this.#editorCss = undefined;\n }\n}\n\n/**\n * Converts a workspace URI to its decoded absolute path without filesystem access.\n *\n * @param uri - Absolute URI whose pathname identifies a file in the virtual inventory.\n * @returns The decoded pathname; the scheme and authority are omitted.\n * @throws If the URI or its percent encoding is invalid.\n */\nexport function virtualPath(uri: string): string {\n return decodeURIComponent(new URL(uri).pathname);\n}\n"],"mappings":";;;;;;;;;;;;;;;AAWA,SAAgB,MAAM,MAAe,UAAyC;CAC5E,SAAS,IAAI;CACb,KAAK,cAAc,UAAU,MAAM,OAAO,QAAQ,CAAC;AACrD;;;;;;;;AA2BA,SAAS,WAAW,MAAe,OAAqC;CACtE,MAAM,OAAO,KAAK,aAAa,eAAe,EAAE,EAAE,cAAc,CAAC,CAAC;CAClE,OAAO,SAAS,KAAA,KAAa,MAAM,IAAI,IAAI;AAC7C;;AAGA,MAAM,qBACJ,GAAG,UAAU,aACb,GAAG,UAAU,aACb,GAAG,UAAU,aACb,GAAG,UAAU,cACb,GAAG,UAAU,WACb,GAAG,UAAU,eACb,GAAG,UAAU,OACb,GAAG,UAAU,YACb,GAAG,UAAU,OACb,GAAG,UAAU;;;;;;;;;;;;;;;AAgBf,SAAgB,OACd,SACA,MACA,UACA,YACA,QACA,WACA,i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MAAM;EACpB,KAAK,WAAW,KAAA;EAChB,KAAK,UAAU,KAAA;EACf,KAAK,aAAa,KAAA;CACpB;AACF;;;;;;;;AASA,SAAgB,YAAY,KAAqB;CAC/C,OAAO,mBAAmB,IAAI,IAAI,GAAG,CAAC,CAAC,QAAQ;AACjD"}
@@ -0,0 +1,405 @@
1
+ // src/css/plugins/tailwind/css.ts
2
+ /**
3
+ * Serializes a plugin CSS object, as plugins pass it to Tailwind's API, while preserving
4
+ * repeated declarations and nested rules.
5
+ *
6
+ * @param input - CSS-in-JS object or array of them. An array value of a property repeats the
7
+ * declaration, camel-case property names become kebab-case, and null, undefined, and false
8
+ * values are skipped. `@slot` keys and values become `@slot` statements.
9
+ * @returns CSS declarations and rules without surrounding braces, or an empty string for input
10
+ * that is not an object.
11
+ */
12
+ function serializeCss(input) {
13
+ if (Array.isArray(input)) return input.map(serializeCss).join("\n");
14
+ if (!input || typeof input !== "object") return "";
15
+ let output = "";
16
+ for (const [key, value] of Object.entries(input)) {
17
+ if (value === null || value === void 0 || value === false) continue;
18
+ if (key === "@slot") {
19
+ output += "@slot;";
20
+ continue;
21
+ }
22
+ if (!key.startsWith("--") && value === "@slot") {
23
+ output += `${key}{@slot;}`;
24
+ continue;
25
+ }
26
+ if (statement(key, value)) {
27
+ output += `${key};`;
28
+ continue;
29
+ }
30
+ const values = Array.isArray(value) ? value : [value];
31
+ for (const entry of values) if (entry && typeof entry === "object") output += `${key}{${serializeCss(entry)}}`;
32
+ else if (entry !== null && entry !== void 0 && entry !== false) {
33
+ const property = key.startsWith("--") ? key : key.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`).replace(/^ms-/, "-ms-");
34
+ output += `${property}:${String(entry)};`;
35
+ }
36
+ }
37
+ return output;
38
+ }
39
+ /**
40
+ * Whether an entry is an at-rule without a block, such as `{ "@apply p-4": {} }`, which
41
+ * Tailwind serializes as the statement `@apply p-4;`.
42
+ *
43
+ * @param key - Entry key.
44
+ * @param value - Entry value.
45
+ * @returns Whether the key is an at-rule and the value an empty object.
46
+ */
47
+ function statement(key, value) {
48
+ return key.startsWith("@") && typeof value === "object" && value !== null && !Array.isArray(value) && Object.keys(value).length === 0;
49
+ }
50
+ /**
51
+ * Escapes a complete candidate as one CSS identifier, including arbitrary-value punctuation.
52
+ *
53
+ * @param value - Candidate or variant name, such as `-probe-[3px]/mirror`.
54
+ * @returns An identifier whose CSS escapes decode to `value`. A leading digit becomes a
55
+ * six-digit hexadecimal escape.
56
+ */
57
+ function identifier(value) {
58
+ return Array.from(value).map((character, index) => {
59
+ if (/[_a-zA-Z\u0080-\uffff-]/u.test(character) || index > 0 && /\d/.test(character)) return character;
60
+ if (/\d/.test(character)) return `\\${character.codePointAt(0).toString(16).padStart(6, "0")}`;
61
+ return `\\${character}`;
62
+ }).join("");
63
+ }
64
+ /**
65
+ * Applies an alpha value to a color as Tailwind's `withAlpha()` does.
66
+ *
67
+ * Every plain number is multiplied by 100, so `0.5` means 50% and `50` means 5000%, which
68
+ * `color-mix()` rejects. Tailwind applies this to the `/50` of `theme("colors.red.500 / 50")`,
69
+ * while a `/50` color modifier of a utility arrives here already as `50%`.
70
+ *
71
+ * @param value - CSS color.
72
+ * @param alpha - Number, percentage, or other CSS value such as `var(--opacity)`.
73
+ * @returns The color itself for `100%`, and a `color-mix()` toward transparent otherwise.
74
+ */
75
+ function withAlpha(value, alpha) {
76
+ const number = Number(alpha);
77
+ const percentage = Number.isNaN(number) ? alpha : `${number * 100}%`;
78
+ return percentage === "100%" ? value : `color-mix(in oklab, ${value} ${percentage}, transparent)`;
79
+ }
80
+ /** Class names that Tailwind's `addUtilities()` registers. */
81
+ const IS_VALID_UTILITY_NAME = /^[a-z@][a-zA-Z0-9/%._-]*$/;
82
+ /**
83
+ * Finds the classes that a plugin selector registers, as Tailwind's `addUtilities()` does: every
84
+ * class outside attribute selectors and outside the arguments of `:not()`, `:nth-child()`, and
85
+ * `:nth-last-child()`, whose classes are conditions rather than utilities. `.outer .inner`
86
+ * registers both `outer` and `inner`.
87
+ *
88
+ * @param selector - One complex selector without top-level commas.
89
+ * @returns The decoded class names with the range of each `.name`, in source order.
90
+ */
91
+ function utilityClasses(selector) {
92
+ const classes = [];
93
+ const parentheses = [];
94
+ let excluded = 0;
95
+ let attribute = 0;
96
+ let quote = "";
97
+ for (let index = 0; index < selector.length; index++) {
98
+ const char = selector[index];
99
+ if (char === "\\") index++;
100
+ else if (quote) quote = char === quote ? "" : quote;
101
+ else if (char === "\"" || char === "'") quote = char;
102
+ else if (char === "[") attribute++;
103
+ else if (char === "]") attribute--;
104
+ else if (char === "(") {
105
+ const condition = /:(?:not|nth-child|nth-last-child)$/i.test(selector.slice(0, index));
106
+ parentheses.push(condition);
107
+ excluded += condition ? 1 : 0;
108
+ } else if (char === ")") excluded -= parentheses.pop() ? 1 : 0;
109
+ else if (char === "." && !excluded && !attribute) {
110
+ const { name, end } = readIdentifier(selector, index + 1);
111
+ if (IS_VALID_UTILITY_NAME.test(name)) classes.push({
112
+ name,
113
+ start: index,
114
+ end
115
+ });
116
+ index = end - 1;
117
+ }
118
+ }
119
+ return classes;
120
+ }
121
+ /**
122
+ * Reads a CSS identifier and decodes its escapes.
123
+ *
124
+ * @param text - Text that contains the identifier.
125
+ * @param start - Index of the first character of the identifier.
126
+ * @returns The decoded name, empty when no identifier starts at `start`, and the index after it.
127
+ */
128
+ function readIdentifier(text, start) {
129
+ let end = start;
130
+ let name = "";
131
+ while (end < text.length) {
132
+ const next = text[end];
133
+ if (next === "\\") {
134
+ const hex = /^[0-9a-f]{1,6}\s?/i.exec(text.slice(end + 1));
135
+ name += hex ? String.fromCodePoint(Number.parseInt(hex[0], 16)) : text[end + 1];
136
+ end += 1 + (hex ? hex[0].length : 1);
137
+ } else if (/[\w\u0080-￿-]/u.test(next)) {
138
+ name += next;
139
+ end++;
140
+ } else break;
141
+ }
142
+ return {
143
+ name,
144
+ end
145
+ };
146
+ }
147
+ /**
148
+ * Serializes text as a CSS string.
149
+ *
150
+ * @param value - Text, such as generated CSS.
151
+ * @returns A double-quoted CSS string whose escapes decode to `value`.
152
+ */
153
+ function cssString(value) {
154
+ return `"${value.replace(/["\\]/g, "\\$&").replace(/[\n\r\f]/g, (character) => `\\${character.codePointAt(0).toString(16)} `)}"`;
155
+ }
156
+ /**
157
+ * Replaces every `&` outside strings and attribute selectors.
158
+ *
159
+ * @param selector - Selector that may contain `&`.
160
+ * @param parent - Replacement for `&`.
161
+ * @returns The selector with the parent substituted, or undefined when it has no `&`.
162
+ */
163
+ function substituteNesting(selector, parent) {
164
+ let output = "";
165
+ let nested = false;
166
+ let attribute = 0;
167
+ let quote = "";
168
+ for (let index = 0; index < selector.length; index++) {
169
+ const char = selector[index];
170
+ if (char === "\\") {
171
+ output += selector.slice(index, index + 2);
172
+ index++;
173
+ continue;
174
+ }
175
+ if (quote) quote = char === quote ? "" : quote;
176
+ else if (char === "\"" || char === "'") quote = char;
177
+ else if (char === "[") attribute++;
178
+ else if (char === "]") attribute--;
179
+ else if (char === "&" && !attribute) {
180
+ output += parent;
181
+ nested = true;
182
+ continue;
183
+ }
184
+ output += char;
185
+ }
186
+ return nested ? output : void 0;
187
+ }
188
+ /**
189
+ * Converts the rules that `addUtilities()` receives into utility bodies. At-rules retain their
190
+ * enclosing conditions.
191
+ *
192
+ * @param input - CSS-in-JS object keyed by selectors and at-rules, or an array of them.
193
+ * @param register - Receives the anchor class of a selector and one body for it, once for each
194
+ * selector of the body.
195
+ * @param global - Receives top-level `@keyframes` and `@property` rules, which apply whether or
196
+ * not a utility is used. The compiler emits such rules nested in a utility body only with that
197
+ * utility.
198
+ * @param wrappers - Enclosing at-rule preludes, outermost first.
199
+ * @throws If a selector has no class outside `:not()` and attribute selectors.
200
+ */
201
+ function utilityRules(input, register, global, wrappers = []) {
202
+ if (Array.isArray(input)) {
203
+ for (const entry of input) utilityRules(entry, register, global, wrappers);
204
+ return;
205
+ }
206
+ if (!input || typeof input !== "object") return;
207
+ /**
208
+ * Wraps CSS in the enclosing at-rules.
209
+ * @param body - CSS inside the innermost at-rule.
210
+ * @returns The wrapped CSS.
211
+ */
212
+ const wrap = (body) => wrappers.reduceRight((css, rule) => `${rule}{${css}}`, body);
213
+ for (const [selector, body] of Object.entries(input)) if (selector.startsWith("@keyframes ") || selector.startsWith("@property ")) global(wrap(`${selector}{${serializeCss(body)}}`));
214
+ else if (selector.startsWith("@")) utilityRules(body, register, global, [...wrappers, selector]);
215
+ else for (const branch of splitTopLevel(selector, ",").map((part) => part.trim())) {
216
+ const classes = utilityClasses(branch);
217
+ if (!classes.length) throw new Error(`Tailwind plugin utility requires a class selector: ${selector}`);
218
+ for (const anchor of classes) {
219
+ const relative = `${branch.slice(0, anchor.start)}&${branch.slice(anchor.end)}`;
220
+ for (const css of utilityBodies(body, relative, wrappers)) register(anchor.name, css);
221
+ }
222
+ }
223
+ }
224
+ /**
225
+ * Lists the selectors of the nested rules in CSS-in-JS input, each as an empty rule, so that
226
+ * the compiler can collect the classes that they name without the declarations.
227
+ *
228
+ * @param input - CSS-in-JS body, or an array of them.
229
+ * @returns Each selector key as written followed by `{}`, in source order. Selectors inside
230
+ * conditional at-rules are included, and `@keyframes` and `@property` rules are skipped.
231
+ */
232
+ function selectorRules(input) {
233
+ if (Array.isArray(input)) return input.flatMap(selectorRules);
234
+ if (!input || typeof input !== "object") return [];
235
+ const rules = [];
236
+ for (const [key, value] of Object.entries(input)) {
237
+ if (!value || typeof value !== "object" || statement(key, value) || Array.isArray(value) && !value.some((entry) => entry && typeof entry === "object") || key.startsWith("@keyframes ") || key.startsWith("@property ")) continue;
238
+ if (!key.startsWith("@")) rules.push(`${key}{}`);
239
+ rules.push(...selectorRules(value));
240
+ }
241
+ return rules;
242
+ }
243
+ /**
244
+ * Flattens nested selector rules into utility bodies with one selector block each, which the
245
+ * compiler composes as independent targets.
246
+ *
247
+ * @param input - CSS-in-JS body, or an array of them.
248
+ * @param selector - Selector of the body relative to the utility class, `&` for the class itself.
249
+ * @param conditions - Enclosing at-rule preludes, outermost first.
250
+ * @returns Bodies in source order. Each one is either declarations, possibly inside
251
+ * conditions, for `&`, one rule for another selector, or one `@keyframes` or `@property` rule
252
+ * inside its conditions.
253
+ */
254
+ function utilityBodies(input, selector = "&", conditions = []) {
255
+ if (Array.isArray(input)) return input.flatMap((entry) => utilityBodies(entry, selector, conditions));
256
+ if (!input || typeof input !== "object") return [];
257
+ const result = [];
258
+ let declarations = {};
259
+ /** Adds the declarations collected so far as one body and starts a new collection. */
260
+ const flush = () => {
261
+ const css = serializeCss(declarations);
262
+ if (css) {
263
+ const body = conditions.reduceRight((body, condition) => `${condition}{${body}}`, css);
264
+ result.push(selector === "&" ? body : `${selector}{${body}}`);
265
+ }
266
+ declarations = {};
267
+ };
268
+ for (const [key, value] of Object.entries(input)) if (value && typeof value === "object" && !statement(key, value) && (!Array.isArray(value) || value.some((entry) => entry && typeof entry === "object"))) {
269
+ flush();
270
+ if (key.startsWith("@keyframes ") || key.startsWith("@property ")) result.push(conditions.reduceRight((body, condition) => `${condition}{${body}}`, `${key}{${serializeCss(value)}}`));
271
+ else if (key.startsWith("@")) result.push(...utilityBodies(value, selector, [...conditions, key]));
272
+ else for (const parent of splitTopLevel(selector, ",").map((part) => part.trim())) for (const child of splitTopLevel(key, ",").map((part) => part.trim())) result.push(...utilityBodies(value, substituteNesting(child, parent) ?? `${parent} ${child}`, conditions));
273
+ } else declarations[key] = value;
274
+ flush();
275
+ return result;
276
+ }
277
+ /**
278
+ * Splits text at a delimiter outside CSS strings, brackets, and function calls.
279
+ *
280
+ * @param value - Text to split. Escaped characters never delimit.
281
+ * @param delimiter - One character, such as `,` or `/`.
282
+ * @returns The parts without trimming, including empty ones. Text without the delimiter is one
283
+ * part.
284
+ */
285
+ function splitTopLevel(value, delimiter) {
286
+ const parts = [];
287
+ let start = 0;
288
+ let depth = 0;
289
+ let quote = "";
290
+ for (let index = 0; index < value.length; index++) {
291
+ const char = value[index];
292
+ if (char === "\\") {
293
+ index++;
294
+ continue;
295
+ }
296
+ if (quote) {
297
+ if (char === quote) quote = "";
298
+ continue;
299
+ }
300
+ if (char === "\"" || char === "'") {
301
+ quote = char;
302
+ continue;
303
+ }
304
+ if (char === "[" || char === "(") depth++;
305
+ else if (char === "]" || char === ")") depth--;
306
+ else if (depth === 0 && char === delimiter) {
307
+ parts.push(value.slice(start, index));
308
+ start = index + 1;
309
+ }
310
+ }
311
+ parts.push(value.slice(start));
312
+ return parts;
313
+ }
314
+ /**
315
+ * Converts the declarations of a Tailwind `@plugin` options block into the values that
316
+ * `plugin.withOptions()` factories receive.
317
+ *
318
+ * @param options - Declarations in authored order, such as `prefix` with the value `"x"`.
319
+ * @returns Options by name, converted as Tailwind converts them. A later declaration of a
320
+ * name replaces an earlier one. `true`, `false`, `null`, and numeric text become those values.
321
+ * A quoted string loses its quotes and keeps its backslashes. Other text stays a string, and a
322
+ * comma-separated list becomes an array.
323
+ */
324
+ function pluginOptions(options) {
325
+ const result = {};
326
+ for (const { name, value: text } of options) {
327
+ const entries = splitTopLevel(text, ",").map((part) => {
328
+ const value = part.trim();
329
+ if (value === "true") return true;
330
+ if (value === "false") return false;
331
+ if (value === "null") return null;
332
+ if (!Number.isNaN(Number(value))) return Number(value);
333
+ return value.startsWith("\"") && value.endsWith("\"") || value.startsWith("'") && value.endsWith("'") ? value.slice(1, -1) : value;
334
+ });
335
+ result[name] = entries.length === 1 ? entries[0] : entries;
336
+ }
337
+ return result;
338
+ }
339
+ // src/css/plugins/tailwind/configuration.ts
340
+ /**
341
+ * Normalizes a Tailwind plugin export to `{ handler, config }` and applies the options of its
342
+ * `@plugin` statement.
343
+ *
344
+ * @param plugin - Handler, `{ handler, config }`, or factory from `plugin.withOptions()`.
345
+ * @param options - Declarations of the statement's options block, empty without a block.
346
+ * @returns The factory's result for converted `options`, or the plugin in object form.
347
+ * @throws If a handler that is not a factory receives options, or an option value is invalid.
348
+ */
349
+ function configurePlugin(plugin, options) {
350
+ if (typeof plugin === "function" && "__isOptionsFunction" in plugin && plugin.__isOptionsFunction) return plugin(pluginOptions(options));
351
+ if (options.length) throw new Error("This Tailwind plugin does not accept options");
352
+ return typeof plugin === "function" ? { handler: plugin } : plugin;
353
+ }
354
+ /**
355
+ * Builds the part of Tailwind's resolved config that `config()` reads besides `theme`.
356
+ *
357
+ * Like Tailwind, the result keeps only `darkMode`, `prefix`, `blocklist`, and `important` from
358
+ * the configs, so `config("custom")` returns the fallback. The last config that defines one of
359
+ * these keys sets it, and a `null` value restores the default.
360
+ *
361
+ * @param configs - Plugin configs in registration order, presets first.
362
+ * @returns The resolved keys with Tailwind's defaults for the others.
363
+ */
364
+ function resolveConfig(configs) {
365
+ const defaults = {
366
+ darkMode: null,
367
+ prefix: "",
368
+ blocklist: [],
369
+ important: false
370
+ };
371
+ const result = {
372
+ ...defaults,
373
+ future: {},
374
+ experimental: {},
375
+ plugins: [],
376
+ content: { files: [] }
377
+ };
378
+ for (const config of configs) for (const [key, fallback] of Object.entries(defaults)) if (config[key] !== void 0) result[key] = config[key] ?? fallback;
379
+ return result;
380
+ }
381
+ /**
382
+ * Returns the `dark` variant that Tailwind's `darkMode` configuration key defines.
383
+ *
384
+ * @param setting - `"media"`, `"selector"`, `"class"`, or a tuple of one of these modes and a
385
+ * selector, which defaults to `.dark`. `["variant", selectors]` uses a selector or a list of
386
+ * selectors, and each must contain `&`.
387
+ * @returns The value for `addVariant()`, or undefined when the setting defines no variant,
388
+ * including `null`, `false`, and the `variant` mode with a selector that Tailwind rejects.
389
+ */
390
+ function darkModeVariant(setting) {
391
+ const [mode, selector = ".dark"] = Array.isArray(setting) ? setting : [setting];
392
+ switch (mode) {
393
+ case "media": return "@media (prefers-color-scheme: dark)";
394
+ case "selector": return `&:where(${selector}, ${selector} *)`;
395
+ case "class": return `&:is(${selector} *)`;
396
+ case "variant": {
397
+ const selectors = Array.isArray(selector) ? selector : [selector];
398
+ return selectors.every((entry) => typeof entry === "string" && entry !== ".dark" && entry.includes("&")) ? selectors : void 0;
399
+ }
400
+ default: return;
401
+ }
402
+ }
403
+ export { splitTopLevel as a, withAlpha as c, configurePlugin, darkModeVariant, serializeCss as i, identifier as n, utilityBodies as o, selectorRules as r, resolveConfig, utilityRules as s, cssString as t };
404
+
405
+ //# sourceMappingURL=configuration-CnrzO-F3.js.map