@stillwind/analysis 0.10.1 → 0.12.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/node.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"node.js","names":["process"],"sources":["../src/worker-client.ts","../src/write.ts","../src/rewrite-files.ts","../src/format.ts","../src/design-system.ts","../src/inspect.ts","../src/lint.ts","../src/node-workspace.ts","../src/source-formatter.ts"],"sourcesContent":["import { fork, type ChildProcess } from \"node:child_process\";\nimport process from \"node:process\";\nimport { fileURLToPath } from \"node:url\";\n\nimport type { DesignSystemRequest, EditorRequest, WorkspaceResult } from \"@stillwind/host\";\n\nimport { RewriteFailure, type RewriteInput, type RewriteBatchResult } from \"./rewrite.ts\";\n\n/** Requests sent to the process that owns trusted config evaluation and plugin lifetimes. */\nexport type WorkerRequest =\n | {\n /** Serialized discriminator for replacing the child workspace. */\n method: \"open\";\n /** Configuration path evaluated in the child process, replacing any previously opened workspace. */\n config: string;\n }\n | {\n /** Serialized discriminator for analyzing configured targets. */\n method: \"lint\";\n /** Additional target globs relative to each project root. Omission checks all configured targets. */\n patterns?: readonly string[];\n }\n | {\n /** Serialized discriminator for enumerating distinct targets. */\n method: \"targets\";\n /** Additional project-relative globs. An empty or omitted list keeps every configured target. */\n patterns?: readonly string[];\n /** Adds the stylesheets that each project lints. */\n stylesheets?: boolean;\n }\n | {\n /** Serialized discriminator for computing source replacements. */\n method: \"rewrite\";\n /** Distinct absolute target paths and captured text, retained in result order. */\n inputs: readonly RewriteInput[];\n /** Selects one sort pass or lint fixes that must converge. */\n operation: \"sort\" | \"fixes\";\n }\n | {\n /** Serialized discriminator for preparing a batch of targets. */\n method: \"prepare\";\n /** Absolute target paths. */\n files: readonly string[];\n }\n | {\n /** Serialized discriminator for analyzing one target in matching projects. */\n method: \"analyze\";\n /** Absolute target path. Each project whose scope contains the file returns a result. */\n file: string;\n }\n | {\n /** Serialized discriminator for an editor query against original text. */\n method: \"query\";\n /** Absolute target file path. */\n file: string;\n /** Editor operation in original UTF-16 coordinates. */\n request: EditorRequest;\n }\n | {\n /** Serialized discriminator for a question about each project's design system. */\n method: \"designSystem\";\n /** Theme, utility, or variant request. */\n request: DesignSystemRequest;\n }\n | {\n /** Serialized discriminator for replacing an unsaved buffer. */\n method: \"update\";\n /** Absolute source path, including dependencies outside target scopes. */\n file: string;\n /** Complete unsaved source text. */\n source: string;\n /** Safe integer that increases while this file is open. */\n version: number;\n }\n | {\n /** Serialized discriminator for removing an unsaved buffer. */\n method: \"closeDocument\";\n /** Absolute path of the buffer to remove. Unknown files have no effect. */\n file: string;\n }\n | {\n /** Serialized discriminator for checking whether the caller needs to reopen the workspace. */\n method: \"refresh\";\n /** Absolute file paths reported by save or watch notifications. */\n files: readonly string[];\n }\n | {\n /** Serialized discriminator for checking whether file changes can change results. */\n method: \"affects\";\n /** Absolute file paths reported by watch notifications. */\n files: readonly string[];\n }\n | {\n /** Serialized discriminator for refreshing disk and compiler caches. */\n method: \"invalidate\";\n }\n | {\n /** Serialized discriminator for closing hosts and disconnecting the child. */\n method: \"close\";\n };\n\n/** IPC response correlated with one request. Successful void operations can omit value. */\nexport interface WorkerReply {\n /** Request sequence number assigned by AnalysisWorker. */\n id: number;\n /** Serialized operation result when error is absent. */\n value?: unknown;\n /** Exception message and any analysis results that prevented a rewrite. */\n error?: {\n message: string;\n results?: WorkspaceResult[];\n };\n}\n\n/** Isolates configuration and plugin logs from CLI JSON and the LSP stdout transport. */\nexport class AnalysisWorker {\n /** Owned child with IPC enabled. Both output streams are forwarded to the parent's stderr. */\n readonly #child: ChildProcess;\n /** Unanswered requests keyed by monotonically assigned IPC sequence number. */\n readonly #pending = new Map<\n number,\n {\n /** Settles the request with the child's unvalidated reply value. */\n resolve: (value: unknown) => void;\n /** Rejects the request after delivery, child-operation, or process failure. */\n reject: (error: Error) => void;\n }\n >();\n /** Resolves on process closure after outstanding requests have been rejected. */\n readonly #closed: Promise<void>;\n\n /** Next IPC sequence number, independent of source document versions. */\n #nextId = 0;\n /** Whether process closure has been observed. */\n #exited = false;\n /** Prevents repeated close calls from sending another cleanup request. */\n #closing = false;\n\n /**\n * Starts the child process immediately. Call open before analysis and close when finished.\n */\n constructor() {\n this.#child = fork(fileURLToPath(new URL(\"./worker.js\", import.meta.url)), [], {\n stdio: [\"ignore\", \"pipe\", \"pipe\", \"ipc\"],\n execArgv: [],\n windowsHide: true,\n });\n this.#child.stdout!.on(\"data\", (data: Buffer) => {\n process.stderr.write(data);\n });\n this.#child.stderr!.on(\"data\", (data: Buffer) => {\n process.stderr.write(data);\n });\n this.#child.on(\"message\", (reply: WorkerReply) => {\n const request = this.#pending.get(reply.id);\n this.#pending.delete(reply.id);\n if (reply.error) {\n request?.reject(\n reply.error.results\n ? new RewriteFailure(reply.error.message, reply.error.results)\n : new Error(reply.error.message),\n );\n } else {\n request?.resolve(reply.value);\n }\n });\n this.#child.on(\"error\", (error) => {\n for (const request of this.#pending.values()) {\n request.reject(error);\n }\n this.#pending.clear();\n });\n this.#closed = new Promise((resolve) => {\n this.#child.on(\"close\", (code, signal) => {\n this.#exited = true;\n for (const request of this.#pending.values()) {\n request.reject(new Error(`Stillwind analysis worker closed (${code ?? signal})`));\n }\n this.#pending.clear();\n resolve();\n });\n });\n }\n\n /**\n * Sends an IPC operation and correlates its reply. Calls are not serialized here.\n *\n * @param request - Operation payload. Await open before using workspace operations, and avoid\n * overlapping replacement or closure with analysis requests.\n * @returns The reply value cast to T. The caller must choose T to match the operation's result.\n * @throws If the child is closed, IPC delivery fails, or the child operation reports an error.\n */\n async request<T = void>(request: WorkerRequest): Promise<T> {\n if (this.#exited) {\n throw new Error(\"Stillwind analysis worker is closed\");\n }\n const id = this.#nextId++;\n return (await new Promise<unknown>((resolve, reject) => {\n this.#pending.set(id, { resolve, reject });\n this.#child.send({ id, request }, (error) => {\n if (error) {\n this.#pending.delete(id);\n reject(error);\n }\n });\n })) as T;\n }\n\n /**\n * Replaces the child workspace, closing any previously opened hosts first.\n *\n * @param config - Configuration path. Relative paths use the child's inherited working directory.\n * @returns A promise that resolves after the configuration and project hosts have opened.\n * @throws If configuration evaluation, project initialization, or transport fails.\n */\n async open(config: string): Promise<void> {\n await this.request({\n method: \"open\",\n config,\n });\n }\n\n /**\n * Analyzes a target in each matching project of the opened workspace.\n *\n * @param file - Absolute target path. Unsaved buffers use preceding update requests.\n * @returns Scoped results in project order, or an empty list when no scope includes the target.\n * @throws If the workspace has not opened or transport fails.\n */\n analyze(file: string): Promise<WorkspaceResult[]> {\n return this.request({\n method: \"analyze\",\n file,\n });\n }\n\n /**\n * Enumerates and analyzes targets in the opened workspace.\n *\n * @param patterns - Additional globs relative to each project root. Empty or omitted filters\n * retain every configured target.\n * @returns Results in project order and sorted target order within each project.\n * @throws If the workspace has not opened, enumeration fails, or transport fails.\n */\n lint(patterns?: readonly string[]): Promise<WorkspaceResult[]> {\n return this.request({\n method: \"lint\",\n patterns,\n });\n }\n\n /**\n * Enumerates distinct targets in the opened workspace.\n *\n * @param patterns - Additional project-relative globs. Omission or an empty list retains all targets.\n * @param stylesheets - Adds the stylesheets that each project lints.\n * @returns Sorted absolute paths, deduplicated across projects.\n * @throws If the workspace has not opened, enumeration fails, or transport fails.\n */\n targets(patterns?: readonly string[], stylesheets?: boolean): Promise<string[]> {\n return this.request({\n method: \"targets\",\n patterns,\n stylesheets,\n });\n }\n\n /**\n * Computes replacements from captured buffers without writing files.\n *\n * @param inputs - Distinct absolute target paths and complete original text.\n * @param operation - Utility sorting or lint fixes, limited to ten changing passes per target.\n * @returns Successful replacements and target failures in input order. Captured buffers are removed after planning.\n * @throws If workspace setup, buffer installation, cleanup, or transport fails.\n */\n rewrite(\n inputs: readonly RewriteInput[],\n operation: \"sort\" | \"fixes\",\n ): Promise<RewriteBatchResult> {\n return this.request({\n method: \"rewrite\",\n inputs,\n operation,\n });\n }\n\n /**\n * Requests host cleanup and waits for the child process to close. After the cleanup request\n * settles, a child that remains alive for five seconds is terminated.\n *\n * @returns A promise that resolves after process closure. Repeated calls wait for that closure.\n * @throws If the initial cleanup request or its transport fails.\n */\n async close(): Promise<void> {\n if (this.#closing || this.#exited) {\n await this.#closed;\n return;\n }\n this.#closing = true;\n try {\n await this.request({\n method: \"close\",\n });\n } finally {\n const timer = setTimeout(() => {\n this.#child.kill();\n }, 5000);\n await this.#closed;\n clearTimeout(timer);\n }\n }\n}\n","import { readFile, writeFile } from \"node:fs/promises\";\n\nimport type { RewriteFileFailure } from \"./rewrite.ts\";\n\n/**\n * A replacement with the original bytes retained for verification before saving.\n */\nexport interface FileChange {\n /** Target path. The caller must provide at most one change per file. */\n file: string;\n /** Bytes captured before planning, compared against disk before saving. */\n before: Buffer;\n /** Planned replacement bytes. Equal bytes skip verification and writing. */\n after: Buffer;\n}\n\n/**\n * Saves changed bytes once per file. Identical buffers perform no filesystem operations.\n * Checks each original immediately before saving and continues after a target fails.\n *\n * @param changes - Distinct target paths and original/replacement bytes. Buffers remain unchanged.\n * @returns Saved paths and failures. A stale file is left unchanged.\n */\nexport async function writeChangedFiles(changes: readonly FileChange[]): Promise<{\n changed: string[];\n failures: RewriteFileFailure[];\n}> {\n const changed = changes.filter((change) => !change.before.equals(change.after));\n const saved: string[] = [];\n const failures: RewriteFileFailure[] = [];\n for (const change of changed) {\n try {\n if (!(await readFile(change.file)).equals(change.before)) {\n throw new Error(`Source changed before saving ${change.file}`);\n }\n await writeFile(change.file, change.after);\n saved.push(change.file);\n } catch (error) {\n failures.push({\n file: change.file,\n message: error instanceof Error ? error.message : String(error),\n results: [],\n });\n }\n }\n return {\n changed: saved,\n failures,\n };\n}\n","import { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { findConfiguration } from \"@stillwind/config/node\";\nimport type { WorkspaceResult } from \"@stillwind/host\";\n\nimport type { RewriteFileFailure, RewriteInput } from \"./rewrite.ts\";\nimport { AnalysisWorker } from \"./worker-client.ts\";\nimport { writeChangedFiles } from \"./write.ts\";\n\n/**\n * Selects configured source files for CLI analysis and rewriting.\n */\nexport interface RewriteOptions {\n /** Explicit configuration path, absolute or relative to cwd. Omission searches upward from cwd. */\n config?: string;\n /** Directory for configuration discovery and relative config paths. Defaults to process.cwd(). */\n cwd?: string;\n /** Additional globs relative to each project root. Omission or an empty list retains all configured targets. */\n patterns?: string[];\n}\n\n/**\n * A completed rewrite batch with findings kept separately for each owning project.\n */\ninterface RewriteFilesResult {\n /** Absolute configuration path used by the isolated worker. */\n config: string;\n /** Absolute paths whose original and final bytes differ, in sorted order. */\n changed: string[];\n /** Original findings for sorting and final findings for lint fixes, in project and target order. */\n results: WorkspaceResult[];\n /** Targets that could not be read, rewritten, or saved. */\n failures: RewriteFileFailure[];\n}\n\n/**\n * Computes all replacements before optionally saving changed files. Fixes return final findings.\n *\n * @param options - Configuration discovery and optional filters within configured target scopes.\n * @param operation - Utility sorting or converged lint fixes.\n * @param write - Whether to verify and save changed bytes after every replacement is planned.\n * @returns Configuration, sorted changed paths, findings, and independent target failures.\n * Saving reports only paths whose writes succeeded. Check mode reports planned changes.\n * @throws If selection is empty, configuration, worker communication, or cleanup fails.\n */\nexport async function rewriteFiles(\n options: RewriteOptions,\n operation: \"sort\" | \"fixes\",\n write: boolean,\n): Promise<RewriteFilesResult> {\n const config = resolveRewriteConfig(options);\n const worker = new AnalysisWorker();\n try {\n await worker.open(config);\n const files = await worker.targets(options.patterns, true);\n if (!files.length) {\n throw new Error(\"No analysis targets matched the configured scopes\");\n }\n const failures: RewriteFileFailure[] = [];\n const originals = new Map<string, Buffer>();\n const inputs: RewriteInput[] = [];\n const reads = await Promise.allSettled(files.map((file) => readFile(file)));\n for (const [index, read] of reads.entries()) {\n const file = files[index];\n try {\n if (read.status === \"rejected\") {\n throw read.reason;\n }\n const source = read.value.toString(\"utf8\");\n if (!Buffer.from(source).equals(read.value)) {\n throw new Error(`Source is not valid UTF-8: ${file}`);\n }\n originals.set(file, read.value);\n inputs.push({\n file,\n source,\n });\n } catch (error) {\n failures.push({\n file,\n message: error instanceof Error ? error.message : String(error),\n results: [],\n });\n }\n }\n const batch = await worker.rewrite(inputs, operation);\n failures.push(...batch.failures);\n const changes = batch.outputs.map((output) => ({\n file: output.file,\n before: originals.get(output.file)!,\n after: Buffer.from(output.code),\n }));\n let changed = changes\n .filter((change) => !change.before.equals(change.after))\n .map((change) => change.file);\n if (write) {\n const saved = await writeChangedFiles(changes);\n changed = saved.changed;\n failures.push(...saved.failures);\n }\n changed.sort();\n failures.sort((a, b) => a.file.localeCompare(b.file));\n const results = [...batch.outputs, ...batch.failures]\n .flatMap((output) => output.results)\n .sort((a, b) => a.project - b.project || a.result.entry.localeCompare(b.result.entry));\n return {\n config,\n changed,\n results,\n failures,\n };\n } finally {\n await worker.close();\n }\n}\n\n/**\n * Resolves an explicit configuration path or searches above the chosen working directory.\n *\n * @param options - Optional config path and cwd, defaulting to process.cwd().\n * @returns An absolute path. Explicit paths are resolved without evaluating the configuration.\n * @throws If discovery finds no configuration.\n */\nexport function resolveRewriteConfig(options: RewriteOptions): string {\n const cwd = options.cwd ?? process.cwd();\n const config = options.config ? path.resolve(cwd, options.config) : findConfiguration(cwd);\n if (!config) {\n throw new Error(`Cannot find Stillwind configuration above ${cwd}`);\n }\n return config;\n}\n","import type { WorkspaceResult } from \"@stillwind/host\";\n\nimport { rewriteFiles, type RewriteOptions } from \"./rewrite-files.ts\";\nimport type { RewriteFileFailure } from \"./rewrite.ts\";\n\n/** Sorting results whose changed paths compare original and final source bytes. */\nexport interface FormatResult {\n /** Absolute path of the evaluated configuration. */\n config: string;\n /** Absolute paths that changed or would change, in sorted order. */\n changed: string[];\n /** Findings from the original sources, in configured project and target order. */\n results: WorkspaceResult[];\n /** Targets that could not be read, rewritten, or saved. */\n failures: RewriteFileFailure[];\n /** Failures return 2. Check mode otherwise returns 1 when any file would change. */\n exitCode: 0 | 1 | 2;\n}\n\n/**\n * Sorts configured targets and saves changed files unless check is true.\n *\n * @param options - Configuration discovery, target filters, and optional check mode.\n * @returns Changed paths, original findings, and failures. Healthy targets continue after a failure.\n * @throws If selection, configuration, worker communication, or cleanup fails.\n */\nexport async function format(\n options: RewriteOptions & {\n /** Whether to report changes without saving them. Defaults to false. */\n check?: boolean;\n } = {},\n): Promise<FormatResult> {\n const result = await rewriteFiles(options, \"sort\", !options.check);\n return {\n ...result,\n exitCode: result.failures.length ? 2 : options.check && result.changed.length ? 1 : 0,\n };\n}\n","import type { DesignCandidate, DesignSystemRequest, DesignToken } from \"@stillwind/host\";\n\nimport { resolveRewriteConfig, type RewriteOptions } from \"./rewrite-files.ts\";\nimport { AnalysisWorker } from \"./worker-client.ts\";\n\n/**\n * Design-system answers from every project of one configuration.\n */\nexport interface DesignSystemAnswer {\n /** Absolute path of the evaluated configuration. */\n config: string;\n /** Tokens in project and name order. */\n tokens: (DesignToken & {\n /** Zero-based project index in the evaluated configuration. */\n project: number;\n })[];\n /** Candidates in project order. */\n candidates: (DesignCandidate & {\n /** Zero-based project index in the evaluated configuration. */\n project: number;\n })[];\n /** Targets without a match in any project. */\n unmatched: string[];\n}\n\n/**\n * Answers a question about each project's design system in a child process.\n *\n * @param options - Configuration discovery. Target globs do not apply.\n * @param request - Theme, utility, or variant request.\n * @returns Answers from every project. Unknown names and unmatched targets are data.\n * @throws If configuration discovery, worker initialization, CSS loading, a plugin, or cleanup fails.\n */\nexport async function designSystem(\n options: Omit<RewriteOptions, \"patterns\">,\n request: DesignSystemRequest,\n): Promise<DesignSystemAnswer> {\n const config = resolveRewriteConfig(options);\n const worker = new AnalysisWorker();\n try {\n await worker.open(config);\n const answers = await worker.request<\n {\n project: number;\n result: {\n tokens: DesignToken[];\n candidates: DesignCandidate[];\n unmatched: string[];\n };\n }[]\n >({\n method: \"designSystem\",\n request,\n });\n return {\n config,\n tokens: answers.flatMap(({ project, result }) =>\n result.tokens.map((token) => ({\n ...token,\n project,\n })),\n ),\n candidates: answers.flatMap(({ project, result }) =>\n result.candidates.map((candidate) => ({\n ...candidate,\n project,\n })),\n ),\n unmatched: request.targets.filter((target) =>\n answers.every(({ result }) => result.unmatched.includes(target)),\n ),\n };\n } finally {\n await worker.close();\n }\n}\n","import { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\n\nimport {\n isStylesheet,\n type EditorRequest,\n type EditorResult,\n type WorkspaceResult,\n} from \"@stillwind/host\";\n\nimport { lintReports } from \"./reports.ts\";\nimport { resolveRewriteConfig, type RewriteOptions } from \"./rewrite-files.ts\";\nimport { AnalysisWorker } from \"./worker-client.ts\";\nimport type { WorkspaceEditorResult } from \"./workspace.ts\";\n\n/**\n * Selects generated CSS by file, line, or position.\n */\nexport interface InspectTarget {\n /** Path or glob accepted by target selection. */\n pattern: string;\n /** One-based line. Omission selects the whole file. */\n line?: number;\n /** One-based UTF-16 column. It requires line. */\n column?: number;\n}\n\n/**\n * Generated CSS for one source range in one project.\n */\nexport interface InspectPreview {\n /** Zero-based project index in the evaluated configuration. */\n project: number;\n /** Original document range with zero-based lines and UTF-16 columns, and an exclusive end. */\n location: {\n uri: string;\n startLine: number;\n startColumn: number;\n endLine: number;\n endColumn: number;\n };\n /** Original source text in the range. */\n source: string;\n /** Formatted CSS. It is empty for a failed occurrence or a marker class. */\n css: string;\n /** False when diagnostics contains an error, or when a required style failed. */\n valid: boolean;\n /** Reports whose primary range overlaps this range. CSS omits the utilities that they reject. */\n diagnostics: {\n /** Report severity, as in the reports of lint. */\n severity: string;\n /** Stable compiler code or lint rule. */\n code: string;\n /** Description of the finding. */\n message: string;\n }[];\n /** Markdown for a marker class. */\n documentation?: string;\n /** Authored runtime key expressions that the CSS depends on. */\n runtimeNames?: string[];\n}\n\n/**\n * An editor answer with a source range. Hovers omit valid because they describe generated CSS.\n */\ntype PreviewRange = NonNullable<EditorResult[\"hover\"]> & {\n valid?: boolean;\n};\n\n/**\n * A target that could not be read.\n */\nexport interface InspectFailure {\n /** Absolute path of the target. */\n file: string;\n /** Reason for the failure. */\n message: string;\n}\n\n/**\n * Inspection results with analysis outcomes retained for each project.\n */\nexport interface InspectResult {\n /** Absolute path of the evaluated configuration. */\n config: string;\n /** Analysis of each selected file, in file and project order. */\n results: WorkspaceResult[];\n /** Selected previews in file, project, and source order, without repeated ranges. */\n previews: InspectPreview[];\n /** Targets that could not be read. */\n failures: InspectFailure[];\n}\n\n/**\n * Parses a command-line target with an optional `:line` or `:line:column` suffix.\n *\n * @param target - Path or glob, including absolute Windows paths.\n * @returns The pattern and any one-based position.\n * @throws If the position is not positive or the target names a stylesheet.\n */\nexport function parseInspectTarget(target: string): InspectTarget {\n const [, pattern, line, column] = /^(.+?)(?::(\\d+)(?::(\\d+))?)?$/s.exec(target) ?? [];\n if (!pattern || /^0+$/.test(line ?? \"\") || /^0+$/.test(column ?? \"\")) {\n throw new Error(`Invalid inspect target: ${target}`);\n }\n if (isStylesheet(pattern)) {\n throw new Error(`inspect does not accept stylesheets: ${target}`);\n }\n return {\n pattern,\n ...(line ? { line: Number(line) } : {}),\n ...(column ? { column: Number(column) } : {}),\n };\n}\n\n/**\n * Finds the UTF-16 offset of the start of each line.\n *\n * @param source - Document text. Lines end at `\\n`, so `\\r\\n` remains one line break.\n * @returns Ascending offsets, beginning with zero.\n */\nfunction lineOffsets(source: string): number[] {\n const offsets = [0];\n for (let index = source.indexOf(\"\\n\"); index >= 0; index = source.indexOf(\"\\n\", index + 1)) {\n offsets.push(index + 1);\n }\n return offsets;\n}\n\n/**\n * Converts an offset to a position.\n *\n * @param lines - Result of {@link lineOffsets}.\n * @param offset - UTF-16 offset in the same document.\n * @returns The zero-based line and column.\n */\nfunction position(lines: readonly number[], offset: number) {\n let line = lines.length - 1;\n while (lines[line] > offset) {\n line--;\n }\n return {\n line,\n column: offset - lines[line],\n };\n}\n\n/**\n * Checks whether a report location belongs to a file.\n *\n * @param uri - File URI or path.\n * @param file - Absolute path.\n * @returns Whether both name the same path.\n */\nfunction isDocument(uri: string, file: string): boolean {\n return path.resolve(uri.startsWith(\"file:\") ? fileURLToPath(uri) : uri) === path.resolve(file);\n}\n\n/**\n * Answers one target for one file.\n *\n * @param worker - Opened worker that owns the file's analysis.\n * @param file - Absolute target path.\n * @param source - Text of the file.\n * @param target - Position to select. Positions outside the file select nothing.\n * @param reports - Reports with a range in this file, for each project.\n * @returns Previews with their project, in project and source order.\n * @throws If the editor query fails.\n */\nasync function selectPreviews(\n worker: AnalysisWorker,\n file: string,\n source: string,\n target: InspectTarget,\n reports: ReturnType<typeof lintReports>,\n): Promise<InspectPreview[]> {\n const lines = lineOffsets(source);\n const line = target.line === undefined ? undefined : target.line - 1;\n const lineStart = line === undefined ? undefined : lines[line];\n const lineEnd = line === undefined ? undefined : (lines[line + 1] ?? source.length + 1) - 1;\n if (line !== undefined && lineStart === undefined) {\n return [];\n }\n const offset = target.column === undefined ? undefined : lineStart! + target.column - 1;\n if (offset !== undefined && offset > lineEnd!) {\n return [];\n }\n const query = (request: EditorRequest) =>\n worker.request<WorkspaceEditorResult[]>({ method: \"query\", file, request });\n const uri = pathToFileURL(file).href;\n let selected: { project: number; range: PreviewRange }[];\n if (offset === undefined) {\n selected = (\n await query({\n kind: \"previews\",\n })\n ).flatMap(({ project, result }) =>\n (result.previews ?? [])\n .filter(({ start, end }) => line === undefined || (end > lineStart! && start <= lineEnd!))\n .map((range) => ({\n project,\n range,\n })),\n );\n } else {\n const hovers = await query({\n kind: \"hover\",\n offset,\n });\n selected = hovers.flatMap(({ project, result }) =>\n result.hover ? [{ project, range: result.hover }] : [],\n );\n if (selected.length < hovers.length) {\n // Failed occurrences and Vue template expressions have no hover, so the listing supplies them.\n const answered = new Set(selected.map(({ project }) => project));\n selected.push(\n ...(\n await query({\n kind: \"previews\",\n })\n ).flatMap(({ project, result }) =>\n answered.has(project)\n ? []\n : (result.previews ?? [])\n .filter(({ start, end }) => start <= offset && offset <= end)\n .map((range) => ({\n project,\n range,\n })),\n ),\n );\n }\n }\n return selected.flatMap(\n ({ project, range: { start, end, css, valid = true, documentation, runtimeNames } }) => {\n const diagnostics = reports\n .filter(\n ({ project: owner, report: { primary } }) =>\n owner === project &&\n primary.location.startUtf16 < end &&\n start < Math.max(primary.location.endUtf16, primary.location.startUtf16 + 1),\n )\n .map(({ report: { severity, code, message } }) => ({ severity, code, message }));\n if (!css && valid && !diagnostics.length && !documentation) {\n return [];\n }\n const first = position(lines, start);\n const last = position(lines, end);\n return [\n {\n project,\n location: {\n uri,\n startLine: first.line,\n startColumn: first.column,\n endLine: last.line,\n endColumn: last.column,\n },\n source: source.slice(start, end),\n css,\n valid: valid && !diagnostics.some(({ severity }) => severity === \"error\"),\n diagnostics,\n ...(documentation ? { documentation } : {}),\n ...(runtimeNames ? { runtimeNames } : {}),\n },\n ];\n },\n );\n}\n\n/**\n * Reports the generated CSS of configured source files in a child process.\n *\n * @param options - Configuration discovery and targets. Paths and globs follow the target rules\n * of lint. Stylesheets are not accepted, and an empty list selects every configured source file.\n * @returns Previews and analysis results. A file with incomplete analysis has no previews.\n * @throws If a target is invalid or matches no file, or if configuration discovery, worker\n * initialization, target enumeration, or cleanup fails.\n */\nexport async function inspect(\n options: Omit<RewriteOptions, \"patterns\"> & {\n /** Targets as written on the command line. */\n targets?: readonly string[];\n } = {},\n): Promise<InspectResult> {\n const targets = (options.targets ?? []).map(parseInspectTarget);\n const config = resolveRewriteConfig(options);\n const worker = new AnalysisWorker();\n try {\n await worker.open(config);\n const selections = new Map<string, InspectTarget[]>();\n for (const target of targets.length ? targets : [undefined]) {\n const files = (await worker.targets(target ? [target.pattern] : undefined)).filter(\n (file) => !isStylesheet(file),\n );\n if (!files.length) {\n throw new Error(\n target\n ? `No analysis targets matched ${target.pattern}`\n : \"No analysis targets matched the configured scopes\",\n );\n }\n for (const file of files) {\n selections.set(file, [\n ...(selections.get(file) ?? []),\n target ?? {\n pattern: file,\n },\n ]);\n }\n }\n const files = [...selections.keys()].sort();\n await worker.request({\n method: \"prepare\",\n files,\n });\n\n const result: InspectResult = {\n config,\n results: [],\n previews: [],\n failures: [],\n };\n for (const file of files) {\n const analyses = await worker.analyze(file);\n result.results.push(...analyses);\n const complete = new Set(\n analyses.filter(({ result }) => result.status === \"complete\").map(({ project }) => project),\n );\n let source: string;\n try {\n const bytes = await readFile(file);\n source = bytes.toString(\"utf8\");\n if (!Buffer.from(source).equals(bytes)) {\n throw new Error(`Source is not valid UTF-8: ${file}`);\n }\n } catch (error) {\n result.failures.push({\n file,\n message: error instanceof Error ? error.message : String(error),\n });\n continue;\n }\n const reports = lintReports(analyses).filter(\n ({ report }) =>\n report.primary.scope === \"range\" && isDocument(report.primary.location.uri, file),\n );\n const seen = new Set<string>();\n const previews: InspectPreview[] = [];\n for (const target of selections.get(file)!) {\n for (const preview of await selectPreviews(worker, file, source, target, reports)) {\n const { startLine, startColumn, endLine, endColumn } = preview.location;\n const key = [preview.project, startLine, startColumn, endLine, endColumn].join();\n if (complete.has(preview.project) && !seen.has(key)) {\n seen.add(key);\n previews.push(preview);\n }\n }\n }\n result.previews.push(\n ...previews.sort(\n (a, b) =>\n a.project - b.project ||\n a.location.startLine - b.location.startLine ||\n a.location.startColumn - b.location.startColumn,\n ),\n );\n }\n return result;\n } finally {\n await worker.close();\n }\n}\n","import type { WorkspaceResult } from \"@stillwind/host\";\n\nimport { lintReports } from \"./reports.ts\";\nimport { resolveRewriteConfig, rewriteFiles, type RewriteOptions } from \"./rewrite-files.ts\";\nimport type { RewriteFileFailure } from \"./rewrite.ts\";\nimport { AnalysisWorker } from \"./worker-client.ts\";\n\n/** Lint results preserve project membership and identify incomplete analysis. */\nexport interface LintResult {\n /** Absolute path of the evaluated configuration. */\n config: string;\n /** Target results in configured project order, including overlapping project memberships. */\n results: WorkspaceResult[];\n /** Files whose bytes changed when fix was requested. */\n changed?: string[];\n /** Targets that could not be read, fixed, or saved when fix was requested. */\n failures?: RewriteFileFailure[];\n /**\n * - 0: successful checks\n * - 1: compiler errors or denied lint\n * - 2: incomplete execution\n */\n exitCode: 0 | 1 | 2;\n}\n\n/**\n * Analyzes configured target scopes in a child process and closes it before returning.\n *\n * @param options - Configuration discovery and optional target filters. Omission checks all\n * configured targets from the process working directory.\n * @returns Results and an exit code. Readonly lint returns code 2 for empty selection or incomplete analysis.\n * @throws If configuration discovery, worker initialization, target enumeration, or cleanup fails.\n * Fix mode reports failures per target and continues with healthy targets. Empty selection throws.\n */\nexport async function lint(\n options: RewriteOptions & {\n /** Applies converged fixes and reports findings from the final source buffers. */\n fix?: boolean;\n } = {},\n): Promise<LintResult> {\n if (options.fix) {\n const result = await rewriteFiles(options, \"fixes\", true);\n return {\n ...result,\n exitCode: result.failures.length\n ? 2\n : result.results.some(({ result }) =>\n result.reports.some((report) => report.severity === \"error\"),\n )\n ? 1\n : 0,\n };\n }\n const config = resolveRewriteConfig(options);\n const worker = new AnalysisWorker();\n try {\n await worker.open(config);\n const results = await worker.lint(options.patterns);\n const exitCode =\n !results.length || results.some(({ result }) => result.status !== \"complete\")\n ? 2\n : results.some(({ result }) => result.reports.some((report) => report.severity === \"error\"))\n ? 1\n : 0;\n return { config, results, exitCode };\n } finally {\n await worker.close();\n }\n}\n\n/**\n * Formats findings and incomplete analysis for terminal output.\n *\n * @param result - Lint results whose reports use original document locations.\n * @returns Text with one-based line and column positions. Duplicate findings are removed per\n * project. Findings from overlapping projects remain separate. Successful results can return empty text.\n */\nexport function formatLint(result: LintResult): string {\n const lines: string[] = [];\n for (const { project, report } of lintReports(result.results)) {\n const location = report.primary.location;\n const at =\n report.primary.scope === \"document\"\n ? location.uri\n : `${location.uri}:${location.startLine + 1}:${location.startColumn + 1}`;\n lines.push(\n `[project ${project + 1}] ${at}: ${report.severity} ${report.code}: ${report.message}`,\n );\n for (const related of report.related) {\n lines.push(\n ` ${related.location.uri}:${related.location.startLine + 1}:${related.location.startColumn + 1}${related.message ? `: ${related.message}` : \"\"}`,\n );\n }\n lines.push(...report.notes.map((note) => ` ${note}`));\n }\n for (const entry of result.results) {\n if (entry.result.status !== \"complete\") {\n lines.push(\n `[project ${entry.project + 1}] ${entry.result.entry}: incomplete analysis${entry.result.error ? `: ${entry.result.error}` : \"\"}`,\n );\n for (const dependency of entry.result.graph?.dependencies ?? []) {\n if (dependency.status === \"unresolved\" || dependency.status === \"unsupported\") {\n lines.push(` ${dependency.status}: ${dependency.specifier} from ${dependency.importer}`);\n }\n }\n for (const range of entry.result.graph?.unverified ?? []) {\n lines.push(\n ` unverified: ${range.moduleId}${range.start === undefined ? \"\" : `:${range.start}-${range.end}`}: ${range.reason}`,\n );\n }\n }\n }\n for (const failure of result.failures ?? []) {\n if (!failure.results.some(({ result }) => result.status !== \"complete\")) {\n lines.push(`${failure.file}: ${failure.message}`);\n }\n }\n if (!result.results.length && !result.failures?.length) {\n lines.push(\"No analysis targets matched the configured scopes\");\n }\n return lines.join(\"\\n\");\n}\n","import path from \"node:path\";\nimport process from \"node:process\";\nimport { fileURLToPath } from \"node:url\";\n\nimport { findConfiguration, findDocumentConfiguration } from \"@stillwind/config/node\";\n\nimport { AnalysisWorker } from \"./worker-client.ts\";\nimport type {\n AnalysisWorkspaceContext,\n AnalysisWorkspaceService,\n OpenAnalysisWorkspaces,\n WorkspaceEditorResult,\n} from \"./workspace.ts\";\n\n/**\n * Lists the directories that bound configuration discovery.\n *\n * @param context - Workspace directory URIs.\n * @returns Absolute paths of the file URIs, or the process working directory for an empty list.\n * @throws If converting a malformed file URI fails.\n */\nfunction folderPaths(context: AnalysisWorkspaceContext): string[] {\n return context.workspaceFolders.length\n ? context.workspaceFolders\n .filter((uri) => uri.startsWith(\"file:\"))\n .map((uri) => fileURLToPath(uri))\n : [process.cwd()];\n}\n\n/**\n * Opens one isolated Node analysis process for each distinct configuration.\n *\n * @param context - Workspace directory URIs. File URIs use upward configuration discovery, and a\n * folder without a configuration opens no service. Other URI schemes cannot open Node workspaces.\n * An empty list uses the process working directory.\n * @param config - Optional explicit configuration path, resolved from the process working directory.\n * When supplied, it replaces discovery from workspace folders.\n * @returns Services keyed by absolute configuration path and separate initialization errors.\n * Services accept file URIs, forward buffers to their workers, and discard cancelled results.\n * @throws If converting a malformed file URI or closing a failed worker throws.\n */\nexport async function openNodeWorkspaces(\n context: AnalysisWorkspaceContext,\n config?: string,\n): Promise<OpenAnalysisWorkspaces> {\n const workspaces = new Map<string, AnalysisWorkspaceService>();\n const errors = new Map<string, string>();\n\n const paths = config\n ? [path.resolve(config)]\n : folderPaths(context).map((folder) => findConfiguration(folder));\n for (const file of new Set(paths.filter((file): file is string => Boolean(file)))) {\n await openConfiguration(file, workspaces, errors);\n }\n\n return {\n workspaces,\n errors,\n };\n}\n\n/**\n * Opens the nearest configuration of a document that no open service covers.\n *\n * @param uri - Document URI. Other schemes than `file:` open nothing.\n * @param context - Workspace directory URIs that bound the search.\n * @param known - Configuration paths that already have a service or an attempt.\n * @returns The new service and any initialization error, or undefined when the document has no\n * new configuration.\n * @throws If converting a malformed file URI or closing a failed worker throws.\n */\nexport async function discoverNodeWorkspace(\n uri: string,\n context: AnalysisWorkspaceContext,\n known: ReadonlySet<string>,\n): Promise<OpenAnalysisWorkspaces | undefined> {\n if (!uri.startsWith(\"file:\")) {\n return undefined;\n }\n const file = findDocumentConfiguration(fileURLToPath(uri), folderPaths(context));\n if (!file || known.has(file)) {\n return undefined;\n }\n const workspaces = new Map<string, AnalysisWorkspaceService>();\n const errors = new Map<string, string>();\n await openConfiguration(file, workspaces, errors);\n return {\n workspaces,\n errors,\n };\n}\n\n/**\n * Starts one analysis process and records its service or its initialization failure.\n *\n * @param file - Absolute configuration path.\n * @param workspaces - Receives the service keyed by file.\n * @param errors - Receives the failure message keyed by file.\n * @throws If closing a failed worker throws.\n */\nasync function openConfiguration(\n file: string,\n workspaces: Map<string, AnalysisWorkspaceService>,\n errors: Map<string, string>,\n): Promise<void> {\n const worker = new AnalysisWorker();\n try {\n await worker.open(file);\n /**\n * Selects document identities that can be forwarded to the filesystem worker.\n *\n * @param uri - Document URI whose syntax is validated later by `fileURLToPath`.\n * @returns Whether the URI begins with the `file:` scheme.\n */\n const accepts = (uri: string) => uri.startsWith(\"file:\");\n workspaces.set(file, {\n refresh: (uris) =>\n worker.request<boolean>({\n method: \"refresh\",\n files: uris.filter(accepts).map((uri) => fileURLToPath(uri)),\n }),\n affects: (uris) =>\n worker.request<boolean>({\n method: \"affects\",\n files: uris.filter(accepts).map((uri) => fileURLToPath(uri)),\n }),\n prepare: async (uris, signal) => {\n if (!signal?.aborted) {\n await worker.request({\n method: \"prepare\",\n files: uris.filter(accepts).map((uri) => fileURLToPath(uri)),\n });\n }\n },\n query: async (uri, request, signal) => {\n if (!accepts(uri) || signal?.aborted) {\n return [];\n }\n const results = await worker.request<WorkspaceEditorResult[]>({\n method: \"query\",\n file: fileURLToPath(uri),\n request,\n });\n return signal?.aborted ? [] : results;\n },\n update: async (uri, source, version) => {\n if (accepts(uri)) {\n await worker.request({\n method: \"update\",\n file: fileURLToPath(uri),\n source,\n version,\n });\n }\n },\n analyze: async (uri, signal) => {\n if (!accepts(uri) || signal?.aborted) {\n return [];\n }\n const results = await worker.analyze(fileURLToPath(uri));\n return signal?.aborted\n ? []\n : results.map(({ project, config, result }) => ({\n project,\n config,\n result: {\n entry: result.entry,\n revision: result.revision,\n status: result.status,\n reports: result.reports,\n error: result.error,\n dependencies: result.graph?.dependencies,\n unverified: result.graph?.unverified,\n generation: result.graph?.generation,\n },\n }));\n },\n closeDocument: async (uri) => {\n if (accepts(uri)) {\n await worker.request({\n method: \"closeDocument\",\n file: fileURLToPath(uri),\n });\n }\n },\n close: async () => {\n await worker.close();\n },\n });\n } catch (error) {\n errors.set(file, String(error));\n await worker.close();\n }\n}\n","import path from \"node:path\";\n\nimport { findConfiguration } from \"@stillwind/config/node\";\n\nimport { RewriteFailure, type RewriteInput, type RewriteResult } from \"./rewrite.ts\";\nimport { AnalysisWorker } from \"./worker-client.ts\";\n\n/**\n * Reuses an isolated process while refreshing trusted configuration for each formatting request.\n */\nexport class SourceFormatter {\n /** Child process reused across formatting requests and owned until close completes. */\n readonly #worker = new AnalysisWorker();\n /** Serializes requests while allowing a new request after a preceding failure. */\n #queue: Promise<unknown> = Promise.resolve();\n\n /**\n * Starts the isolated worker that evaluates configuration on each formatting request.\n *\n * @param config - Configuration path resolved in the worker's inherited working directory.\n */\n constructor(private readonly config: string) {}\n\n /**\n * Sorts the supplied buffer with current project settings.\n * Files outside all configured scopes return unchanged text. Requests are serialized and never write files.\n *\n * @param input - Original buffer and optional protected ranges. Relative paths are resolved from cwd.\n * @returns The sorted buffer and original findings after configuration is reopened.\n * @throws If configuration loading, parsing, analysis, project agreement, rewriting, or worker communication fails.\n */\n format(input: RewriteInput): Promise<RewriteResult> {\n const task = this.#queue.then(async () => {\n await this.#worker.open(this.config);\n const { outputs, failures } = await this.#worker.rewrite(\n [\n {\n ...input,\n file: path.resolve(input.file),\n },\n ],\n \"sort\",\n );\n if (failures.length) {\n throw new RewriteFailure(failures[0].message, failures[0].results);\n }\n return outputs[0];\n });\n this.#queue = task.catch(() => {});\n return task;\n }\n\n /**\n * Waits for queued formatting and releases the child process. Stop submitting requests before closure.\n *\n * @returns Completion of worker cleanup.\n * @throws If the worker's cleanup request fails.\n */\n async close(): Promise<void> {\n await this.#queue;\n await this.#worker.close();\n }\n}\n\n/**\n * Finds a configuration above a source file or resolves an explicit path from cwd.\n *\n * @param file - Source path whose parent starts upward discovery. Relative paths use cwd.\n * @param config - Optional explicit configuration path, returned without an existence check.\n * @returns The absolute configuration path, or undefined when discovery finds none.\n */\nexport function findFormatterConfig(file: string, config?: string): string | undefined {\n if (config) {\n return path.resolve(config);\n }\n return findConfiguration(path.dirname(path.resolve(file)));\n}\n"],"mappings":";;;;;;;;;;;AAmHA,IAAa,iBAAb,MAA4B;;CAE1B;;CAEA,2BAAoB,IAAI,IAQtB;;CAEF;;CAGA,UAAU;;CAEV,UAAU;;CAEV,WAAW;;;;CAKX,cAAc;EACZ,KAAK,SAAS,KAAK,cAAc,IAAI,IAAI,eAAe,YAAY,GAAG,CAAC,GAAG,CAAC,GAAG;GAC7E,OAAO;IAAC;IAAU;IAAQ;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,SAAS,QACX,MAAM,IAAI,eAAe,SAAS,EAAE,CAAC,SAAS,SAAS,EAAE,CAAC,OAAO;GAEnE,OAAO,QAAQ;EACjB,CAAC;EACD,KAAK,SAAS,KAAK,YAAY,CAAC,CAAC;EACjC,OAAO;CACT;;;;;;;CAQA,MAAM,QAAuB;EAC3B,MAAM,KAAK;EACX,MAAM,KAAK,QAAQ,MAAM;CAC3B;AACF;;;;;;;;AASA,SAAgB,oBAAoB,MAAc,QAAqC;CACrF,IAAI,QACF,OAAO,KAAK,QAAQ,MAAM;CAE5B,OAAO,kBAAkB,KAAK,QAAQ,KAAK,QAAQ,IAAI,CAAC,CAAC;AAC3D"}
1
+ {"version":3,"file":"node.js","names":["process"],"sources":["../src/worker-client.ts","../src/write.ts","../src/rewrite-files.ts","../src/check.ts","../src/design-system.ts","../src/format.ts","../src/info.ts","../src/inspect.ts","../src/lint.ts","../src/node-workspace.ts","../src/source-formatter.ts"],"sourcesContent":["import { fork, type ChildProcess } from \"node:child_process\";\nimport process from \"node:process\";\nimport { fileURLToPath } from \"node:url\";\n\nimport type { DesignSystemRequest, EditorRequest, WorkspaceResult } from \"@stillwind/host\";\n\nimport type { HookRunOptions } from \"./hooks.ts\";\nimport {\n RewriteFailure,\n type RewriteBatchResult,\n type RewriteInput,\n type RewriteOperation,\n} from \"./rewrite.ts\";\n\n/**\n * Requests sent to the process that owns trusted config evaluation and plugin lifetimes.\n */\nexport type WorkerRequest =\n | {\n /** Serialized discriminator for replacing the child workspace. */\n method: \"open\";\n /** Configuration path evaluated in the child process, replacing any previously opened workspace. */\n config: string;\n }\n | {\n /** Serialized discriminator for analyzing configured targets. */\n method: \"lint\";\n /** Additional target globs relative to each project root. Omission checks all configured targets. */\n patterns?: readonly string[];\n }\n | {\n /** Serialized discriminator for enumerating distinct targets. */\n method: \"targets\";\n /** Additional project-relative globs. An empty or omitted list keeps every configured target. */\n patterns?: readonly string[];\n /** Adds the stylesheets that each project lints. */\n stylesheets?: boolean;\n }\n | {\n /** Serialized discriminator for computing source replacements. */\n method: \"rewrite\";\n /** Distinct absolute target paths and captured text, retained in result order. */\n inputs: readonly RewriteInput[];\n /** Selects one sort pass, lint fixes that must converge, or converged fixes followed by sorting. */\n operation: RewriteOperation;\n /** Optional hook execution mode for CLI commands. Omission skips project hooks. */\n hooks?: HookRunOptions;\n }\n | {\n /** Serialized discriminator for preparing a batch of targets. */\n method: \"prepare\";\n /** Absolute target paths. */\n files: readonly string[];\n }\n | {\n /** Serialized discriminator for analyzing one target in matching projects. */\n method: \"analyze\";\n /** Absolute target path. Each project whose scope contains the file returns a result. */\n file: string;\n }\n | {\n /** Serialized discriminator for an editor query against original text. */\n method: \"query\";\n /** Absolute target file path. */\n file: string;\n /** Editor operation in original UTF-16 coordinates. */\n request: EditorRequest;\n }\n | {\n /** Serialized discriminator for reading resolved project metadata. */\n method: \"info\";\n }\n | {\n /** Serialized discriminator for a question about each project's design system. */\n method: \"designSystem\";\n /** Theme, utility, or variant request. */\n request: DesignSystemRequest;\n }\n | {\n /** Serialized discriminator for replacing an unsaved buffer. */\n method: \"update\";\n /** Absolute source path, including dependencies outside target scopes. */\n file: string;\n /** Complete unsaved source text. */\n source: string;\n /** Safe integer that increases while this file is open. */\n version: number;\n }\n | {\n /** Serialized discriminator for removing an unsaved buffer. */\n method: \"closeDocument\";\n /** Absolute path of the buffer to remove. Unknown files have no effect. */\n file: string;\n }\n | {\n /** Serialized discriminator for checking whether the caller needs to reopen the workspace. */\n method: \"refresh\";\n /** Absolute file paths reported by save or watch notifications. */\n files: readonly string[];\n }\n | {\n /** Serialized discriminator for checking whether file changes can change results. */\n method: \"affects\";\n /** Absolute file paths reported by watch notifications. */\n files: readonly string[];\n }\n | {\n /** Serialized discriminator for refreshing disk and compiler caches. */\n method: \"invalidate\";\n }\n | {\n /** Serialized discriminator for closing hosts and disconnecting the child. */\n method: \"close\";\n };\n\n/**\n * IPC response correlated with one request. Successful void operations can omit value.\n */\nexport interface WorkerReply {\n /** Request sequence number assigned by AnalysisWorker. */\n id: number;\n /** Serialized operation result when error is absent. */\n value?: unknown;\n /** Exception message and any analysis results that prevented a rewrite. */\n error?: {\n message: string;\n results?: WorkspaceResult[];\n };\n}\n\n/**\n * Isolates configuration and plugin logs from CLI JSON and the LSP stdout transport.\n */\nexport class AnalysisWorker {\n /** Owned child with IPC enabled. Both output streams are forwarded to the parent's stderr. */\n readonly #child: ChildProcess;\n /** Unanswered requests keyed by monotonically assigned IPC sequence number. */\n readonly #pending = new Map<\n number,\n {\n /** Settles the request with the child's unvalidated reply value. */\n resolve: (value: unknown) => void;\n /** Rejects the request after delivery, child-operation, or process failure. */\n reject: (error: Error) => void;\n }\n >();\n /** Resolves on process closure after outstanding requests have been rejected. */\n readonly #closed: Promise<void>;\n\n /** Next IPC sequence number, independent of source document versions. */\n #nextId = 0;\n /** Whether process closure has been observed. */\n #exited = false;\n /** Prevents repeated close calls from sending another cleanup request. */\n #closing = false;\n\n /**\n * Starts the child process immediately. Call open before analysis and close when finished.\n */\n constructor() {\n this.#child = fork(fileURLToPath(new URL(\"./worker.js\", import.meta.url)), [], {\n stdio: [\"ignore\", \"pipe\", \"pipe\", \"ipc\"],\n execArgv: [],\n windowsHide: true,\n });\n this.#child.stdout!.on(\"data\", (data: Buffer) => {\n process.stderr.write(data);\n });\n this.#child.stderr!.on(\"data\", (data: Buffer) => {\n process.stderr.write(data);\n });\n this.#child.on(\"message\", (reply: WorkerReply) => {\n const request = this.#pending.get(reply.id);\n this.#pending.delete(reply.id);\n if (reply.error) {\n request?.reject(\n reply.error.results\n ? new RewriteFailure(reply.error.message, reply.error.results)\n : new Error(reply.error.message),\n );\n } else {\n request?.resolve(reply.value);\n }\n });\n this.#child.on(\"error\", (error) => {\n for (const request of this.#pending.values()) {\n request.reject(error);\n }\n this.#pending.clear();\n });\n this.#closed = new Promise((resolve) => {\n this.#child.on(\"close\", (code, signal) => {\n this.#exited = true;\n for (const request of this.#pending.values()) {\n request.reject(new Error(`Stillwind analysis worker closed (${code ?? signal})`));\n }\n this.#pending.clear();\n resolve();\n });\n });\n }\n\n /**\n * Sends an IPC operation and correlates its reply. Calls are not serialized here.\n *\n * @param request - Operation payload. Await open before using workspace operations, and avoid\n * overlapping replacement or closure with analysis requests.\n * @returns The reply value cast to T. The caller must choose T to match the operation's result.\n * @throws If the child is closed, IPC delivery fails, or the child operation reports an error.\n */\n async request<T = void>(request: WorkerRequest): Promise<T> {\n if (this.#exited) {\n throw new Error(\"Stillwind analysis worker is closed\");\n }\n const id = this.#nextId++;\n return (await new Promise<unknown>((resolve, reject) => {\n this.#pending.set(id, { resolve, reject });\n this.#child.send({ id, request }, (error) => {\n if (error) {\n this.#pending.delete(id);\n reject(error);\n }\n });\n })) as T;\n }\n\n /**\n * Replaces the child workspace, closing any previously opened hosts first.\n *\n * @param config - Configuration path. Relative paths use the child's inherited working directory.\n * @returns A promise that resolves after the configuration and project hosts have opened.\n * @throws If configuration evaluation, project initialization, or transport fails.\n */\n async open(config: string): Promise<void> {\n await this.request({\n method: \"open\",\n config,\n });\n }\n\n /**\n * Analyzes a target in each matching project of the opened workspace.\n *\n * @param file - Absolute target path. Unsaved buffers use preceding update requests.\n * @returns Scoped results in project order, or an empty list when no scope includes the target.\n * @throws If the workspace has not opened or transport fails.\n */\n analyze(file: string): Promise<WorkspaceResult[]> {\n return this.request({\n method: \"analyze\",\n file,\n });\n }\n\n /**\n * Enumerates and analyzes targets in the opened workspace.\n *\n * @param patterns - Additional globs relative to each project root. Empty or omitted filters\n * retain every configured target.\n * @returns Results in project order and sorted target order within each project.\n * @throws If the workspace has not opened, enumeration fails, or transport fails.\n */\n lint(patterns?: readonly string[]): Promise<WorkspaceResult[]> {\n return this.request({\n method: \"lint\",\n patterns,\n });\n }\n\n /**\n * Enumerates distinct targets in the opened workspace.\n *\n * @param patterns - Additional project-relative globs. Omission or an empty list retains all targets.\n * @param stylesheets - Adds the stylesheets that each project lints.\n * @returns Sorted absolute paths, deduplicated across projects.\n * @throws If the workspace has not opened, enumeration fails, or transport fails.\n */\n targets(patterns?: readonly string[], stylesheets?: boolean): Promise<string[]> {\n return this.request({\n method: \"targets\",\n patterns,\n stylesheets,\n });\n }\n\n /**\n * Computes replacements from captured buffers without writing files.\n *\n * @param inputs - Distinct absolute target paths and complete original text.\n * @param operation - Utility sorting or lint fixes, limited to ten changing passes per target.\n * @returns Successful replacements and target failures in input order. Captured buffers are removed after planning.\n * @throws If workspace setup, buffer installation, cleanup, or transport fails.\n */\n rewrite(\n inputs: readonly RewriteInput[],\n operation: RewriteOperation,\n hooks?: HookRunOptions,\n ): Promise<RewriteBatchResult> {\n return this.request({\n method: \"rewrite\",\n inputs,\n operation,\n hooks,\n });\n }\n\n /**\n * Requests host cleanup and waits for the child process to close. After the cleanup request\n * settles, a child that remains alive for five seconds is terminated.\n *\n * @returns A promise that resolves after process closure. Repeated calls wait for that closure.\n * @throws If the initial cleanup request or its transport fails.\n */\n async close(): Promise<void> {\n if (this.#closing || this.#exited) {\n await this.#closed;\n return;\n }\n this.#closing = true;\n try {\n await this.request({\n method: \"close\",\n });\n } finally {\n const timer = setTimeout(() => {\n this.#child.kill();\n }, 5000);\n await this.#closed;\n clearTimeout(timer);\n }\n }\n}\n","import { readFile, writeFile } from \"node:fs/promises\";\n\nimport type { RewriteFileFailure } from \"./rewrite.ts\";\n\n/**\n * A replacement with the original bytes retained for verification before saving.\n */\nexport interface FileChange {\n /** Target path. The caller must provide at most one change per file. */\n file: string;\n /** Bytes captured before planning, compared against disk before saving. */\n before: Buffer;\n /** Planned replacement bytes. Equal bytes skip verification and writing. */\n after: Buffer;\n}\n\n/**\n * Saves changed bytes once per file. Identical buffers perform no filesystem operations.\n * Checks each original immediately before saving and continues after a target fails.\n *\n * @param changes - Distinct target paths and original/replacement bytes. Buffers remain unchanged.\n * @returns Saved paths and failures. A stale file is left unchanged.\n */\nexport async function writeChangedFiles(changes: readonly FileChange[]): Promise<{\n changed: string[];\n failures: RewriteFileFailure[];\n}> {\n const changed = changes.filter((change) => !change.before.equals(change.after));\n const saved: string[] = [];\n const failures: RewriteFileFailure[] = [];\n for (const change of changed) {\n try {\n if (!(await readFile(change.file)).equals(change.before)) {\n throw new Error(`Source changed before saving ${change.file}`);\n }\n await writeFile(change.file, change.after);\n saved.push(change.file);\n } catch (error) {\n failures.push({\n file: change.file,\n message: error instanceof Error ? error.message : String(error),\n results: [],\n });\n }\n }\n return {\n changed: saved,\n failures,\n };\n}\n","import { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { findConfiguration } from \"@stillwind/config/node\";\nimport type { WorkspaceResult } from \"@stillwind/host\";\n\nimport type { HookRunOptions } from \"./hooks.ts\";\nimport type { RewriteFileFailure, RewriteInput, RewriteOperation } from \"./rewrite.ts\";\nimport { AnalysisWorker } from \"./worker-client.ts\";\nimport { writeChangedFiles } from \"./write.ts\";\n\n/**\n * Selects configured source files for CLI analysis and rewriting.\n */\nexport interface RewriteOptions {\n /** Explicit configuration path, absolute or relative to cwd. Omission searches upward from cwd. */\n config?: string;\n /** Directory for configuration discovery and relative config paths. Defaults to process.cwd(). */\n cwd?: string;\n /** Additional globs relative to each project root. Omission or an empty list retains all configured targets. */\n patterns?: string[];\n}\n\n/**\n * A completed rewrite batch with findings kept separately for each owning project.\n */\ninterface RewriteFilesResult {\n /** Absolute configuration path used by the isolated worker. */\n config: string;\n /** Absolute paths whose original and final bytes differ, in sorted order. */\n changed: string[];\n /** Original findings for sorting and final findings for lint fixes, in project and target order. */\n results: WorkspaceResult[];\n /** Targets that could not be read, rewritten, or saved. */\n failures: RewriteFileFailure[];\n}\n\n/**\n * Computes all replacements before optionally saving changed files. Fixes return final findings.\n *\n * @param options - Configuration discovery and optional filters within configured target scopes.\n * @param operation - Utility sorting, converged lint fixes, or converged lint fixes followed by sorting.\n * @param write - Whether to verify and save changed bytes after every replacement is planned.\n * @returns Configuration, sorted changed paths, findings, and independent target failures.\n * Saving reports only paths whose writes succeeded. Check mode reports planned changes.\n * @throws If selection is empty, configuration, worker communication, or cleanup fails.\n */\nexport async function rewriteFiles(\n options: RewriteOptions,\n operation: RewriteOperation,\n write: boolean,\n hooks?: HookRunOptions,\n): Promise<RewriteFilesResult> {\n const config = resolveRewriteConfig(options);\n const worker = new AnalysisWorker();\n try {\n await worker.open(config);\n const files = await worker.targets(options.patterns, true);\n if (!files.length) {\n throw new Error(\"No analysis targets matched the configured scopes\");\n }\n const failures: RewriteFileFailure[] = [];\n const originals = new Map<string, Buffer>();\n const inputs: RewriteInput[] = [];\n const reads = await Promise.allSettled(files.map((file) => readFile(file)));\n for (const [index, read] of reads.entries()) {\n const file = files[index];\n try {\n if (read.status === \"rejected\") {\n throw read.reason;\n }\n const source = read.value.toString(\"utf8\");\n if (!Buffer.from(source).equals(read.value)) {\n throw new Error(`Source is not valid UTF-8: ${file}`);\n }\n originals.set(file, read.value);\n inputs.push({\n file,\n source,\n });\n } catch (error) {\n failures.push({\n file,\n message: error instanceof Error ? error.message : String(error),\n results: [],\n });\n }\n }\n const batch = await worker.rewrite(inputs, operation, hooks);\n failures.push(...batch.failures);\n const changes = batch.outputs.map((output) => ({\n file: output.file,\n before: originals.get(output.file)!,\n after: Buffer.from(output.code),\n }));\n let changed = changes\n .filter((change) => !change.before.equals(change.after))\n .map((change) => change.file);\n if (write) {\n const saved = await writeChangedFiles(changes);\n changed = saved.changed;\n failures.push(...saved.failures);\n }\n changed.sort();\n failures.sort((a, b) => a.file.localeCompare(b.file));\n const results = [...batch.outputs, ...batch.failures]\n .flatMap((output) => output.results)\n .sort((a, b) => a.project - b.project || a.result.entry.localeCompare(b.result.entry));\n return {\n config,\n changed,\n results,\n failures,\n };\n } finally {\n await worker.close();\n }\n}\n\n/**\n * Resolves an explicit configuration path or searches above the chosen working directory.\n *\n * @param options - Optional config path and cwd, defaulting to process.cwd().\n * @returns An absolute path. Explicit paths are resolved without evaluating the configuration.\n * @throws If discovery finds no configuration.\n */\nexport function resolveRewriteConfig(options: RewriteOptions): string {\n const cwd = options.cwd ?? process.cwd();\n const config = options.config ? path.resolve(cwd, options.config) : findConfiguration(cwd);\n if (!config) {\n throw new Error(`Cannot find Stillwind configuration above ${cwd}`);\n }\n return config;\n}\n","import type { WorkspaceResult } from \"@stillwind/host\";\n\nimport { rewriteFiles, type RewriteOptions } from \"./rewrite-files.ts\";\nimport type { RewriteFileFailure } from \"./rewrite.ts\";\n\n/**\n * Combined lint and formatting check results for one configuration.\n */\nexport interface CheckResult {\n /** Absolute path of the evaluated configuration. */\n config: string;\n /** Absolute paths that changed when fix is true, or need sorting when fix is false. */\n changed: string[];\n /** Findings from original sources without fix, or from final sorted sources with fix. */\n results: WorkspaceResult[];\n /** Targets that could not be read, rewritten, or saved. */\n failures: RewriteFileFailure[];\n /**\n * - 0: no failures, no errors, and no unformatted files when fix is false\n * - 1: compiler errors, denied lint, or unformatted files when fix is false\n * - 2: incomplete execution or target failures\n */\n exitCode: 0 | 1 | 2;\n}\n\n/**\n * Runs lint and utility sorting in one worker pass. Without fix, checks formatting and reports\n * findings without saving. With fix, applies converged automatic fixes and utility sorting, saves\n * changed files, and reports findings for the final sources.\n *\n * @param options - Configuration discovery, target filters, and optional fix mode.\n * @returns Changed paths, findings, failures, and exit code. Healthy targets continue after a failure.\n * @throws If selection, configuration, worker communication, or cleanup fails.\n */\nexport async function check(\n options: RewriteOptions & {\n /** Applies converged automatic fixes and utility sorting, and saves changed files. */\n fix?: boolean;\n } = {},\n): Promise<CheckResult> {\n const result = await rewriteFiles(\n options,\n options.fix ? \"fixes-and-sort\" : \"sort\",\n !!options.fix,\n {\n command: \"check\",\n mode: options.fix ? \"write\" : \"check\",\n },\n );\n const hasErrors = result.results.some(({ result: entry }) =>\n entry.reports.some((report) => report.severity === \"error\"),\n );\n return {\n ...result,\n exitCode: result.failures.length\n ? 2\n : hasErrors || (!options.fix && result.changed.length)\n ? 1\n : 0,\n };\n}\n","import type { DesignCandidate, DesignSystemRequest, DesignToken } from \"@stillwind/host\";\n\nimport { resolveRewriteConfig, type RewriteOptions } from \"./rewrite-files.ts\";\nimport { AnalysisWorker } from \"./worker-client.ts\";\n\n/**\n * Design-system answers from every project of one configuration.\n */\nexport interface DesignSystemAnswer {\n /** Absolute path of the evaluated configuration. */\n config: string;\n /** Tokens in project and name order. */\n tokens: (DesignToken & {\n /** Zero-based project index in the evaluated configuration. */\n project: number;\n })[];\n /** Candidates in project order. */\n candidates: (DesignCandidate & {\n /** Zero-based project index in the evaluated configuration. */\n project: number;\n })[];\n /** Targets without a match in any project. */\n unmatched: string[];\n}\n\n/**\n * Answers a question about each project's design system in a child process.\n *\n * @param options - Configuration discovery. Target globs do not apply.\n * @param request - Theme, utility, or variant request.\n * @returns Answers from every project. Unknown names and unmatched targets are data.\n * @throws If configuration discovery, worker initialization, CSS loading, a plugin, or cleanup fails.\n */\nexport async function designSystem(\n options: Omit<RewriteOptions, \"patterns\">,\n request: DesignSystemRequest,\n): Promise<DesignSystemAnswer> {\n const config = resolveRewriteConfig(options);\n const worker = new AnalysisWorker();\n try {\n await worker.open(config);\n const answers = await worker.request<\n {\n project: number;\n result: {\n tokens: DesignToken[];\n candidates: DesignCandidate[];\n unmatched: string[];\n };\n }[]\n >({\n method: \"designSystem\",\n request,\n });\n return {\n config,\n tokens: answers.flatMap(({ project, result }) =>\n result.tokens.map((token) => ({\n ...token,\n project,\n })),\n ),\n candidates: answers.flatMap(({ project, result }) =>\n result.candidates.map((candidate) => ({\n ...candidate,\n project,\n })),\n ),\n unmatched: request.targets.filter((target) =>\n answers.every(({ result }) => result.unmatched.includes(target)),\n ),\n };\n } finally {\n await worker.close();\n }\n}\n","import type { WorkspaceResult } from \"@stillwind/host\";\n\nimport { rewriteFiles, type RewriteOptions } from \"./rewrite-files.ts\";\nimport type { RewriteFileFailure } from \"./rewrite.ts\";\n\n/** Sorting results whose changed paths compare original and final source bytes. */\nexport interface FormatResult {\n /** Absolute path of the evaluated configuration. */\n config: string;\n /** Absolute paths that changed or would change, in sorted order. */\n changed: string[];\n /** Findings from the original sources, in configured project and target order. */\n results: WorkspaceResult[];\n /** Targets that could not be read, rewritten, or saved. */\n failures: RewriteFileFailure[];\n /** Failures return 2. Check mode otherwise returns 1 when any file would change. */\n exitCode: 0 | 1 | 2;\n}\n\n/**\n * Sorts configured targets and saves changed files unless check is true.\n *\n * @param options - Configuration discovery, target filters, and optional check mode.\n * @returns Changed paths, original findings, and failures. Healthy targets continue after a failure.\n * @throws If selection, configuration, worker communication, or cleanup fails.\n */\nexport async function format(\n options: RewriteOptions & {\n /** Whether to report changes without saving them. Defaults to false. */\n check?: boolean;\n } = {},\n): Promise<FormatResult> {\n const result = await rewriteFiles(options, \"sort\", !options.check, {\n command: \"fmt\",\n mode: options.check ? \"check\" : \"write\",\n });\n return {\n ...result,\n exitCode: result.failures.length ? 2 : options.check && result.changed.length ? 1 : 0,\n };\n}\n","import type { LintSeverity } from \"@stillwind/config\";\n\nimport { resolveRewriteConfig, type RewriteOptions } from \"./rewrite-files.ts\";\nimport { AnalysisWorker } from \"./worker-client.ts\";\n\n/** Effective setting of an active lint rule. */\nexport type ActiveLintRule =\n | Exclude<LintSeverity, \"off\">\n | (Record<string, unknown> & {\n /** Active severity after preset composition and rule overrides. */\n severity: Exclude<LintSeverity, \"off\">;\n });\n\n/** Resolved configuration summary for one project in a configuration file. */\nexport interface ProjectInfo {\n /** Zero-based project index in the evaluated configuration. */\n project: number;\n /** Optional configured project name. */\n name?: string;\n /** Absolute project root directory. */\n root: string;\n /** Absolute path of the configured stylesheet entry. */\n css: string;\n /** Configured target globs relative to root. */\n files: string[];\n /** Configured exclude globs relative to root. */\n exclude: string[];\n /** Number of source files currently matching the project's scope. */\n matchedFiles: number;\n /** Names of configured Stillwind plugins. */\n plugins: string[];\n /** Names of configured project analysis hooks. */\n hooks: string[];\n /** Whether utility sorting is enabled. */\n sort: boolean;\n /** Whether TypeScript type facts are enabled. */\n typeFacts: boolean;\n /** Active lint rules (excluding rules set to `off`), in rule-name order. */\n lint: Record<string, ActiveLintRule>;\n}\n\n/** Resolved project configurations for one configuration file. */\nexport interface InfoResult {\n /** Absolute path of the evaluated configuration. */\n config: string;\n /** Resolved projects in configuration order. */\n projects: ProjectInfo[];\n}\n\n/**\n * Resolves the configuration and returns each project's effective scope, plugins, and active lint\n * rules in a child process without compiling source files.\n *\n * @param options - Configuration discovery. Target globs do not apply.\n * @returns Configuration path and resolved project metadata.\n * @throws If configuration discovery, evaluation, worker initialization, or cleanup fails.\n */\nexport async function info(options: Omit<RewriteOptions, \"patterns\"> = {}): Promise<InfoResult> {\n const config = resolveRewriteConfig(options);\n const worker = new AnalysisWorker();\n try {\n await worker.open(config);\n const projects = await worker.request<ProjectInfo[]>({\n method: \"info\",\n });\n return {\n config,\n projects,\n };\n } finally {\n await worker.close();\n }\n}\n","import { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\n\nimport {\n isStylesheet,\n type EditorRequest,\n type EditorResult,\n type WorkspaceResult,\n} from \"@stillwind/host\";\n\nimport { lintReports } from \"./reports.ts\";\nimport { resolveRewriteConfig, type RewriteOptions } from \"./rewrite-files.ts\";\nimport { AnalysisWorker } from \"./worker-client.ts\";\nimport type { WorkspaceEditorResult } from \"./workspace.ts\";\n\n/**\n * Selects generated CSS by file, line, or position.\n */\nexport interface InspectTarget {\n /** Path or glob accepted by target selection. */\n pattern: string;\n /** One-based line. Omission selects the whole file. */\n line?: number;\n /** One-based UTF-16 column. It requires line. */\n column?: number;\n}\n\n/**\n * Generated CSS for one source range in one project.\n */\nexport interface InspectPreview {\n /** Zero-based project index in the evaluated configuration. */\n project: number;\n /** Original document range with zero-based lines and UTF-16 columns, and an exclusive end. */\n location: {\n uri: string;\n startLine: number;\n startColumn: number;\n endLine: number;\n endColumn: number;\n };\n /** Original source text in the range. */\n source: string;\n /** Formatted CSS. It is empty for a failed occurrence or a marker class. */\n css: string;\n /** False when diagnostics contains an error, or when a required style failed. */\n valid: boolean;\n /** Reports whose primary range overlaps this range. CSS omits the utilities that they reject. */\n diagnostics: {\n /** Report severity, as in the reports of lint. */\n severity: string;\n /** Stable compiler code or lint rule. */\n code: string;\n /** Description of the finding. */\n message: string;\n }[];\n /** Markdown for a marker class. */\n documentation?: string;\n /** Authored runtime key expressions that the CSS depends on. */\n runtimeNames?: string[];\n}\n\n/**\n * An editor answer with a source range. Hovers omit valid because they describe generated CSS.\n */\ntype PreviewRange = NonNullable<EditorResult[\"hover\"]> & {\n valid?: boolean;\n};\n\n/**\n * A target that could not be read.\n */\nexport interface InspectFailure {\n /** Absolute path of the target. */\n file: string;\n /** Reason for the failure. */\n message: string;\n}\n\n/** Reason why `inspect` returned no previews when no execution failures occurred. */\nexport type InspectEmptyReason =\n | \"no-styles\"\n | \"line-out-of-range\"\n | \"column-out-of-range\"\n | \"no-match-at-position\";\n\n/**\n * Inspection results with analysis outcomes retained for each project.\n */\nexport interface InspectResult {\n /** Absolute path of the evaluated configuration. */\n config: string;\n /** Analysis of each selected file, in file and project order. */\n results: WorkspaceResult[];\n /** Selected previews in file, project, and source order, without repeated ranges. */\n previews: InspectPreview[];\n /** Explains why `previews` is empty when `failures` is also empty. */\n emptyReason?: InspectEmptyReason;\n /** Targets that could not be read. */\n failures: InspectFailure[];\n}\n\n/**\n * Parses a command-line target with an optional `:line` or `:line:column` suffix.\n *\n * @param target - Path or glob, including absolute Windows paths.\n * @returns The pattern and any one-based position.\n * @throws If the position is not positive or the target names a stylesheet.\n */\nexport function parseInspectTarget(target: string): InspectTarget {\n const [, pattern, line, column] = /^(.+?)(?::(\\d+)(?::(\\d+))?)?$/s.exec(target) ?? [];\n if (!pattern || /^0+$/.test(line ?? \"\") || /^0+$/.test(column ?? \"\")) {\n throw new Error(`Invalid inspect target: ${target}`);\n }\n if (isStylesheet(pattern)) {\n throw new Error(`inspect does not accept stylesheets: ${target}`);\n }\n return {\n pattern,\n ...(line ? { line: Number(line) } : {}),\n ...(column ? { column: Number(column) } : {}),\n };\n}\n\n/**\n * Finds the UTF-16 offset of the start of each line.\n *\n * @param source - Document text. Lines end at `\\n`, so `\\r\\n` remains one line break.\n * @returns Ascending offsets, beginning with zero.\n */\nfunction lineOffsets(source: string): number[] {\n const offsets = [0];\n for (let index = source.indexOf(\"\\n\"); index >= 0; index = source.indexOf(\"\\n\", index + 1)) {\n offsets.push(index + 1);\n }\n return offsets;\n}\n\n/**\n * Converts an offset to a position.\n *\n * @param lines - Result of {@link lineOffsets}.\n * @param offset - UTF-16 offset in the same document.\n * @returns The zero-based line and column.\n */\nfunction position(lines: readonly number[], offset: number) {\n let line = lines.length - 1;\n while (lines[line] > offset) {\n line--;\n }\n return {\n line,\n column: offset - lines[line],\n };\n}\n\n/**\n * Checks whether a report location belongs to a file.\n *\n * @param uri - File URI or path.\n * @param file - Absolute path.\n * @returns Whether both name the same path.\n */\nfunction isDocument(uri: string, file: string): boolean {\n return path.resolve(uri.startsWith(\"file:\") ? fileURLToPath(uri) : uri) === path.resolve(file);\n}\n\n/**\n * Answers one target for one file.\n *\n * @param worker - Opened worker that owns the file's analysis.\n * @param file - Absolute target path.\n * @param source - Text of the file.\n * @param target - Position to select. Positions outside the file select nothing.\n * @param reports - Reports with a range in this file, for each project.\n * @returns Previews with their project, in project and source order.\n * @throws If the editor query fails.\n */\nasync function selectPreviews(\n worker: AnalysisWorker,\n file: string,\n source: string,\n target: InspectTarget,\n reports: ReturnType<typeof lintReports>,\n): Promise<{\n previews: InspectPreview[];\n emptyReason?: InspectEmptyReason;\n}> {\n const lines = lineOffsets(source);\n const line = target.line === undefined ? undefined : target.line - 1;\n const lineStart = line === undefined ? undefined : lines[line];\n const lineEnd = line === undefined ? undefined : (lines[line + 1] ?? source.length + 1) - 1;\n if (line !== undefined && lineStart === undefined) {\n return {\n previews: [],\n emptyReason: \"line-out-of-range\",\n };\n }\n const offset = target.column === undefined ? undefined : lineStart! + target.column - 1;\n if (offset !== undefined && offset > lineEnd!) {\n return {\n previews: [],\n emptyReason: \"column-out-of-range\",\n };\n }\n const query = (request: EditorRequest) =>\n worker.request<WorkspaceEditorResult[]>({\n method: \"query\",\n file,\n request,\n });\n const uri = pathToFileURL(file).href;\n let selected: { project: number; range: PreviewRange }[];\n let fileHasPreviews = false;\n if (offset === undefined) {\n const all = await query({\n kind: \"previews\",\n });\n fileHasPreviews = all.some(({ result }) => (result.previews?.length ?? 0) > 0);\n selected = all.flatMap(({ project, result }) =>\n (result.previews ?? [])\n .filter(({ start, end }) => line === undefined || (end > lineStart! && start <= lineEnd!))\n .map((range) => ({\n project,\n range,\n })),\n );\n } else {\n const hovers = await query({\n kind: \"hover\",\n offset,\n });\n selected = hovers.flatMap(({ project, result }) =>\n result.hover ? [{ project, range: result.hover }] : [],\n );\n if (selected.length < hovers.length) {\n // Failed occurrences and Vue template expressions have no hover, so the listing supplies them.\n const answered = new Set(selected.map(({ project }) => project));\n const all = await query({\n kind: \"previews\",\n });\n fileHasPreviews = all.some(({ result }) => (result.previews?.length ?? 0) > 0);\n selected.push(\n ...all.flatMap(({ project, result }) =>\n answered.has(project)\n ? []\n : (result.previews ?? [])\n .filter(({ start, end }) => start <= offset && offset <= end)\n .map((range) => ({\n project,\n range,\n })),\n ),\n );\n }\n }\n const previews = selected.flatMap(\n ({ project, range: { start, end, css, valid = true, documentation, runtimeNames } }) => {\n const diagnostics = reports\n .filter(\n ({ project: owner, report: { primary } }) =>\n owner === project &&\n primary.location.startUtf16 < end &&\n start < Math.max(primary.location.endUtf16, primary.location.startUtf16 + 1),\n )\n .map(({ report: { severity, code, message } }) => ({ severity, code, message }));\n if (!css && valid && !diagnostics.length && !documentation) {\n return [];\n }\n const first = position(lines, start);\n const last = position(lines, end);\n return [\n {\n project,\n location: {\n uri,\n startLine: first.line,\n startColumn: first.column,\n endLine: last.line,\n endColumn: last.column,\n },\n source: source.slice(start, end),\n css,\n valid: valid && !diagnostics.some(({ severity }) => severity === \"error\"),\n diagnostics,\n ...(documentation ? { documentation } : {}),\n ...(runtimeNames ? { runtimeNames } : {}),\n },\n ];\n },\n );\n if (!previews.length) {\n return {\n previews,\n emptyReason: line !== undefined && fileHasPreviews ? \"no-match-at-position\" : \"no-styles\",\n };\n }\n return {\n previews,\n };\n}\n\n/**\n * Reports the generated CSS of configured source files in a child process.\n *\n * @param options - Configuration discovery and targets. Paths and globs follow the target rules\n * of lint. Stylesheets are not accepted, and an empty list selects every configured source file.\n * @returns Previews and analysis results. A file with incomplete analysis has no previews.\n * @throws If a target is invalid or matches no file, or if configuration discovery, worker\n * initialization, target enumeration, or cleanup fails.\n */\nexport async function inspect(\n options: Omit<RewriteOptions, \"patterns\"> & {\n /** Targets as written on the command line. */\n targets?: readonly string[];\n } = {},\n): Promise<InspectResult> {\n const targets = (options.targets ?? []).map(parseInspectTarget);\n const config = resolveRewriteConfig(options);\n const worker = new AnalysisWorker();\n try {\n await worker.open(config);\n const selections = new Map<string, InspectTarget[]>();\n for (const target of targets.length ? targets : [undefined]) {\n const files = (await worker.targets(target ? [target.pattern] : undefined)).filter(\n (file) => !isStylesheet(file),\n );\n if (!files.length) {\n throw new Error(\n target\n ? `No analysis targets matched ${target.pattern}`\n : \"No analysis targets matched the configured scopes\",\n );\n }\n for (const file of files) {\n selections.set(file, [\n ...(selections.get(file) ?? []),\n target ?? {\n pattern: file,\n },\n ]);\n }\n }\n const files = [...selections.keys()].sort();\n await worker.request({\n method: \"prepare\",\n files,\n });\n\n const result: InspectResult = {\n config,\n results: [],\n previews: [],\n failures: [],\n };\n const emptyReasons = new Set<InspectEmptyReason>();\n for (const file of files) {\n const analyses = await worker.analyze(file);\n result.results.push(...analyses);\n const complete = new Set(\n analyses.filter(({ result }) => result.status === \"complete\").map(({ project }) => project),\n );\n let source: string;\n try {\n const bytes = await readFile(file);\n source = bytes.toString(\"utf8\");\n if (!Buffer.from(source).equals(bytes)) {\n throw new Error(`Source is not valid UTF-8: ${file}`);\n }\n } catch (error) {\n result.failures.push({\n file,\n message: error instanceof Error ? error.message : String(error),\n });\n continue;\n }\n const reports = lintReports(analyses).filter(\n ({ report }) =>\n report.primary.scope === \"range\" && isDocument(report.primary.location.uri, file),\n );\n const seen = new Set<string>();\n const previews: InspectPreview[] = [];\n for (const target of selections.get(file)!) {\n const selection = await selectPreviews(worker, file, source, target, reports);\n if (selection.emptyReason) {\n emptyReasons.add(selection.emptyReason);\n }\n for (const preview of selection.previews) {\n const { startLine, startColumn, endLine, endColumn } = preview.location;\n const key = [preview.project, startLine, startColumn, endLine, endColumn].join();\n if (complete.has(preview.project) && !seen.has(key)) {\n seen.add(key);\n previews.push(preview);\n }\n }\n }\n result.previews.push(\n ...previews.sort(\n (a, b) =>\n a.project - b.project ||\n a.location.startLine - b.location.startLine ||\n a.location.startColumn - b.location.startColumn,\n ),\n );\n }\n if (!result.previews.length && !result.failures.length) {\n result.emptyReason = emptyReasons.has(\"no-match-at-position\")\n ? \"no-match-at-position\"\n : emptyReasons.has(\"column-out-of-range\")\n ? \"column-out-of-range\"\n : emptyReasons.has(\"line-out-of-range\")\n ? \"line-out-of-range\"\n : \"no-styles\";\n }\n return result;\n } finally {\n await worker.close();\n }\n}\n","import type { WorkspaceResult } from \"@stillwind/host\";\n\nimport { lintReports } from \"./reports.ts\";\nimport { resolveRewriteConfig, rewriteFiles, type RewriteOptions } from \"./rewrite-files.ts\";\nimport type { RewriteFileFailure } from \"./rewrite.ts\";\nimport { AnalysisWorker } from \"./worker-client.ts\";\n\n/** Lint results preserve project membership and identify incomplete analysis. */\nexport interface LintResult {\n /** Absolute path of the evaluated configuration. */\n config: string;\n /** Target results in configured project order, including overlapping project memberships. */\n results: WorkspaceResult[];\n /** Files whose bytes changed when fix was requested. */\n changed?: string[];\n /** Targets that could not be read, fixed, or saved when fix was requested. */\n failures?: RewriteFileFailure[];\n /**\n * - 0: successful checks\n * - 1: compiler errors or denied lint\n * - 2: incomplete execution\n */\n exitCode: 0 | 1 | 2;\n}\n\n/**\n * Analyzes configured target scopes in a child process and closes it before returning.\n *\n * @param options - Configuration discovery and optional target filters. Omission checks all\n * configured targets from the process working directory.\n * @returns Results and an exit code. Readonly lint returns code 2 for empty selection or incomplete analysis.\n * @throws If configuration discovery, worker initialization, target enumeration, or cleanup fails.\n * Fix mode reports failures per target and continues with healthy targets. Empty selection throws.\n */\nexport async function lint(\n options: RewriteOptions & {\n /** Applies converged fixes and reports findings from the final source buffers. */\n fix?: boolean;\n } = {},\n): Promise<LintResult> {\n if (options.fix) {\n const result = await rewriteFiles(options, \"fixes\", true);\n return {\n ...result,\n exitCode: result.failures.length\n ? 2\n : result.results.some(({ result }) =>\n result.reports.some((report) => report.severity === \"error\"),\n )\n ? 1\n : 0,\n };\n }\n const config = resolveRewriteConfig(options);\n const worker = new AnalysisWorker();\n try {\n await worker.open(config);\n const results = await worker.lint(options.patterns);\n const exitCode =\n !results.length || results.some(({ result }) => result.status !== \"complete\")\n ? 2\n : results.some(({ result }) => result.reports.some((report) => report.severity === \"error\"))\n ? 1\n : 0;\n return { config, results, exitCode };\n } finally {\n await worker.close();\n }\n}\n\n/**\n * Formats findings and incomplete analysis for terminal output.\n *\n * @param result - Lint results whose reports use original document locations.\n * @returns Text with one-based line and column positions. Duplicate findings are removed per\n * project. Findings from overlapping projects remain separate. Successful results can return empty text.\n */\nexport function formatLint(result: LintResult): string {\n const lines: string[] = [];\n for (const { project, report } of lintReports(result.results)) {\n const location = report.primary.location;\n const at =\n report.primary.scope === \"document\"\n ? location.uri\n : `${location.uri}:${location.startLine + 1}:${location.startColumn + 1}`;\n lines.push(\n `[project ${project + 1}] ${at}: ${report.severity} ${report.code}: ${report.message}`,\n );\n for (const related of report.related) {\n lines.push(\n ` ${related.location.uri}:${related.location.startLine + 1}:${related.location.startColumn + 1}${related.message ? `: ${related.message}` : \"\"}`,\n );\n }\n lines.push(...report.notes.map((note) => ` ${note}`));\n }\n for (const entry of result.results) {\n if (entry.result.status !== \"complete\") {\n lines.push(\n `[project ${entry.project + 1}] ${entry.result.entry}: incomplete analysis${entry.result.error ? `: ${entry.result.error}` : \"\"}`,\n );\n for (const dependency of entry.result.graph?.dependencies ?? []) {\n if (dependency.status === \"unresolved\" || dependency.status === \"unsupported\") {\n lines.push(` ${dependency.status}: ${dependency.specifier} from ${dependency.importer}`);\n }\n }\n for (const range of entry.result.graph?.unverified ?? []) {\n lines.push(\n ` unverified: ${range.moduleId}${range.start === undefined ? \"\" : `:${range.start}-${range.end}`}: ${range.reason}`,\n );\n }\n }\n }\n for (const failure of result.failures ?? []) {\n if (!failure.results.some(({ result }) => result.status !== \"complete\")) {\n lines.push(`${failure.file}: ${failure.message}`);\n }\n }\n if (!result.results.length && !result.failures?.length) {\n lines.push(\"No analysis targets matched the configured scopes\");\n }\n return lines.join(\"\\n\");\n}\n","import path from \"node:path\";\nimport process from \"node:process\";\nimport { fileURLToPath } from \"node:url\";\n\nimport { findConfiguration, findDocumentConfiguration } from \"@stillwind/config/node\";\n\nimport { AnalysisWorker } from \"./worker-client.ts\";\nimport type {\n AnalysisWorkspaceContext,\n AnalysisWorkspaceService,\n OpenAnalysisWorkspaces,\n WorkspaceEditorResult,\n} from \"./workspace.ts\";\n\n/**\n * Lists the directories that bound configuration discovery.\n *\n * @param context - Workspace directory URIs.\n * @returns Absolute paths of the file URIs, or the process working directory for an empty list.\n * @throws If converting a malformed file URI fails.\n */\nfunction folderPaths(context: AnalysisWorkspaceContext): string[] {\n return context.workspaceFolders.length\n ? context.workspaceFolders\n .filter((uri) => uri.startsWith(\"file:\"))\n .map((uri) => fileURLToPath(uri))\n : [process.cwd()];\n}\n\n/**\n * Opens one isolated Node analysis process for each distinct configuration.\n *\n * @param context - Workspace directory URIs. File URIs use upward configuration discovery, and a\n * folder without a configuration opens no service. Other URI schemes cannot open Node workspaces.\n * An empty list uses the process working directory.\n * @param config - Optional explicit configuration path, resolved from the process working directory.\n * When supplied, it replaces discovery from workspace folders.\n * @returns Services keyed by absolute configuration path and separate initialization errors.\n * Services accept file URIs, forward buffers to their workers, and discard cancelled results.\n * @throws If converting a malformed file URI or closing a failed worker throws.\n */\nexport async function openNodeWorkspaces(\n context: AnalysisWorkspaceContext,\n config?: string,\n): Promise<OpenAnalysisWorkspaces> {\n const workspaces = new Map<string, AnalysisWorkspaceService>();\n const errors = new Map<string, string>();\n\n const paths = config\n ? [path.resolve(config)]\n : folderPaths(context).map((folder) => findConfiguration(folder));\n for (const file of new Set(paths.filter((file): file is string => Boolean(file)))) {\n await openConfiguration(file, workspaces, errors);\n }\n\n return {\n workspaces,\n errors,\n };\n}\n\n/**\n * Opens the nearest configuration of a document that no open service covers.\n *\n * @param uri - Document URI. Other schemes than `file:` open nothing.\n * @param context - Workspace directory URIs that bound the search.\n * @param known - Configuration paths that already have a service or an attempt.\n * @returns The new service and any initialization error, or undefined when the document has no\n * new configuration.\n * @throws If converting a malformed file URI or closing a failed worker throws.\n */\nexport async function discoverNodeWorkspace(\n uri: string,\n context: AnalysisWorkspaceContext,\n known: ReadonlySet<string>,\n): Promise<OpenAnalysisWorkspaces | undefined> {\n if (!uri.startsWith(\"file:\")) {\n return undefined;\n }\n const file = findDocumentConfiguration(fileURLToPath(uri), folderPaths(context));\n if (!file || known.has(file)) {\n return undefined;\n }\n const workspaces = new Map<string, AnalysisWorkspaceService>();\n const errors = new Map<string, string>();\n await openConfiguration(file, workspaces, errors);\n return {\n workspaces,\n errors,\n };\n}\n\n/**\n * Starts one analysis process and records its service or its initialization failure.\n *\n * @param file - Absolute configuration path.\n * @param workspaces - Receives the service keyed by file.\n * @param errors - Receives the failure message keyed by file.\n * @throws If closing a failed worker throws.\n */\nasync function openConfiguration(\n file: string,\n workspaces: Map<string, AnalysisWorkspaceService>,\n errors: Map<string, string>,\n): Promise<void> {\n const worker = new AnalysisWorker();\n try {\n await worker.open(file);\n /**\n * Selects document identities that can be forwarded to the filesystem worker.\n *\n * @param uri - Document URI whose syntax is validated later by `fileURLToPath`.\n * @returns Whether the URI begins with the `file:` scheme.\n */\n const accepts = (uri: string) => uri.startsWith(\"file:\");\n workspaces.set(file, {\n refresh: (uris) =>\n worker.request<boolean>({\n method: \"refresh\",\n files: uris.filter(accepts).map((uri) => fileURLToPath(uri)),\n }),\n affects: (uris) =>\n worker.request<boolean>({\n method: \"affects\",\n files: uris.filter(accepts).map((uri) => fileURLToPath(uri)),\n }),\n prepare: async (uris, signal) => {\n if (!signal?.aborted) {\n await worker.request({\n method: \"prepare\",\n files: uris.filter(accepts).map((uri) => fileURLToPath(uri)),\n });\n }\n },\n query: async (uri, request, signal) => {\n if (!accepts(uri) || signal?.aborted) {\n return [];\n }\n const results = await worker.request<WorkspaceEditorResult[]>({\n method: \"query\",\n file: fileURLToPath(uri),\n request,\n });\n return signal?.aborted ? [] : results;\n },\n update: async (uri, source, version) => {\n if (accepts(uri)) {\n await worker.request({\n method: \"update\",\n file: fileURLToPath(uri),\n source,\n version,\n });\n }\n },\n analyze: async (uri, signal) => {\n if (!accepts(uri) || signal?.aborted) {\n return [];\n }\n const results = await worker.analyze(fileURLToPath(uri));\n return signal?.aborted\n ? []\n : results.map(({ project, config, result }) => ({\n project,\n config,\n result: {\n entry: result.entry,\n revision: result.revision,\n status: result.status,\n reports: result.reports,\n error: result.error,\n dependencies: result.graph?.dependencies,\n unverified: result.graph?.unverified,\n generation: result.graph?.generation,\n },\n }));\n },\n closeDocument: async (uri) => {\n if (accepts(uri)) {\n await worker.request({\n method: \"closeDocument\",\n file: fileURLToPath(uri),\n });\n }\n },\n close: async () => {\n await worker.close();\n },\n });\n } catch (error) {\n errors.set(file, String(error));\n await worker.close();\n }\n}\n","import path from \"node:path\";\n\nimport { findConfiguration } from \"@stillwind/config/node\";\n\nimport { RewriteFailure, type RewriteInput, type RewriteResult } from \"./rewrite.ts\";\nimport { AnalysisWorker } from \"./worker-client.ts\";\n\n/**\n * Reuses an isolated process while refreshing trusted configuration for each formatting request.\n */\nexport class SourceFormatter {\n /** Child process reused across formatting requests and owned until close completes. */\n readonly #worker = new AnalysisWorker();\n /** Serializes requests while allowing a new request after a preceding failure. */\n #queue: Promise<unknown> = Promise.resolve();\n\n /**\n * Starts the isolated worker that evaluates configuration on each formatting request.\n *\n * @param config - Configuration path resolved in the worker's inherited working directory.\n */\n constructor(private readonly config: string) {}\n\n /**\n * Sorts the supplied buffer with current project settings.\n * Files outside all configured scopes return unchanged text. Requests are serialized and never write files.\n *\n * @param input - Original buffer and optional protected ranges. Relative paths are resolved from cwd.\n * @returns The sorted buffer and original findings after configuration is reopened.\n * @throws If configuration loading, parsing, analysis, project agreement, rewriting, or worker communication fails.\n */\n format(input: RewriteInput): Promise<RewriteResult> {\n const task = this.#queue.then(async () => {\n await this.#worker.open(this.config);\n const { outputs, failures } = await this.#worker.rewrite(\n [\n {\n ...input,\n file: path.resolve(input.file),\n },\n ],\n \"sort\",\n );\n if (failures.length) {\n throw new RewriteFailure(failures[0].message, failures[0].results);\n }\n return outputs[0];\n });\n this.#queue = task.catch(() => {});\n return task;\n }\n\n /**\n * Waits for queued formatting and releases the child process. Stop submitting requests before closure.\n *\n * @returns Completion of worker cleanup.\n * @throws If the worker's cleanup request fails.\n */\n async close(): Promise<void> {\n await this.#queue;\n await this.#worker.close();\n }\n}\n\n/**\n * Finds a configuration above a source file or resolves an explicit path from cwd.\n *\n * @param file - Source path whose parent starts upward discovery. Relative paths use cwd.\n * @param config - Optional explicit configuration path, returned without an existence check.\n * @returns The absolute configuration path, or undefined when discovery finds none.\n */\nexport function findFormatterConfig(file: string, config?: string): string | undefined {\n if (config) {\n return path.resolve(config);\n }\n return findConfiguration(path.dirname(path.resolve(file)));\n}\n"],"mappings":";;;;;;;;;;;;;AAqIA,IAAa,iBAAb,MAA4B;;CAE1B;;CAEA,2BAAoB,IAAI,IAQtB;;CAEF;;CAGA,UAAU;;CAEV,UAAU;;CAEV,WAAW;;;;CAKX,cAAc;EACZ,KAAK,SAAS,KAAK,cAAc,IAAI,IAAI,eAAe,YAAY,GAAG,CAAC,GAAG,CAAC,GAAG;GAC7E,OAAO;IAAC;IAAU;IAAQ;IAAQ;GAAK;GACvC,UAAU,CAAC;GACX,aAAa;EACf,CAAC;EACD,KAAK,OAAO,OAAQ,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a,MAAM,KAAK,QAAQ,QAC/C,CACE;IACE,GAAG;IACH,MAAM,KAAK,QAAQ,MAAM,IAAI;GAC/B,CACF,GACA,MACF;GACA,IAAI,SAAS,QACX,MAAM,IAAI,eAAe,SAAS,EAAE,CAAC,SAAS,SAAS,EAAE,CAAC,OAAO;GAEnE,OAAO,QAAQ;EACjB,CAAC;EACD,KAAK,SAAS,KAAK,YAAY,CAAC,CAAC;EACjC,OAAO;CACT;;;;;;;CAQA,MAAM,QAAuB;EAC3B,MAAM,KAAK;EACX,MAAM,KAAK,QAAQ,MAAM;CAC3B;AACF;;;;;;;;AASA,SAAgB,oBAAoB,MAAc,QAAqC;CACrF,IAAI,QACF,OAAO,KAAK,QAAQ,MAAM;CAE5B,OAAO,kBAAkB,KAAK,QAAQ,KAAK,QAAQ,IAAI,CAAC,CAAC;AAC3D"}
@@ -1,3 +1,4 @@
1
+ import { lintRules } from "@stillwind/config";
1
2
  // src/reports.ts
2
3
  /**
3
4
  * Collects distinct reports per project while preserving their analysis order.
@@ -34,8 +35,8 @@ function documentationUrl(code) {
34
35
  * @returns `errors` for compiler codes, `lints` for lint rule names, and otherwise undefined.
35
36
  */
36
37
  function documentationSection(code) {
37
- return /^SW\d+$/.test(code) ? "errors" : /^[a-z][a-z-]*$/.test(code) ? "lints" : void 0;
38
+ return /^SW\d+$/.test(code) ? "errors" : Object.hasOwn(lintRules, code) ? "lints" : void 0;
38
39
  }
39
40
  export { documentationUrl as n, lintReports as r, documentationSection as t };
40
41
 
41
- //# sourceMappingURL=reports-DvHppcFa.js.map
42
+ //# sourceMappingURL=reports-Bu0OQg-C.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reports-Bu0OQg-C.js","names":[],"sources":["../src/reports.ts"],"sourcesContent":["import { lintRules } from \"@stillwind/config\";\n\nimport type { WorkspaceResult } from \"./workspace.ts\";\n\n/**\n * Collects distinct reports per project while preserving their analysis order.\n *\n * @param results - Analysis results with their project membership.\n * @returns Reports in first-occurrence order. Equal reports from different projects remain separate.\n */\nexport function lintReports(results: readonly WorkspaceResult[]) {\n const seen = new Set<string>();\n return results.flatMap((entry) =>\n entry.result.reports.flatMap((report) => {\n const key = JSON.stringify([entry.project, report]);\n if (seen.has(key)) {\n return [];\n }\n seen.add(key);\n return [\n {\n project: entry.project,\n report,\n },\n ];\n }),\n );\n}\n\n/**\n * Returns the website page that explains a report code.\n *\n * @param code - Compiler code, such as `SW01001`, or lint rule name, such as `unknown-utility`.\n * @returns The page URL, or undefined for codes without a page, such as `SW_UNVERIFIED`.\n */\nexport function documentationUrl(code: string): string | undefined {\n const section = documentationSection(code);\n return section && `https://stillwind.dev/docs/${section}/${code}`;\n}\n\n/**\n * Returns the documentation section of a report code.\n *\n * @param code - Report code of a diagnostic.\n * @returns `errors` for compiler codes, `lints` for lint rule names, and otherwise undefined.\n */\nexport function documentationSection(code: string): \"errors\" | \"lints\" | undefined {\n return /^SW\\d+$/.test(code) ? \"errors\" : Object.hasOwn(lintRules, code) ? \"lints\" : undefined;\n}\n"],"mappings":";;;;;;;;AAUA,SAAgB,YAAY,SAAqC;CAC/D,MAAM,uBAAO,IAAI,IAAY;CAC7B,OAAO,QAAQ,SAAS,UACtB,MAAM,OAAO,QAAQ,SAAS,WAAW;EACvC,MAAM,MAAM,KAAK,UAAU,CAAC,MAAM,SAAS,MAAM,CAAC;EAClD,IAAI,KAAK,IAAI,GAAG,GACd,OAAO,CAAC;EAEV,KAAK,IAAI,GAAG;EACZ,OAAO,CACL;GACE,SAAS,MAAM;GACf;EACF,CACF;CACF,CAAC,CACH;AACF;;;;;;;AAQA,SAAgB,iBAAiB,MAAkC;CACjE,MAAM,UAAU,qBAAqB,IAAI;CACzC,OAAO,WAAW,8BAA8B,QAAQ,GAAG;AAC7D;;;;;;;AAQA,SAAgB,qBAAqB,MAA8C;CACjF,OAAO,UAAU,KAAK,IAAI,IAAI,WAAW,OAAO,OAAO,WAAW,IAAI,IAAI,UAAU,KAAA;AACtF"}
@@ -1,6 +1,8 @@
1
1
  import { fingerprint } from "@stillwind/native";
2
2
  // src/rewrite.ts
3
- /** Failed rewrite planning with the analysis results that prevented writing. */
3
+ /**
4
+ * Failed rewrite planning with the analysis results that prevented writing.
5
+ */
4
6
  var RewriteFailure = class extends Error {
5
7
  results;
6
8
  constructor(message, results) {
@@ -9,7 +11,9 @@ var RewriteFailure = class extends Error {
9
11
  this.name = "RewriteFailure";
10
12
  }
11
13
  };
12
- /** Owns buffer versions while computing changes against one workspace. Calls must be serialized. */
14
+ /**
15
+ * Owns buffer versions while computing changes against one workspace. Calls must be serialized.
16
+ */
13
17
  var SourceRewriter = class {
14
18
  workspace;
15
19
  /** Increasing version assigned to every buffer in each rewrite pass. */
@@ -29,13 +33,15 @@ var SourceRewriter = class {
29
33
  * buffers are removed even when rewriting fails. Preparation runs once before each pass's per-file queries.
30
34
  *
31
35
  * @param inputs - Distinct absolute paths and complete text. Only sorting uses protected ranges.
32
- * @param operation - One sort pass or lint-fix passes until the text stops changing.
36
+ * @param operation - One sort pass, lint-fix passes until the text stops changing, or converged
37
+ * lint fixes followed by a sort pass and final analysis when sorting changes any buffer.
33
38
  * @returns Successful buffers and failures in input order. Failed buffers retain their original
34
39
  * text in subsequent passes. Fixes return no edits because their offsets span several passes.
35
40
  * @throws If paths repeat or workspace invalidation, preparation, buffer installation, or cleanup fails.
36
41
  */
37
42
  async rewrite(inputs, operation) {
38
43
  if (new Set(inputs.map((input) => input.file)).size !== inputs.length) throw new Error("Rewrite inputs must have distinct file paths");
44
+ const loopOperation = operation === "sort" ? "sort" : "fixes";
39
45
  let buffers = inputs;
40
46
  const failures = /* @__PURE__ */ new Map();
41
47
  const originals = new Map(inputs.map((input) => [input.file, input.source]));
@@ -52,8 +58,8 @@ var SourceRewriter = class {
52
58
  for (const input of buffers) {
53
59
  if (failures.has(input.file)) continue;
54
60
  try {
55
- const output = await this.#rewriteBuffer(input, operation);
56
- if (operation === "fixes" && output.code !== input.source) {
61
+ const output = await this.#rewriteBuffer(input, loopOperation);
62
+ if (loopOperation === "fixes" && output.code !== input.source) {
57
63
  const history = seen.get(input.file);
58
64
  if (history.has(snapshot)) throw new RewriteFailure("Stillwind fixes did not converge", output.results);
59
65
  if (history.size >= 10) throw new RewriteFailure("Stillwind fixes exceeded ten passes", output.results);
@@ -70,16 +76,19 @@ var SourceRewriter = class {
70
76
  changed ||= input.source !== originals.get(input.file);
71
77
  }
72
78
  }
73
- if (operation === "sort" || !changed) return {
74
- outputs: outputs.map((output) => ({
75
- ...output,
76
- edits: operation === "sort" ? output.edits : []
77
- })),
78
- failures: inputs.flatMap((input) => {
79
- const failure = failures.get(input.file);
80
- return failure ? [failure] : [];
81
- })
82
- };
79
+ if (loopOperation === "sort" || !changed) {
80
+ if (operation === "fixes-and-sort") return await this.#sortAndAnalyze(inputs, buffers, failures);
81
+ return {
82
+ outputs: outputs.map((output) => ({
83
+ ...output,
84
+ edits: operation === "sort" ? output.edits : []
85
+ })),
86
+ failures: inputs.flatMap((input) => {
87
+ const failure = failures.get(input.file);
88
+ return failure ? [failure] : [];
89
+ })
90
+ };
91
+ }
83
92
  const replacements = new Map(outputs.map((output) => [output.file, output.code]));
84
93
  buffers = inputs.map((input) => ({
85
94
  file: input.file,
@@ -91,6 +100,75 @@ var SourceRewriter = class {
91
100
  }
92
101
  }
93
102
  /**
103
+ * Runs one sort pass on buffers that survived lint fixes and re-analyzes surviving targets when
104
+ * sorting changes any buffer, so returned diagnostics match the final text and positions.
105
+ *
106
+ * @param inputs - Original rewrite inputs, used to preserve result order and restore failed
107
+ * targets when installing sorted buffers.
108
+ * @param buffers - Converged post-fix buffers already installed and prepared in the workspace.
109
+ * @param failures - Accumulated per-file failures keyed by path. Targets whose sort pass fails
110
+ * are added to this map.
111
+ * @returns Successful outputs and failures in input order. Outputs carry empty `edits` because
112
+ * replacements span multiple passes.
113
+ * @throws If installing, preparing, or re-analyzing the sorted buffers fails.
114
+ */
115
+ async #sortAndAnalyze(inputs, buffers, failures) {
116
+ const outputs = [];
117
+ let sortedChanged = false;
118
+ for (const input of buffers) {
119
+ if (failures.has(input.file)) continue;
120
+ try {
121
+ const output = await this.#rewriteBuffer(input, "sort");
122
+ if (output.code !== input.source) sortedChanged = true;
123
+ outputs.push({
124
+ ...output,
125
+ edits: []
126
+ });
127
+ } catch (error) {
128
+ failures.set(input.file, {
129
+ file: input.file,
130
+ message: error instanceof Error ? error.message : String(error),
131
+ results: error instanceof RewriteFailure ? error.results : []
132
+ });
133
+ }
134
+ }
135
+ if (sortedChanged && outputs.length) {
136
+ const replacements = new Map(outputs.map((output) => [output.file, output.code]));
137
+ const version = ++this.#version;
138
+ for (const input of inputs) this.workspace.update(input.file, replacements.get(input.file) ?? input.source, version);
139
+ await this.workspace.prepare?.(outputs.map((output) => output.file));
140
+ for (const output of outputs) output.results = await this.workspace.analyze(output.file);
141
+ }
142
+ return {
143
+ outputs,
144
+ failures: inputs.flatMap((input) => {
145
+ const failure = failures.get(input.file);
146
+ return failure ? [failure] : [];
147
+ })
148
+ };
149
+ }
150
+ /**
151
+ * Re-analyzes surviving rewrite outputs after external hooks modify their text, so Stillwind
152
+ * diagnostics match the final buffer contents and positions.
153
+ *
154
+ * @param inputs - Original rewrite inputs, used to restore unmodified or failed targets.
155
+ * @param outputs - Surviving outputs whose `code` has been updated by hooks. Their `results`
156
+ * arrays are replaced in place.
157
+ * @throws If installing, preparing, analyzing, or closing buffers fails.
158
+ */
159
+ async reanalyze(inputs, outputs) {
160
+ if (!outputs.length) return;
161
+ const replacements = new Map(outputs.map((output) => [output.file, output.code]));
162
+ const version = ++this.#version;
163
+ try {
164
+ for (const input of inputs) this.workspace.update(input.file, replacements.get(input.file) ?? input.source, version);
165
+ await this.workspace.prepare?.(outputs.map((output) => output.file));
166
+ for (const output of outputs) output.results = await this.workspace.analyze(output.file);
167
+ } finally {
168
+ for (const input of inputs) this.workspace.closeDocument(input.file);
169
+ }
170
+ }
171
+ /**
94
172
  * Analyzes one installed buffer and requires matching project answers to produce the same text.
95
173
  *
96
174
  * @param input - Buffer already installed in the workspace for the current pass.
@@ -152,4 +230,4 @@ function applySourceEdits(source, edits) {
152
230
  }
153
231
  export { SourceRewriter as n, RewriteFailure as t };
154
232
 
155
- //# sourceMappingURL=rewrite-Bdo2ssmD.js.map
233
+ //# sourceMappingURL=rewrite-daiEBUgj.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rewrite-daiEBUgj.js","names":[],"sources":["../src/rewrite.ts"],"sourcesContent":["import type { AnalysisWorkspace, EditorEdit, WorkspaceResult } from \"@stillwind/host\";\nimport { fingerprint } from \"@stillwind/native\";\n\n/**\n * Rewrite mode: utility sorting, converged lint fixes, or converged lint fixes followed by sorting.\n */\nexport type RewriteOperation = \"sort\" | \"fixes\" | \"fixes-and-sort\";\n\n/**\n * Failed rewrite planning with the analysis results that prevented writing.\n */\nexport class RewriteFailure extends Error {\n constructor(\n message: string,\n readonly results: WorkspaceResult[],\n ) {\n super(message);\n this.name = \"RewriteFailure\";\n }\n}\n\n/**\n * Original buffer and ranges excluded by a formatter adapter. Paths are absolute.\n */\nexport interface RewriteInput {\n /** Absolute target path used for workspace membership and dependency resolution. */\n file: string;\n /** Complete original text against which edits are measured. */\n source: string;\n /** Half-open UTF-16 ranges in source. Only sorting accepts protected ranges. */\n protectedRanges?: readonly {\n /** Inclusive original UTF-16 offset. */\n start: number;\n /** Exclusive original UTF-16 offset. */\n end: number;\n }[];\n}\n\n/**\n * Replacement text and independent project findings for one original buffer.\n */\nexport interface RewriteResult {\n /** Absolute path copied from the corresponding input. */\n file: string;\n /** Final text after sorting or converged fixes. */\n code: string;\n /** Sorting edits in the input buffer. Iterated lint fixes omit these edits. */\n edits: EditorEdit[];\n /** Findings for the analyzed input of the final pass, in project order. */\n results: WorkspaceResult[];\n}\n\n/**\n * A target that could not be read, rewritten, or saved.\n */\nexport interface RewriteFileFailure {\n /** Absolute path of the failed target. */\n file: string;\n /** Reason that reading, planning, or saving this target failed. */\n message: string;\n /** Analysis findings captured before planning failed, when available. */\n results: WorkspaceResult[];\n}\n\n/**\n * Independent target outcomes from a shared set of captured buffers.\n */\nexport interface RewriteBatchResult {\n /** Successful replacements in input order. */\n outputs: RewriteResult[];\n /** Failed targets in input order. */\n failures: RewriteFileFailure[];\n}\n\n/**\n * Owns buffer versions while computing changes against one workspace. Calls must be serialized.\n */\nexport class SourceRewriter {\n /** Increasing version assigned to every buffer in each rewrite pass. */\n #version = 0;\n\n /**\n * Attaches rewriting to a workspace whose buffers the caller reserves for this rewriter.\n *\n * @param workspace - Open workspace. Serialize rewrite calls and avoid concurrent updates to input paths.\n * When prepare is available, the rewriter calls it after installing each pass's buffers.\n */\n constructor(\n private readonly workspace: Pick<\n AnalysisWorkspace,\n \"invalidate\" | \"update\" | \"analyze\" | \"query\" | \"closeDocument\"\n > &\n Partial<Pick<AnalysisWorkspace, \"prepare\">>,\n ) {}\n\n /**\n * Computes sorting or converged lint fixes without saving files. All input buffers are visible\n * to dependency analysis. After distinct paths are validated, captured\n * buffers are removed even when rewriting fails. Preparation runs once before each pass's per-file queries.\n *\n * @param inputs - Distinct absolute paths and complete text. Only sorting uses protected ranges.\n * @param operation - One sort pass, lint-fix passes until the text stops changing, or converged\n * lint fixes followed by a sort pass and final analysis when sorting changes any buffer.\n * @returns Successful buffers and failures in input order. Failed buffers retain their original\n * text in subsequent passes. Fixes return no edits because their offsets span several passes.\n * @throws If paths repeat or workspace invalidation, preparation, buffer installation, or cleanup fails.\n */\n async rewrite(\n inputs: readonly RewriteInput[],\n operation: RewriteOperation,\n ): Promise<RewriteBatchResult> {\n if (new Set(inputs.map((input) => input.file)).size !== inputs.length) {\n throw new Error(\"Rewrite inputs must have distinct file paths\");\n }\n const loopOperation = operation === \"sort\" ? \"sort\" : \"fixes\";\n let buffers = inputs;\n const failures = new Map<string, RewriteFileFailure>();\n const originals = new Map(inputs.map((input) => [input.file, input.source]));\n const seen = new Map(inputs.map((input) => [input.file, new Set<string>()]));\n try {\n this.workspace.invalidate();\n for (;;) {\n const snapshot = JSON.stringify([\n buffers.map((input) => input.source),\n [...failures.keys()],\n ]);\n const version = ++this.#version;\n for (const input of buffers) {\n this.workspace.update(input.file, input.source, version);\n }\n await this.workspace.prepare?.(\n buffers.filter((input) => !failures.has(input.file)).map((input) => input.file),\n );\n const outputs: RewriteResult[] = [];\n let changed = false;\n for (const input of buffers) {\n if (failures.has(input.file)) {\n continue;\n }\n try {\n const output = await this.#rewriteBuffer(input, loopOperation);\n if (loopOperation === \"fixes\" && output.code !== input.source) {\n const history = seen.get(input.file)!;\n if (history.has(snapshot)) {\n throw new RewriteFailure(\"Stillwind fixes did not converge\", output.results);\n }\n if (history.size >= 10) {\n throw new RewriteFailure(\"Stillwind fixes exceeded ten passes\", output.results);\n }\n history.add(snapshot);\n changed = true;\n }\n outputs.push(output);\n } catch (error) {\n failures.set(input.file, {\n file: input.file,\n message: error instanceof Error ? error.message : String(error),\n results: error instanceof RewriteFailure ? error.results : [],\n });\n changed ||= input.source !== originals.get(input.file);\n }\n }\n if (loopOperation === \"sort\" || !changed) {\n if (operation === \"fixes-and-sort\") {\n return await this.#sortAndAnalyze(inputs, buffers, failures);\n }\n return {\n outputs: outputs.map((output) => ({\n ...output,\n edits: operation === \"sort\" ? output.edits : [],\n })),\n failures: inputs.flatMap((input) => {\n const failure = failures.get(input.file);\n return failure ? [failure] : [];\n }),\n };\n }\n const replacements = new Map(outputs.map((output) => [output.file, output.code]));\n buffers = inputs.map((input) => ({\n file: input.file,\n source: replacements.get(input.file) ?? input.source,\n }));\n }\n } finally {\n for (const input of inputs) {\n this.workspace.closeDocument(input.file);\n }\n }\n }\n\n /**\n * Runs one sort pass on buffers that survived lint fixes and re-analyzes surviving targets when\n * sorting changes any buffer, so returned diagnostics match the final text and positions.\n *\n * @param inputs - Original rewrite inputs, used to preserve result order and restore failed\n * targets when installing sorted buffers.\n * @param buffers - Converged post-fix buffers already installed and prepared in the workspace.\n * @param failures - Accumulated per-file failures keyed by path. Targets whose sort pass fails\n * are added to this map.\n * @returns Successful outputs and failures in input order. Outputs carry empty `edits` because\n * replacements span multiple passes.\n * @throws If installing, preparing, or re-analyzing the sorted buffers fails.\n */\n async #sortAndAnalyze(\n inputs: readonly RewriteInput[],\n buffers: readonly RewriteInput[],\n failures: Map<string, RewriteFileFailure>,\n ): Promise<RewriteBatchResult> {\n const outputs: RewriteResult[] = [];\n let sortedChanged = false;\n for (const input of buffers) {\n if (failures.has(input.file)) {\n continue;\n }\n try {\n const output = await this.#rewriteBuffer(input, \"sort\");\n if (output.code !== input.source) {\n sortedChanged = true;\n }\n outputs.push({\n ...output,\n edits: [],\n });\n } catch (error) {\n failures.set(input.file, {\n file: input.file,\n message: error instanceof Error ? error.message : String(error),\n results: error instanceof RewriteFailure ? error.results : [],\n });\n }\n }\n if (sortedChanged && outputs.length) {\n const replacements = new Map(outputs.map((output) => [output.file, output.code]));\n const version = ++this.#version;\n for (const input of inputs) {\n this.workspace.update(input.file, replacements.get(input.file) ?? input.source, version);\n }\n await this.workspace.prepare?.(outputs.map((output) => output.file));\n for (const output of outputs) {\n output.results = await this.workspace.analyze(output.file);\n }\n }\n return {\n outputs,\n failures: inputs.flatMap((input) => {\n const failure = failures.get(input.file);\n return failure ? [failure] : [];\n }),\n };\n }\n\n /**\n * Re-analyzes surviving rewrite outputs after external hooks modify their text, so Stillwind\n * diagnostics match the final buffer contents and positions.\n *\n * @param inputs - Original rewrite inputs, used to restore unmodified or failed targets.\n * @param outputs - Surviving outputs whose `code` has been updated by hooks. Their `results`\n * arrays are replaced in place.\n * @throws If installing, preparing, analyzing, or closing buffers fails.\n */\n async reanalyze(\n inputs: readonly RewriteInput[],\n outputs: readonly RewriteResult[],\n ): Promise<void> {\n if (!outputs.length) {\n return;\n }\n const replacements = new Map(outputs.map((output) => [output.file, output.code]));\n const version = ++this.#version;\n try {\n for (const input of inputs) {\n this.workspace.update(input.file, replacements.get(input.file) ?? input.source, version);\n }\n await this.workspace.prepare?.(outputs.map((output) => output.file));\n for (const output of outputs) {\n output.results = await this.workspace.analyze(output.file);\n }\n } finally {\n for (const input of inputs) {\n this.workspace.closeDocument(input.file);\n }\n }\n }\n\n /**\n * Analyzes one installed buffer and requires matching project answers to produce the same text.\n *\n * @param input - Buffer already installed in the workspace for the current pass.\n * @param operation - Sort or fixes query to apply to the original text of this pass.\n * @returns The first project's edits and all project findings, or unchanged text outside every scope.\n * @throws If analysis is incomplete, syntax is invalid, answers are missing or stale, or projects disagree.\n */\n async #rewriteBuffer(input: RewriteInput, operation: \"sort\" | \"fixes\"): Promise<RewriteResult> {\n const results = await this.workspace.analyze(input.file);\n if (results.some(({ result }) => result.status !== \"complete\")) {\n const reasons = results.flatMap(({ result }) =>\n result.status === \"complete\"\n ? []\n : [result.error ?? result.graph?.unverified[0]?.reason ?? result.status],\n );\n throw new RewriteFailure(\n `Incomplete analysis for ${input.file}: ${reasons.join(\"; \")}`,\n results,\n );\n }\n const syntaxErrors = results.flatMap(({ result }) =>\n result.reports.filter((report) => [\"SW10001\", \"SW10002\"].includes(report.code)),\n );\n if (syntaxErrors.length) {\n throw new RewriteFailure(\n `Cannot rewrite ${input.file}: ${syntaxErrors.map((report) => report.message).join(\"; \")}`,\n results,\n );\n }\n const answers = await this.workspace.query(\n input.file,\n operation === \"sort\"\n ? {\n kind: \"sort\",\n protectedRanges: input.protectedRanges,\n }\n : {\n kind: \"fixes\",\n },\n );\n if (answers.length !== results.length) {\n throw new Error(`Missing rewrite result for ${input.file}`);\n }\n const revision = fingerprint(input.source);\n const candidates = answers.map(({ result }) => {\n if (result.revision !== revision) {\n throw new Error(`Stale edits for ${input.file}`);\n }\n const edits = result.edits ?? [];\n return {\n code: applySourceEdits(input.source, edits),\n edits,\n };\n });\n const first = candidates[0] ?? {\n code: input.source,\n edits: [],\n };\n if (candidates.some((candidate) => candidate.code !== first.code)) {\n throw new Error(`Conflicting project rewrites for ${input.file}`);\n }\n return {\n file: input.file,\n ...first,\n results,\n };\n }\n}\n\n/**\n * Applies edits from the end of the original text after validating their ranges.\n *\n * @param source - Original text from which all edit offsets were measured.\n * @param edits - Half-open ranges with safe integer UTF-16 offsets, in any order. The array is unchanged.\n * @returns Text with every replacement applied.\n * @throws If a range is invalid, outside the source, or overlaps another range.\n */\nexport function applySourceEdits(source: string, edits: readonly EditorEdit[]): string {\n const ordered = [...edits].sort((a, b) => a.start - b.start || a.end - b.end);\n let end = 0;\n for (const edit of ordered) {\n if (\n !Number.isSafeInteger(edit.start) ||\n !Number.isSafeInteger(edit.end) ||\n edit.start < end ||\n edit.end < edit.start ||\n edit.end > source.length\n ) {\n throw new Error(\"Invalid or overlapping source edits\");\n }\n end = edit.end;\n }\n for (const edit of ordered.reverse()) {\n source = source.slice(0, edit.start) + edit.newText + source.slice(edit.end);\n }\n return source;\n}\n"],"mappings":";;;;;AAWA,IAAa,iBAAb,cAAoC,MAAM;CAG7B;CAFX,YACE,SACA,SACA;EACA,MAAM,OAAO;EAFJ,KAAA,UAAA;EAGT,KAAK,OAAO;CACd;AACF;;;;AA0DA,IAAa,iBAAb,MAA4B;CAWP;;CATnB,WAAW;;;;;;;CAQX,YACE,WAKA;EALiB,KAAA,YAAA;CAKhB;;;;;;;;;;;;;CAcH,MAAM,QACJ,QACA,WAC6B;EAC7B,IAAI,IAAI,IAAI,OAAO,KAAK,UAAU,MAAM,IAAI,CAAC,CAAC,CAAC,SAAS,OAAO,QAC7D,MAAM,IAAI,MAAM,8CAA8C;EAEhE,MAAM,gBAAgB,cAAc,SAAS,SAAS;EACtD,IAAI,UAAU;EACd,MAAM,2BAAW,IAAI,IAAgC;EACrD,MAAM,YAAY,IAAI,IAAI,OAAO,KAAK,UAAU,CAAC,MAAM,MAAM,MAAM,MAAM,CAAC,CAAC;EAC3E,MAAM,OAAO,IAAI,IAAI,OAAO,KAAK,UAAU,CAAC,MAAM,sBAAM,IAAI,IAAY,CAAC,CAAC,CAAC;EAC3E,IAAI;GACF,KAAK,UAAU,WAAW;GAC1B,SAAS;IACP,MAAM,WAAW,KAAK,UAAU,CA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