@stillwind/analysis 0.12.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,27 @@
1
1
  # @stillwind/analysis
2
2
 
3
+ ## 0.14.0
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies:
8
+ - @stillwind/config@0.14.0
9
+ - @stillwind/host@0.14.0
10
+ - @stillwind/native@0.14.0
11
+
12
+ ## 0.13.0
13
+
14
+ ### Minor Changes
15
+
16
+ - `stillwind lint`, `fmt`, and `check` now analyze the projects of a configuration in parallel worker processes, so a configuration that lists several projects, such as a monorepo root, finishes sooner. Projects that share a target file are still analyzed together in one process. `lint`, `format`, and `check` in `@stillwind/analysis` accept a `concurrency` option that sets the maximum number of worker processes. By default, the maximum is half of the available parallelism.
17
+
18
+ ### Patch Changes
19
+
20
+ - Updated dependencies:
21
+ - @stillwind/config@0.13.0
22
+ - @stillwind/host@0.13.0
23
+ - @stillwind/native@0.13.0
24
+
3
25
  ## 0.12.0
4
26
 
5
27
  ### Minor Changes
package/dist/node.d.ts CHANGED
@@ -52,6 +52,11 @@ interface RewriteOptions {
52
52
  cwd?: string;
53
53
  /** Additional globs relative to each project root. Omission or an empty list retains all configured targets. */
54
54
  patterns?: string[];
55
+ /**
56
+ * Maximum number of analysis worker processes. Omission selects half of the available
57
+ * parallelism. Projects that share a target are analyzed in the same process.
58
+ */
59
+ concurrency?: number;
55
60
  }
56
61
  /**
57
62
  * Combined lint and formatting check results for one configuration.
@@ -287,12 +292,14 @@ interface LintResult {
287
292
  exitCode: 0 | 1 | 2;
288
293
  }
289
294
  /**
290
- * Analyzes configured target scopes in a child process and closes it before returning.
295
+ * Analyzes configured target scopes in child processes and closes them before returning. Disjoint
296
+ * project groups are analyzed concurrently.
291
297
  *
292
298
  * @param options - Configuration discovery and optional target filters. Omission checks all
293
299
  * configured targets from the process working directory.
294
300
  * @returns Results and an exit code. Readonly lint returns code 2 for empty selection or incomplete analysis.
295
- * @throws If configuration discovery, worker initialization, target enumeration, or cleanup fails.
301
+ * @throws If configuration discovery, worker initialization, target enumeration, or cleanup fails,
302
+ * or if concurrency is invalid.
296
303
  * Fix mode reports failures per target and continues with healthy targets. Empty selection throws.
297
304
  */
298
305
  export declare function lint(options?: RewriteOptions & {
package/dist/node.js CHANGED
@@ -3,6 +3,7 @@ import { r as lintReports } from "./reports-Bu0OQg-C.js";
3
3
  import { readFile, writeFile } from "node:fs/promises";
4
4
  import path from "node:path";
5
5
  import { findConfiguration, findDocumentConfiguration } from "@stillwind/config/node";
6
+ import { availableParallelism } from "node:os";
6
7
  import { fork } from "node:child_process";
7
8
  import process$1 from "node:process";
8
9
  import { fileURLToPath, pathToFileURL } from "node:url";
@@ -94,11 +95,11 @@ var AnalysisWorker = class {
94
95
  * Replaces the child workspace, closing any previously opened hosts first.
95
96
  *
96
97
  * @param config - Configuration path. Relative paths use the child's inherited working directory.
97
- * @returns A promise that resolves after the configuration and project hosts have opened.
98
+ * @returns The number of configured projects, after the configuration and project hosts have opened.
98
99
  * @throws If configuration evaluation, project initialization, or transport fails.
99
100
  */
100
- async open(config) {
101
- await this.request({
101
+ open(config) {
102
+ return this.request({
102
103
  method: "open",
103
104
  config
104
105
  });
@@ -121,13 +122,15 @@ var AnalysisWorker = class {
121
122
  *
122
123
  * @param patterns - Additional globs relative to each project root. Empty or omitted filters
123
124
  * retain every configured target.
125
+ * @param projects - Zero-based indices of the projects to analyze. Omission analyzes every project.
124
126
  * @returns Results in project order and sorted target order within each project.
125
127
  * @throws If the workspace has not opened, enumeration fails, or transport fails.
126
128
  */
127
- lint(patterns) {
129
+ lint(patterns, projects) {
128
130
  return this.request({
129
131
  method: "lint",
130
- patterns
132
+ patterns,
133
+ projects
131
134
  });
132
135
  }
133
136
  /**
@@ -146,6 +149,22 @@ var AnalysisWorker = class {
146
149
  });
147
150
  }
148
151
  /**
152
+ * Enumerates the targets of each project in the opened workspace.
153
+ *
154
+ * @param patterns - Additional project-relative globs. Omission or an empty list retains all targets.
155
+ * @param stylesheets - Adds the stylesheets that each project lints.
156
+ * @returns One list of sorted absolute paths for each project, in project order. A path that
157
+ * several projects include appears in each of their lists.
158
+ * @throws If the workspace has not opened, enumeration fails, or transport fails.
159
+ */
160
+ projectTargets(patterns, stylesheets) {
161
+ return this.request({
162
+ method: "projectTargets",
163
+ patterns,
164
+ stylesheets
165
+ });
166
+ }
167
+ /**
149
168
  * Computes replacements from captured buffers without writing files.
150
169
  *
151
170
  * @param inputs - Distinct absolute target paths and complete original text.
@@ -185,6 +204,134 @@ var AnalysisWorker = class {
185
204
  }
186
205
  }
187
206
  };
207
+ // src/project-workers.ts
208
+ /**
209
+ * Splits configured projects into groups that separate worker processes analyze concurrently.
210
+ *
211
+ * Projects that share a target stay in one group, because a rewrite must compare the answers of
212
+ * every project that includes the target. Groups are balanced by their number of distinct targets.
213
+ *
214
+ * @param targets - Absolute target paths of each project, in project order. Projects without
215
+ * targets are still assigned to a group.
216
+ * @param limit - Maximum number of groups. Values below 1 are treated as 1.
217
+ * @returns Non-empty groups of ascending zero-based project indices, ordered by their first index.
218
+ * Every project index appears in exactly one group. An empty input returns no groups.
219
+ */
220
+ function groupProjects(targets, limit) {
221
+ const parents = targets.map((_, index) => index);
222
+ const root = (index) => {
223
+ while (parents[index] !== index) {
224
+ parents[index] = parents[parents[index]];
225
+ index = parents[index];
226
+ }
227
+ return index;
228
+ };
229
+ const owners = /* @__PURE__ */ new Map();
230
+ for (const [index, files] of targets.entries()) for (const file of files) {
231
+ const owner = owners.get(file);
232
+ if (owner === void 0) owners.set(file, index);
233
+ else parents[root(index)] = root(owner);
234
+ }
235
+ const components = /* @__PURE__ */ new Map();
236
+ for (const [index, files] of targets.entries()) {
237
+ const component = components.get(root(index)) ?? {
238
+ projects: [],
239
+ files: /* @__PURE__ */ new Set()
240
+ };
241
+ component.projects.push(index);
242
+ for (const file of files) component.files.add(file);
243
+ components.set(root(index), component);
244
+ }
245
+ const bins = Array.from({ length: Math.min(components.size, Math.max(1, Math.floor(limit))) }, () => ({
246
+ projects: [],
247
+ weight: 0
248
+ }));
249
+ const ordered = [...components.values()].sort((a, b) => b.files.size - a.files.size || a.projects[0] - b.projects[0]);
250
+ for (const component of ordered) {
251
+ const bin = bins.reduce((lightest, candidate) => candidate.weight < lightest.weight ? candidate : lightest);
252
+ bin.projects.push(...component.projects);
253
+ bin.weight += component.files.size;
254
+ }
255
+ return bins.map((bin) => bin.projects.sort((a, b) => a - b)).filter((projects) => projects.length).sort((a, b) => a[0] - b[0]);
256
+ }
257
+ /**
258
+ * Resolves the maximum number of analysis worker processes.
259
+ *
260
+ * @param concurrency - Requested maximum. Omission selects half of the available parallelism.
261
+ * @returns A positive integer.
262
+ * @throws If concurrency is present and is not a positive integer.
263
+ */
264
+ function analysisConcurrency(concurrency) {
265
+ if (concurrency === void 0) return Math.max(1, Math.floor(availableParallelism() / 2));
266
+ if (!Number.isInteger(concurrency) || concurrency < 1) throw new Error(`Analysis concurrency must be a positive integer: ${concurrency}`);
267
+ return concurrency;
268
+ }
269
+ /**
270
+ * Worker processes that analyze disjoint project groups of one configuration concurrently.
271
+ * Close it after use, also when an operation fails.
272
+ */
273
+ var ProjectWorkers = class ProjectWorkers {
274
+ /** Every started worker, including workers that no group uses. */
275
+ #workers;
276
+ /** Groups in order of their first project index. */
277
+ groups;
278
+ /** Sorted, distinct absolute targets of every group. */
279
+ files;
280
+ constructor(workers, groups) {
281
+ this.#workers = workers;
282
+ this.groups = groups;
283
+ this.files = [...new Set(groups.flatMap((group) => group.files))].sort();
284
+ }
285
+ /**
286
+ * Opens the configuration in one worker, enumerates targets, and opens more workers when the
287
+ * configuration has several project groups.
288
+ *
289
+ * @param config - Absolute configuration path.
290
+ * @param options - Target filters, stylesheet selection, and the maximum number of workers.
291
+ * @returns Workers whose groups partition the selected targets. A group can have no files.
292
+ * @throws If a worker cannot open the configuration, enumeration fails, or concurrency is invalid.
293
+ * Started workers are closed before the error is rethrown.
294
+ */
295
+ static async open(config, options) {
296
+ const limit = analysisConcurrency(options.concurrency);
297
+ const first = new AnalysisWorker();
298
+ const workers = [first];
299
+ try {
300
+ const count = await first.open(config);
301
+ if (Math.min(count, limit) <= 1) {
302
+ const files = await first.targets(options.patterns, options.stylesheets);
303
+ return new ProjectWorkers(workers, [{
304
+ worker: first,
305
+ files
306
+ }]);
307
+ }
308
+ const extra = Array.from({ length: Math.min(count, limit) - 1 }, () => new AnalysisWorker());
309
+ workers.push(...extra);
310
+ const opening = Promise.all(extra.map((worker) => worker.open(config)));
311
+ const [targets] = await Promise.all([first.projectTargets(options.patterns, options.stylesheets), opening]);
312
+ const groups = groupProjects(targets, limit).map((projects, index) => ({
313
+ worker: workers[index],
314
+ projects,
315
+ files: [...new Set(projects.flatMap((project) => targets[project]))].sort()
316
+ }));
317
+ const unused = workers.splice(groups.length);
318
+ await Promise.all(unused.map((worker) => worker.close()));
319
+ return new ProjectWorkers(workers, groups);
320
+ } catch (error) {
321
+ await Promise.allSettled(workers.map((worker) => worker.close()));
322
+ throw error;
323
+ }
324
+ }
325
+ /**
326
+ * Closes every worker and waits for each process to exit.
327
+ *
328
+ * @throws The first cleanup failure after every worker has been closed.
329
+ */
330
+ async close() {
331
+ const failure = (await Promise.allSettled(this.#workers.map((worker) => worker.close()))).find((result) => result.status === "rejected");
332
+ if (failure) throw failure.reason;
333
+ }
334
+ };
188
335
  // src/write.ts
189
336
  /**
190
337
  * Saves changed bytes once per file. Identical buffers perform no filesystem operations.
@@ -216,20 +363,26 @@ async function writeChangedFiles(changes) {
216
363
  // src/rewrite-files.ts
217
364
  /**
218
365
  * Computes all replacements before optionally saving changed files. Fixes return final findings.
366
+ * Disjoint project groups are rewritten concurrently in separate worker processes. A group reads
367
+ * the targets of other groups from disk, not from their buffers of the current pass.
219
368
  *
220
369
  * @param options - Configuration discovery and optional filters within configured target scopes.
221
370
  * @param operation - Utility sorting, converged lint fixes, or converged lint fixes followed by sorting.
222
371
  * @param write - Whether to verify and save changed bytes after every replacement is planned.
223
372
  * @returns Configuration, sorted changed paths, findings, and independent target failures.
224
373
  * Saving reports only paths whose writes succeeded. Check mode reports planned changes.
225
- * @throws If selection is empty, configuration, worker communication, or cleanup fails.
374
+ * @throws If selection is empty, concurrency is invalid, or configuration, worker communication,
375
+ * or cleanup fails.
226
376
  */
227
377
  async function rewriteFiles(options, operation, write, hooks) {
228
378
  const config = resolveRewriteConfig(options);
229
- const worker = new AnalysisWorker();
379
+ const workers = await ProjectWorkers.open(config, {
380
+ patterns: options.patterns,
381
+ stylesheets: true,
382
+ concurrency: options.concurrency
383
+ });
230
384
  try {
231
- await worker.open(config);
232
- const files = await worker.targets(options.patterns, true);
385
+ const files = workers.files;
233
386
  if (!files.length) throw new Error("No analysis targets matched the configured scopes");
234
387
  const failures = [];
235
388
  const originals = /* @__PURE__ */ new Map();
@@ -254,7 +407,15 @@ async function rewriteFiles(options, operation, write, hooks) {
254
407
  });
255
408
  }
256
409
  }
257
- const batch = await worker.rewrite(inputs, operation, hooks);
410
+ const groupOf = new Map(workers.groups.flatMap((group, index) => group.files.map((file) => [file, index])));
411
+ const batches = await Promise.all(workers.groups.map((group, index) => group.worker.rewrite(inputs.filter((input) => groupOf.get(input.file) === index), operation, hooks && group.projects ? {
412
+ ...hooks,
413
+ projects: group.projects
414
+ } : hooks)));
415
+ const batch = {
416
+ outputs: batches.flatMap((entry) => entry.outputs),
417
+ failures: batches.flatMap((entry) => entry.failures)
418
+ };
258
419
  failures.push(...batch.failures);
259
420
  const changes = batch.outputs.map((output) => ({
260
421
  file: output.file,
@@ -277,7 +438,7 @@ async function rewriteFiles(options, operation, write, hooks) {
277
438
  failures
278
439
  };
279
440
  } finally {
280
- await worker.close();
441
+ await workers.close();
281
442
  }
282
443
  }
283
444
  /**
@@ -613,12 +774,14 @@ async function inspect(options = {}) {
613
774
  }
614
775
  // src/lint.ts
615
776
  /**
616
- * Analyzes configured target scopes in a child process and closes it before returning.
777
+ * Analyzes configured target scopes in child processes and closes them before returning. Disjoint
778
+ * project groups are analyzed concurrently.
617
779
  *
618
780
  * @param options - Configuration discovery and optional target filters. Omission checks all
619
781
  * configured targets from the process working directory.
620
782
  * @returns Results and an exit code. Readonly lint returns code 2 for empty selection or incomplete analysis.
621
- * @throws If configuration discovery, worker initialization, target enumeration, or cleanup fails.
783
+ * @throws If configuration discovery, worker initialization, target enumeration, or cleanup fails,
784
+ * or if concurrency is invalid.
622
785
  * Fix mode reports failures per target and continues with healthy targets. Empty selection throws.
623
786
  */
624
787
  async function lint(options = {}) {
@@ -630,17 +793,19 @@ async function lint(options = {}) {
630
793
  };
631
794
  }
632
795
  const config = resolveRewriteConfig(options);
633
- const worker = new AnalysisWorker();
796
+ const workers = await ProjectWorkers.open(config, {
797
+ patterns: options.patterns,
798
+ concurrency: options.concurrency
799
+ });
634
800
  try {
635
- await worker.open(config);
636
- const results = await worker.lint(options.patterns);
801
+ const results = (await Promise.all(workers.groups.map((group) => group.worker.lint(options.patterns, group.projects)))).flat().sort((a, b) => a.project - b.project);
637
802
  return {
638
803
  config,
639
804
  results,
640
805
  exitCode: !results.length || results.some(({ result }) => result.status !== "complete") ? 2 : results.some(({ result }) => result.reports.some((report) => report.severity === "error")) ? 1 : 0
641
806
  };
642
807
  } finally {
643
- await worker.close();
808
+ await workers.close();
644
809
  }
645
810
  }
646
811
  /**
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/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,GAAG,SAAS,SAAiB;GAC/C,UAAQ,OAAO,MAAM,IAAI;EAC3B,CAAC;EACD,KAAK,OAAO,OAAQ,GAAG,SAAS,SAAiB;GAC/C,UAAQ,OAAO,MAAM,IAAI;EAC3B,CAAC;EACD,KAAK,OAAO,GAAG,YAAY,UAAuB;GAChD,MAAM,UAAU,KAAK,SAAS,IAAI,MAAM,EAAE;GAC1C,KAAK,SAAS,OAAO,MAAM,EAAE;GAC7B,IAAI,MAAM,OACR,SAAS,OACP,MAAM,MAAM,UACR,IAAI,eAAe,MAAM,MAAM,SAAS,MAAM,MAAM,OAAO,IAC3D,IAAI,MAAM,MAAM,MAAM,OAAO,CACnC;QAEA,SAAS,QAAQ,MAAM,KAAK;EAEhC,CAAC;EACD,KAAK,OAAO,GAAG,UAAU,UAAU;GACjC,KAAK,MAAM,WAAW,KAAK,SAAS,OAAO,GACzC,QAAQ,OAAO,KAAK;GAEtB,KAAK,SAAS,MAAM;EACtB,CAAC;EACD,KAAK,UAAU,IAAI,SAAS,YAAY;GACtC,KAAK,OAAO,GAAG,UAAU,MAAM,WAAW;IACxC,KAAK,UAAU;IACf,KAAK,MAAM,WAAW,KAAK,SAAS,OAAO,GACzC,QAAQ,uBAAO,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AAc,GAAG;IACzB,CAAC;GAEL;GACA,OAAO,YAAY;IACjB,MAAM,OAAO,MAAM;GACrB;EACF,CAAC;CACH,SAAS,OAAO;EACd,OAAO,IAAI,MAAM,OAAO,KAAK,CAAC;EAC9B,MAAM,OAAO,MAAM;CACrB;AACF;;;;;ACvLA,IAAa,kBAAb,MAA6B;CAWE;;CAT7B,UAAmB,IAAI,eAAe;;CAEtC,SAA2B,QAAQ,QAAQ;;;;;;CAO3C,YAAY,QAAiC;EAAhB,KAAA,SAAA;CAAiB;;;;;;;;;CAU9C,OAAO,OAA6C;EAClD,MAAM,OAAO,KAAK,OAAO,KAAK,YAAY;GACxC,MAAM,KAAK,QAAQ,KAAK,KAAK,MAAM;GACnC,MAAM,EAAE,SAAS,aAAa,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
+ {"version":3,"file":"node.js","names":["process"],"sources":["../src/worker-client.ts","../src/project-workers.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 /** Zero-based indices of the projects to analyze. Omission analyzes every project. */\n projects?: readonly number[];\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 enumerating the targets of each project. */\n method: \"projectTargets\";\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 The number of configured projects, after the configuration and project hosts have opened.\n * @throws If configuration evaluation, project initialization, or transport fails.\n */\n open(config: string): Promise<number> {\n return 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 * @param projects - Zero-based indices of the projects to analyze. Omission analyzes every project.\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[], projects?: readonly number[]): Promise<WorkspaceResult[]> {\n return this.request({\n method: \"lint\",\n patterns,\n projects,\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 * Enumerates the targets of each project 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 One list of sorted absolute paths for each project, in project order. A path that\n * several projects include appears in each of their lists.\n * @throws If the workspace has not opened, enumeration fails, or transport fails.\n */\n projectTargets(patterns?: readonly string[], stylesheets?: boolean): Promise<string[][]> {\n return this.request({\n method: \"projectTargets\",\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 { availableParallelism } from \"node:os\";\n\nimport { AnalysisWorker } from \"./worker-client.ts\";\n\n/**\n * Splits configured projects into groups that separate worker processes analyze concurrently.\n *\n * Projects that share a target stay in one group, because a rewrite must compare the answers of\n * every project that includes the target. Groups are balanced by their number of distinct targets.\n *\n * @param targets - Absolute target paths of each project, in project order. Projects without\n * targets are still assigned to a group.\n * @param limit - Maximum number of groups. Values below 1 are treated as 1.\n * @returns Non-empty groups of ascending zero-based project indices, ordered by their first index.\n * Every project index appears in exactly one group. An empty input returns no groups.\n */\nexport function groupProjects(targets: readonly (readonly string[])[], limit: number): number[][] {\n const parents = targets.map((_, index) => index);\n const root = (index: number): number => {\n while (parents[index] !== index) {\n parents[index] = parents[parents[index]];\n index = parents[index];\n }\n return index;\n };\n const owners = new Map<string, number>();\n for (const [index, files] of targets.entries()) {\n for (const file of files) {\n const owner = owners.get(file);\n if (owner === undefined) {\n owners.set(file, index);\n } else {\n parents[root(index)] = root(owner);\n }\n }\n }\n const components = new Map<number, { projects: number[]; files: Set<string> }>();\n for (const [index, files] of targets.entries()) {\n const component = components.get(root(index)) ?? { projects: [], files: new Set<string>() };\n component.projects.push(index);\n for (const file of files) {\n component.files.add(file);\n }\n components.set(root(index), component);\n }\n // Longest-processing-time assignment: place the largest component in the lightest group.\n const bins = Array.from(\n { length: Math.min(components.size, Math.max(1, Math.floor(limit))) },\n () => ({\n projects: [] as number[],\n weight: 0,\n }),\n );\n const ordered = [...components.values()].sort(\n (a, b) => b.files.size - a.files.size || a.projects[0] - b.projects[0],\n );\n for (const component of ordered) {\n const bin = bins.reduce((lightest, candidate) =>\n candidate.weight < lightest.weight ? candidate : lightest,\n );\n bin.projects.push(...component.projects);\n bin.weight += component.files.size;\n }\n return bins\n .map((bin) => bin.projects.sort((a, b) => a - b))\n .filter((projects) => projects.length)\n .sort((a, b) => a[0] - b[0]);\n}\n\n/**\n * Resolves the maximum number of analysis worker processes.\n *\n * @param concurrency - Requested maximum. Omission selects half of the available parallelism.\n * @returns A positive integer.\n * @throws If concurrency is present and is not a positive integer.\n */\nexport function analysisConcurrency(concurrency?: number): number {\n if (concurrency === undefined) {\n return Math.max(1, Math.floor(availableParallelism() / 2));\n }\n if (!Number.isInteger(concurrency) || concurrency < 1) {\n throw new Error(`Analysis concurrency must be a positive integer: ${concurrency}`);\n }\n return concurrency;\n}\n\n/** One worker process and the configured targets that it analyzes. */\nexport interface ProjectWorkerGroup {\n /** Worker with the complete configuration open. Result project indices are configuration indices. */\n worker: AnalysisWorker;\n /**\n * Zero-based indices of the projects that this worker analyzes, in ascending order. Undefined\n * means every project, when one worker handles the whole configuration.\n */\n projects?: number[];\n /** Sorted, distinct absolute targets of these projects. No other group includes them. */\n files: string[];\n}\n\n/**\n * Worker processes that analyze disjoint project groups of one configuration concurrently.\n * Close it after use, also when an operation fails.\n */\nexport class ProjectWorkers {\n /** Every started worker, including workers that no group uses. */\n readonly #workers: AnalysisWorker[];\n /** Groups in order of their first project index. */\n readonly groups: readonly ProjectWorkerGroup[];\n /** Sorted, distinct absolute targets of every group. */\n readonly files: readonly string[];\n\n private constructor(workers: AnalysisWorker[], groups: ProjectWorkerGroup[]) {\n this.#workers = workers;\n this.groups = groups;\n this.files = [...new Set(groups.flatMap((group) => group.files))].sort();\n }\n\n /**\n * Opens the configuration in one worker, enumerates targets, and opens more workers when the\n * configuration has several project groups.\n *\n * @param config - Absolute configuration path.\n * @param options - Target filters, stylesheet selection, and the maximum number of workers.\n * @returns Workers whose groups partition the selected targets. A group can have no files.\n * @throws If a worker cannot open the configuration, enumeration fails, or concurrency is invalid.\n * Started workers are closed before the error is rethrown.\n */\n static async open(\n config: string,\n options: {\n /** Additional project-relative globs. Omission or an empty list keeps every configured target. */\n patterns?: readonly string[];\n /** Adds the stylesheets that each project lints to the targets. */\n stylesheets?: boolean;\n /** Maximum number of worker processes. Omission selects half of the available parallelism. */\n concurrency?: number;\n },\n ): Promise<ProjectWorkers> {\n const limit = analysisConcurrency(options.concurrency);\n const first = new AnalysisWorker();\n const workers = [first];\n try {\n const count = await first.open(config);\n if (Math.min(count, limit) <= 1) {\n const files = await first.targets(options.patterns, options.stylesheets);\n return new ProjectWorkers(workers, [{ worker: first, files }]);\n }\n // Additional workers evaluate the configuration while the first worker enumerates targets.\n const extra = Array.from({ length: Math.min(count, limit) - 1 }, () => new AnalysisWorker());\n workers.push(...extra);\n const opening = Promise.all(extra.map((worker) => worker.open(config)));\n const [targets] = await Promise.all([\n first.projectTargets(options.patterns, options.stylesheets),\n opening,\n ]);\n const groups = groupProjects(targets, limit).map((projects, index) => ({\n worker: workers[index],\n projects,\n files: [...new Set(projects.flatMap((project) => targets[project]))].sort(),\n }));\n const unused = workers.splice(groups.length);\n await Promise.all(unused.map((worker) => worker.close()));\n return new ProjectWorkers(workers, groups);\n } catch (error) {\n await Promise.allSettled(workers.map((worker) => worker.close()));\n throw error;\n }\n }\n\n /**\n * Closes every worker and waits for each process to exit.\n *\n * @throws The first cleanup failure after every worker has been closed.\n */\n async close(): Promise<void> {\n const results = await Promise.allSettled(this.#workers.map((worker) => worker.close()));\n const failure = results.find((result) => result.status === \"rejected\");\n if (failure) {\n throw failure.reason;\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 { ProjectWorkers } from \"./project-workers.ts\";\nimport type {\n RewriteBatchResult,\n RewriteFileFailure,\n RewriteInput,\n RewriteOperation,\n} from \"./rewrite.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 * Maximum number of analysis worker processes. Omission selects half of the available\n * parallelism. Projects that share a target are analyzed in the same process.\n */\n concurrency?: number;\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 * Disjoint project groups are rewritten concurrently in separate worker processes. A group reads\n * the targets of other groups from disk, not from their buffers of the current pass.\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, concurrency is invalid, or configuration, worker communication,\n * 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 workers = await ProjectWorkers.open(config, {\n patterns: options.patterns,\n stylesheets: true,\n concurrency: options.concurrency,\n });\n try {\n const files = workers.files;\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 groupOf = new Map(\n workers.groups.flatMap((group, index) => group.files.map((file) => [file, index] as const)),\n );\n const batches = await Promise.all(\n workers.groups.map((group, index) =>\n group.worker.rewrite(\n inputs.filter((input) => groupOf.get(input.file) === index),\n operation,\n hooks && group.projects ? { ...hooks, projects: group.projects } : hooks,\n ),\n ),\n );\n const batch: RewriteBatchResult = {\n outputs: batches.flatMap((entry) => entry.outputs),\n failures: batches.flatMap((entry) => entry.failures),\n };\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 workers.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 { ProjectWorkers } from \"./project-workers.ts\";\nimport { lintReports } from \"./reports.ts\";\nimport { resolveRewriteConfig, rewriteFiles, type RewriteOptions } from \"./rewrite-files.ts\";\nimport type { RewriteFileFailure } from \"./rewrite.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 child processes and closes them before returning. Disjoint\n * project groups are analyzed concurrently.\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 * or if concurrency is invalid.\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 workers = await ProjectWorkers.open(config, {\n patterns: options.patterns,\n concurrency: options.concurrency,\n });\n try {\n const results = (\n await Promise.all(\n workers.groups.map((group) => group.worker.lint(options.patterns, group.projects)),\n )\n )\n .flat()\n .sort((a, b) => a.project - b.project);\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 workers.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":";;;;;;;;;;;;;;AA+IA,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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H,SAAS,OAAO;EACd,OAAO,IAAI,MAAM,OAAO,KAAK,CAAC;EAC9B,MAAM,OAAO,MAAM;CACrB;AACF;;;;;ACvLA,IAAa,kBAAb,MAA6B;CAWE;;CAT7B,UAAmB,IAAI,eAAe;;CAEtC,SAA2B,QAAQ,QAAQ;;;;;;CAO3C,YAAY,QAAiC;EAAhB,KAAA,SAAA;CAAiB;;;;;;;;;CAU9C,OAAO,OAA6C;EAClD,MAAM,OAAO,KAAK,OAAO,KAAK,YAAY;GACxC,MAAM,KAAK,QAAQ,KAAK,KAAK,MAAM;GACnC,MAAM,EAAE,SAAS,aAAa,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"}
package/dist/worker.js CHANGED
@@ -23,16 +23,19 @@ var ProjectHookSession = class ProjectHookSession {
23
23
  this.#contexts = contexts;
24
24
  }
25
25
  /**
26
- * Creates contexts for all projects and runs `setup` in project and array order.
27
- * If a `setup` callback throws, earlier initialized hooks are torn down before rethrowing.
26
+ * Creates contexts for all projects and runs `setup` of the selected projects in project and
27
+ * array order. If a `setup` callback throws, earlier initialized hooks are torn down before
28
+ * rethrowing.
28
29
  *
29
30
  * @param projects - Opened workspace projects.
30
31
  * @param command - Invoking CLI command.
31
32
  * @param mode - Write or check mode.
33
+ * @param selected - Zero-based indices of the projects whose hooks run. Omission selects every
34
+ * project.
32
35
  * @returns An open session whose `close()` must be awaited in a `finally` block.
33
36
  * @throws If any hook's `setup` callback throws.
34
37
  */
35
- static async open(projects, command, mode) {
38
+ static async open(projects, command, mode, selected) {
36
39
  const controller = new AbortController();
37
40
  const contexts = projects.map((project) => ({
38
41
  root: project.analysis.host.root,
@@ -44,6 +47,7 @@ var ProjectHookSession = class ProjectHookSession {
44
47
  const session = new ProjectHookSession(contexts);
45
48
  try {
46
49
  for (const [index, project] of projects.entries()) {
50
+ if (selected && !selected.includes(index)) continue;
47
51
  const context = contexts[index];
48
52
  for (const hook of project.config.hooks ?? []) {
49
53
  if (hook.setup) try {
@@ -209,7 +213,8 @@ process.on("disconnect", () => {
209
213
  *
210
214
  * @param request - Operation payload. Open must complete before other operations except close.
211
215
  * @returns The operation result, including a boolean for refresh, or undefined for state changes.
212
- * The targets operation returns sorted, distinct paths.
216
+ * The open operation returns the number of configured projects. The targets operation returns
217
+ * sorted, distinct paths.
213
218
  * @throws If no workspace is open or the selected workspace operation fails.
214
219
  */
215
220
  async function handle(request) {
@@ -218,7 +223,7 @@ async function handle(request) {
218
223
  workspace = void 0;
219
224
  workspace = await AnalysisWorkspace.open(request.config);
220
225
  rewriter = new SourceRewriter(workspace);
221
- return;
226
+ return workspace.projects.length;
222
227
  }
223
228
  if (!workspace) {
224
229
  if (request.method === "close") return;
@@ -229,8 +234,9 @@ async function handle(request) {
229
234
  const files = await Promise.all(workspace.projects.map((project) => workspace.targets(project, request.patterns ? [...request.patterns] : void 0, { stylesheets: request.stylesheets })));
230
235
  return [...new Set(files.flat())].sort();
231
236
  }
237
+ case "projectTargets": return Promise.all(workspace.projects.map((project) => workspace.targets(project, request.patterns ? [...request.patterns] : void 0, { stylesheets: request.stylesheets })));
232
238
  case "rewrite": return runRewriteWithHooks(workspace, rewriter, request.inputs, request.operation, request.hooks);
233
- case "lint": return workspace.lint(request.patterns ? [...request.patterns] : void 0);
239
+ case "lint": return workspace.lint(request.patterns ? [...request.patterns] : void 0, request.projects);
234
240
  case "analyze": return workspace.analyze(request.file);
235
241
  case "prepare": return workspace.prepare(request.files);
236
242
  case "query": return workspace.query(request.file, request.request);
@@ -289,7 +295,7 @@ async function runRewriteWithHooks(currentWorkspace, currentRewriter, inputs, op
289
295
  const batch = await currentRewriter.rewrite(inputs, operation);
290
296
  if (!hooks || !hasActiveHooks(currentWorkspace.projects)) return batch;
291
297
  const originals = new Map(inputs.map((input) => [input.file, input.source]));
292
- const session = await ProjectHookSession.open(currentWorkspace.projects, hooks.command, hooks.mode);
298
+ const session = await ProjectHookSession.open(currentWorkspace.projects, hooks.command, hooks.mode, hooks.projects);
293
299
  try {
294
300
  const formatted = await applyFormatHooks(currentWorkspace.projects, batch, originals, session);
295
301
  if (hooks.mode === "write" && hooks.command === "check" && formatted.changed && formatted.outputs.length) await currentRewriter.reanalyze(inputs, formatted.outputs);
@@ -1 +1 @@
1
- {"version":3,"file":"worker.js","names":[],"sources":["../src/hooks.ts","../src/worker.ts"],"sourcesContent":["import type { AnalysisHook, HookCommand, HookContext, HookMode } from \"@stillwind/config\";\nimport type { WorkspaceProject } from \"@stillwind/host\";\n\nimport type { RewriteBatchResult, RewriteFileFailure, RewriteResult } from \"./rewrite.ts\";\n\n/** Options selecting which project hooks run for a worker rewrite operation. */\nexport interface HookRunOptions {\n /** CLI command invoking the hooks. */\n command: HookCommand;\n /** Whether modified buffers will be written to disk or only checked. */\n mode: HookMode;\n}\n\n/**\n * Tests whether any project in the workspace declares at least one hook.\n *\n * @param projects - Opened workspace projects.\n * @returns True when at least one project has a configured hook.\n */\nexport function hasActiveHooks(projects: readonly WorkspaceProject[]): boolean {\n return projects.some((project) => (project.config.hooks?.length ?? 0) > 0);\n}\n\n/**\n * Manages per-project hook contexts and `setup` / `teardown` lifetimes for one command run.\n */\nexport class ProjectHookSession {\n readonly #contexts: readonly HookContext[];\n readonly #started: { hook: AnalysisHook; context: HookContext }[] = [];\n\n private constructor(contexts: readonly HookContext[]) {\n this.#contexts = contexts;\n }\n\n /**\n * Creates contexts for all projects and runs `setup` in project and array order.\n * If a `setup` callback throws, earlier initialized hooks are torn down before rethrowing.\n *\n * @param projects - Opened workspace projects.\n * @param command - Invoking CLI command.\n * @param mode - Write or check mode.\n * @returns An open session whose `close()` must be awaited in a `finally` block.\n * @throws If any hook's `setup` callback throws.\n */\n static async open(\n projects: readonly WorkspaceProject[],\n command: HookCommand,\n mode: HookMode,\n ): Promise<ProjectHookSession> {\n const controller = new AbortController();\n const contexts: HookContext[] = projects.map((project) => ({\n root: project.analysis.host.root,\n ...(project.config.name !== undefined ? { project: project.config.name } : {}),\n command,\n mode,\n signal: controller.signal,\n }));\n const session = new ProjectHookSession(contexts);\n try {\n for (const [index, project] of projects.entries()) {\n const context = contexts[index];\n for (const hook of project.config.hooks ?? []) {\n if (hook.setup) {\n try {\n await hook.setup(context);\n } catch (error) {\n throw new Error(\n `Hook \"${hook.name}\" setup failed: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n }\n session.#started.push({ hook, context });\n }\n }\n return session;\n } catch (error) {\n await session.close().catch(() => undefined);\n throw error;\n }\n }\n\n /**\n * Returns the immutable hook context for a project index.\n *\n * @param projectIndex - Zero-based project index in the workspace.\n * @returns The project's hook context.\n */\n context(projectIndex: number): HookContext {\n return this.#contexts[projectIndex];\n }\n\n /**\n * Runs `teardown` in reverse initialization order for all hooks whose `setup` succeeded.\n *\n * @throws The first teardown error after attempting to tear down every remaining hook.\n */\n async close(): Promise<void> {\n let firstError: unknown;\n for (let index = this.#started.length - 1; index >= 0; index -= 1) {\n const { hook, context } = this.#started[index];\n if (!hook.teardown) {\n continue;\n }\n try {\n await hook.teardown(context);\n } catch (error) {\n firstError ??= new Error(\n `Hook \"${hook.name}\" teardown failed: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n }\n this.#started.length = 0;\n if (firstError !== undefined) {\n throw firstError;\n }\n }\n}\n\n/**\n * Tests whether two hook arrays contain the exact same hook object references in the same order.\n */\nfunction sameHookList(a: readonly AnalysisHook[], b: readonly AnalysisHook[]): boolean {\n return a.length === b.length && a.every((hook, index) => hook === b[index]);\n}\n\n/**\n * Runs one project's format hook pipeline over a single buffer.\n */\nasync function runProjectFormatHooks(\n hooks: readonly AnalysisHook[],\n file: string,\n initialCode: string,\n original: string,\n context: HookContext,\n): Promise<string> {\n let code = initialCode;\n for (const hook of hooks) {\n let next: unknown;\n try {\n next = await hook.format!(\n {\n path: file,\n code,\n original,\n changed: code !== original,\n },\n context,\n );\n } catch (error) {\n throw new Error(\n `Hook \"${hook.name}\" failed for ${file}: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n if (typeof next === \"string\") {\n code = next;\n } else if (next !== undefined) {\n throw new Error(`Hook \"${hook.name}\" format must return a string or undefined`);\n }\n }\n return code;\n}\n\n/**\n * Applies project `format` hooks in memory to surviving rewrite outputs.\n *\n * When a file belongs to multiple projects:\n * - If every owning project has the exact same format hook list (by object identity), the pipeline\n * runs once.\n * - Otherwise, each owning project runs its own pipeline and conflicting results fail that file.\n *\n * @param projects - Opened workspace projects.\n * @param batch - Rewrite outputs and existing failures.\n * @param originals - Original file text read from disk, keyed by absolute file path.\n * @param session - Open hook session supplying per-project contexts.\n * @returns Updated outputs, combined failures, and whether any output buffer changed.\n */\nexport async function applyFormatHooks(\n projects: readonly WorkspaceProject[],\n batch: RewriteBatchResult,\n originals: ReadonlyMap<string, string>,\n session: ProjectHookSession,\n): Promise<{\n outputs: RewriteResult[];\n failures: RewriteFileFailure[];\n changed: boolean;\n}> {\n const outputs: RewriteResult[] = [];\n const failures: RewriteFileFailure[] = [...batch.failures];\n let changed = false;\n\n for (const output of batch.outputs) {\n const projectIndices = [...new Set(output.results.map((entry) => entry.project))];\n const pipelines = projectIndices.map((projectIndex) => ({\n projectIndex,\n hooks: (projects[projectIndex]?.config.hooks ?? []).filter(\n (hook) => typeof hook.format === \"function\",\n ),\n }));\n if (!pipelines.some((entry) => entry.hooks.length > 0)) {\n outputs.push(output);\n continue;\n }\n\n const original = originals.get(output.file) ?? output.code;\n try {\n let nextCode: string;\n const first = pipelines[0];\n if (pipelines.every((entry) => sameHookList(entry.hooks, first.hooks))) {\n nextCode = await runProjectFormatHooks(\n first.hooks,\n output.file,\n output.code,\n original,\n session.context(first.projectIndex),\n );\n } else {\n const candidates: string[] = [];\n for (const entry of pipelines) {\n candidates.push(\n entry.hooks.length\n ? await runProjectFormatHooks(\n entry.hooks,\n output.file,\n output.code,\n original,\n session.context(entry.projectIndex),\n )\n : output.code,\n );\n }\n nextCode = candidates[0];\n if (candidates.some((candidate) => candidate !== nextCode)) {\n throw new Error(`Conflicting project format hooks for ${output.file}`);\n }\n }\n if (nextCode !== output.code) {\n changed = true;\n }\n outputs.push({\n ...output,\n code: nextCode,\n edits: nextCode === output.code ? output.edits : [],\n });\n } catch (error) {\n failures.push({\n file: output.file,\n message: error instanceof Error ? error.message : String(error),\n results: output.results,\n });\n }\n }\n\n return { outputs, failures, changed };\n}\n","import path from \"node:path\";\nimport process from \"node:process\";\n\nimport { resolveLintConfig } from \"@stillwind/config\";\nimport { AnalysisWorkspace } from \"@stillwind/host\";\n\nimport {\n applyFormatHooks,\n hasActiveHooks,\n ProjectHookSession,\n type HookRunOptions,\n} from \"./hooks.ts\";\nimport type { ActiveLintRule, ProjectInfo } from \"./info.ts\";\nimport {\n RewriteFailure,\n SourceRewriter,\n type RewriteBatchResult,\n type RewriteInput,\n type RewriteOperation,\n} from \"./rewrite.ts\";\nimport type { WorkerRequest } from \"./worker-client.ts\";\n\nlet workspace: AnalysisWorkspace | undefined;\nlet rewriter: SourceRewriter | undefined;\n\nprocess.on(\n \"message\",\n (message: {\n /** Sequence number copied into the IPC reply. */\n id: number;\n /** Operation payload sent by AnalysisWorker. Callers serialize workspace replacement and rewrites. */\n request: WorkerRequest;\n }) => {\n void handle(message.request).then(\n (value) => {\n process.send?.({ id: message.id, value }, () => {\n if (message.request.method === \"close\") {\n process.disconnect?.();\n }\n });\n },\n (error: unknown) => {\n process.send?.({\n id: message.id,\n error: {\n message: error instanceof Error ? error.message : String(error),\n results: error instanceof RewriteFailure ? error.results : undefined,\n },\n });\n },\n );\n },\n);\n\nprocess.on(\"disconnect\", () => {\n void Promise.resolve(workspace?.close()).finally(() => {\n process.exit();\n });\n});\n\n/**\n * Dispatches one IPC operation against the child-owned workspace and rewriter.\n *\n * @param request - Operation payload. Open must complete before other operations except close.\n * @returns The operation result, including a boolean for refresh, or undefined for state changes.\n * The targets operation returns sorted, distinct paths.\n * @throws If no workspace is open or the selected workspace operation fails.\n */\nasync function handle(request: WorkerRequest): Promise<unknown> {\n if (request.method === \"open\") {\n await workspace?.close();\n workspace = undefined;\n workspace = await AnalysisWorkspace.open(request.config);\n rewriter = new SourceRewriter(workspace);\n return undefined;\n }\n\n if (!workspace) {\n if (request.method === \"close\") {\n return undefined;\n }\n throw new Error(\"Stillwind workspace has not been opened\");\n }\n\n switch (request.method) {\n case \"targets\": {\n const files = await Promise.all(\n workspace.projects.map((project) =>\n workspace!.targets(project, request.patterns ? [...request.patterns] : undefined, {\n stylesheets: request.stylesheets,\n }),\n ),\n );\n return [...new Set(files.flat())].sort();\n }\n\n case \"rewrite\":\n return runRewriteWithHooks(\n workspace,\n rewriter!,\n request.inputs,\n request.operation,\n request.hooks,\n );\n\n case \"lint\":\n return workspace.lint(request.patterns ? [...request.patterns] : undefined);\n\n case \"analyze\":\n return workspace.analyze(request.file);\n\n case \"prepare\":\n return workspace.prepare(request.files);\n\n case \"query\":\n return workspace.query(request.file, request.request);\n\n case \"info\": {\n const projects: ProjectInfo[] = [];\n for (const [index, project] of workspace.projects.entries()) {\n const matched = await workspace.targets(project);\n const resolved = resolveLintConfig(project.config.lint).rules;\n const lint: Record<string, ActiveLintRule> = {};\n for (const rule of Object.keys(resolved).sort()) {\n const setting = resolved[rule as keyof typeof resolved];\n if (typeof setting === \"string\") {\n if (setting !== \"off\") {\n lint[rule] = setting;\n }\n } else if (setting.severity !== \"off\") {\n lint[rule] = setting as ActiveLintRule;\n }\n }\n projects.push({\n project: index,\n ...(project.config.name ? { name: project.config.name } : {}),\n root: project.analysis.host.root,\n css: path.resolve(project.analysis.host.root, project.config.css),\n files: [...project.config.files],\n exclude: [...(project.config.exclude ?? [])],\n matchedFiles: matched.length,\n plugins: (project.config.plugins ?? []).map((plugin) => plugin.name),\n hooks: (project.config.hooks ?? []).map((hook) => hook.name),\n sort: project.config.sort !== false,\n typeFacts: project.config.typeFacts !== false,\n lint,\n });\n }\n return projects;\n }\n\n case \"designSystem\":\n return workspace.designSystem(request.request);\n\n case \"update\":\n workspace.update(request.file, request.source, request.version);\n return undefined;\n\n case \"closeDocument\":\n workspace.closeDocument(request.file);\n return undefined;\n\n case \"invalidate\":\n workspace.invalidate();\n return undefined;\n\n case \"refresh\":\n return workspace.refresh(request.files);\n\n case \"affects\":\n return workspace.affects(request.files);\n\n case \"close\":\n await workspace.close();\n workspace = undefined;\n return undefined;\n }\n}\n\n/**\n * Runs Stillwind rewriting followed by configured project `format` hooks for CLI `fmt` and `check`\n * commands.\n */\nasync function runRewriteWithHooks(\n currentWorkspace: AnalysisWorkspace,\n currentRewriter: SourceRewriter,\n inputs: readonly RewriteInput[],\n operation: RewriteOperation,\n hooks: HookRunOptions | undefined,\n): Promise<RewriteBatchResult> {\n const batch = await currentRewriter.rewrite(inputs, operation);\n if (!hooks || !hasActiveHooks(currentWorkspace.projects)) {\n return batch;\n }\n\n const originals = new Map(inputs.map((input) => [input.file, input.source]));\n const session = await ProjectHookSession.open(\n currentWorkspace.projects,\n hooks.command,\n hooks.mode,\n );\n try {\n const formatted = await applyFormatHooks(currentWorkspace.projects, batch, originals, session);\n if (\n hooks.mode === \"write\" &&\n hooks.command === \"check\" &&\n formatted.changed &&\n formatted.outputs.length\n ) {\n await currentRewriter.reanalyze(inputs, formatted.outputs);\n }\n return {\n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UAAU,aAAa,QAAQ,OAAO;EAE/C,KAAK;GACH,UAAU,OAAO,QAAQ,MAAM,QAAQ,QAAQ,QAAQ,OAAO;GAC9D;EAEF,KAAK;GACH,UAAU,cAAc,QAAQ,IAAI;GACpC;EAEF,KAAK;GACH,UAAU,WAAW;GACrB;EAEF,KAAK,WACH,OAAO,UAAU,QAAQ,QAAQ,KAAK;EAExC,KAAK,WACH,OAAO,UAAU,QAAQ,QAAQ,KAAK;EAExC,KAAK;GACH,MAAM,UAAU,MAAM;GACtB,YAAY,KAAA;GACZ;CACJ;AACF;;;;;AAMA,eAAe,oBACb,kBACA,iBACA,QACA,WACA,OAC6B;CAC7B,MAAM,QAAQ,MAAM,gBAAgB,QAAQ,QAAQ,SAAS;CAC7D,IAAI,CAAC,SAAS,CAAC,eAAe,iBAAiB,QAAQ,GACrD,OAAO;CAGT,MAAM,YAAY,IAAI,IAAI,OAAO,KAAK,UAAU,CAAC,MAAM,MAAM,MAAM,MAAM,CAAC,CAAC;CAC3E,MAAM,UAAU,MAAM,mBAAmB,KACvC,iBAAiB,UACjB,MAAM,SACN,MAAM,IACR;CACA,IAAI;EACF,MAAM,YAAY,MAAM,iBAAiB,iBAAiB,UAAU,OAAO,WAAW,OAAO;EAC7F,IACE,MAAM,SAAS,WACf,MAAM,YAAY,WAClB,UAAU,WACV,UAAU,QAAQ,QAElB,MAAM,gBAAgB,UAAU,QAAQ,UAAU,OAAO;EAE3D,OAAO;GACL,SAAS,UAAU;GACnB,UAAU,UAAU;EACtB;CACF,UAAU;EACR,MAAM,QAAQ,MAAM;CACtB;AACF"}
1
+ {"version":3,"file":"worker.js","names":[],"sources":["../src/hooks.ts","../src/worker.ts"],"sourcesContent":["import type { AnalysisHook, HookCommand, HookContext, HookMode } from \"@stillwind/config\";\nimport type { WorkspaceProject } from \"@stillwind/host\";\n\nimport type { RewriteBatchResult, RewriteFileFailure, RewriteResult } from \"./rewrite.ts\";\n\n/** Options selecting which project hooks run for a worker rewrite operation. */\nexport interface HookRunOptions {\n /** CLI command invoking the hooks. */\n command: HookCommand;\n /** Whether modified buffers will be written to disk or only checked. */\n mode: HookMode;\n /**\n * Zero-based indices of the projects whose hooks this rewrite sets up. Omission selects every\n * project. Each project must be selected in exactly one concurrent rewrite, so its `setup` and\n * `teardown` run once per command.\n */\n projects?: readonly number[];\n}\n\n/**\n * Tests whether any project in the workspace declares at least one hook.\n *\n * @param projects - Opened workspace projects.\n * @returns True when at least one project has a configured hook.\n */\nexport function hasActiveHooks(projects: readonly WorkspaceProject[]): boolean {\n return projects.some((project) => (project.config.hooks?.length ?? 0) > 0);\n}\n\n/**\n * Manages per-project hook contexts and `setup` / `teardown` lifetimes for one command run.\n */\nexport class ProjectHookSession {\n readonly #contexts: readonly HookContext[];\n readonly #started: { hook: AnalysisHook; context: HookContext }[] = [];\n\n private constructor(contexts: readonly HookContext[]) {\n this.#contexts = contexts;\n }\n\n /**\n * Creates contexts for all projects and runs `setup` of the selected projects in project and\n * array order. If a `setup` callback throws, earlier initialized hooks are torn down before\n * rethrowing.\n *\n * @param projects - Opened workspace projects.\n * @param command - Invoking CLI command.\n * @param mode - Write or check mode.\n * @param selected - Zero-based indices of the projects whose hooks run. Omission selects every\n * project.\n * @returns An open session whose `close()` must be awaited in a `finally` block.\n * @throws If any hook's `setup` callback throws.\n */\n static async open(\n projects: readonly WorkspaceProject[],\n command: HookCommand,\n mode: HookMode,\n selected?: readonly number[],\n ): Promise<ProjectHookSession> {\n const controller = new AbortController();\n const contexts: HookContext[] = projects.map((project) => ({\n root: project.analysis.host.root,\n ...(project.config.name !== undefined ? { project: project.config.name } : {}),\n command,\n mode,\n signal: controller.signal,\n }));\n const session = new ProjectHookSession(contexts);\n try {\n for (const [index, project] of projects.entries()) {\n if (selected && !selected.includes(index)) {\n continue;\n }\n const context = contexts[index];\n for (const hook of project.config.hooks ?? []) {\n if (hook.setup) {\n try {\n await hook.setup(context);\n } catch (error) {\n throw new Error(\n `Hook \"${hook.name}\" setup failed: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n }\n session.#started.push({ hook, context });\n }\n }\n return session;\n } catch (error) {\n await session.close().catch(() => undefined);\n throw error;\n }\n }\n\n /**\n * Returns the immutable hook context for a project index.\n *\n * @param projectIndex - Zero-based project index in the workspace.\n * @returns The project's hook context.\n */\n context(projectIndex: number): HookContext {\n return this.#contexts[projectIndex];\n }\n\n /**\n * Runs `teardown` in reverse initialization order for all hooks whose `setup` succeeded.\n *\n * @throws The first teardown error after attempting to tear down every remaining hook.\n */\n async close(): Promise<void> {\n let firstError: unknown;\n for (let index = this.#started.length - 1; index >= 0; index -= 1) {\n const { hook, context } = this.#started[index];\n if (!hook.teardown) {\n continue;\n }\n try {\n await hook.teardown(context);\n } catch (error) {\n firstError ??= new Error(\n `Hook \"${hook.name}\" teardown failed: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n }\n this.#started.length = 0;\n if (firstError !== undefined) {\n throw firstError;\n }\n }\n}\n\n/**\n * Tests whether two hook arrays contain the exact same hook object references in the same order.\n */\nfunction sameHookList(a: readonly AnalysisHook[], b: readonly AnalysisHook[]): boolean {\n return a.length === b.length && a.every((hook, index) => hook === b[index]);\n}\n\n/**\n * Runs one project's format hook pipeline over a single buffer.\n */\nasync function runProjectFormatHooks(\n hooks: readonly AnalysisHook[],\n file: string,\n initialCode: string,\n original: string,\n context: HookContext,\n): Promise<string> {\n let code = initialCode;\n for (const hook of hooks) {\n let next: unknown;\n try {\n next = await hook.format!(\n {\n path: file,\n code,\n original,\n changed: code !== original,\n },\n context,\n );\n } catch (error) {\n throw new Error(\n `Hook \"${hook.name}\" failed for ${file}: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n if (typeof next === \"string\") {\n code = next;\n } else if (next !== undefined) {\n throw new Error(`Hook \"${hook.name}\" format must return a string or undefined`);\n }\n }\n return code;\n}\n\n/**\n * Applies project `format` hooks in memory to surviving rewrite outputs.\n *\n * When a file belongs to multiple projects:\n * - If every owning project has the exact same format hook list (by object identity), the pipeline\n * runs once.\n * - Otherwise, each owning project runs its own pipeline and conflicting results fail that file.\n *\n * @param projects - Opened workspace projects.\n * @param batch - Rewrite outputs and existing failures.\n * @param originals - Original file text read from disk, keyed by absolute file path.\n * @param session - Open hook session supplying per-project contexts.\n * @returns Updated outputs, combined failures, and whether any output buffer changed.\n */\nexport async function applyFormatHooks(\n projects: readonly WorkspaceProject[],\n batch: RewriteBatchResult,\n originals: ReadonlyMap<string, string>,\n session: ProjectHookSession,\n): Promise<{\n outputs: RewriteResult[];\n failures: RewriteFileFailure[];\n changed: boolean;\n}> {\n const outputs: RewriteResult[] = [];\n const failures: RewriteFileFailure[] = [...batch.failures];\n let changed = false;\n\n for (const output of batch.outputs) {\n const projectIndices = [...new Set(output.results.map((entry) => entry.project))];\n const pipelines = projectIndices.map((projectIndex) => ({\n projectIndex,\n hooks: (projects[projectIndex]?.config.hooks ?? []).filter(\n (hook) => typeof hook.format === \"function\",\n ),\n }));\n if (!pipelines.some((entry) => entry.hooks.length > 0)) {\n outputs.push(output);\n continue;\n }\n\n const original = originals.get(output.file) ?? output.code;\n try {\n let nextCode: string;\n const first = pipelines[0];\n if (pipelines.every((entry) => sameHookList(entry.hooks, first.hooks))) {\n nextCode = await runProjectFormatHooks(\n first.hooks,\n output.file,\n output.code,\n original,\n session.context(first.projectIndex),\n );\n } else {\n const candidates: string[] = [];\n for (const entry of pipelines) {\n candidates.push(\n entry.hooks.length\n ? await runProjectFormatHooks(\n entry.hooks,\n output.file,\n output.code,\n original,\n session.context(entry.projectIndex),\n )\n : output.code,\n );\n }\n nextCode = candidates[0];\n if (candidates.some((candidate) => candidate !== nextCode)) {\n throw new Error(`Conflicting project format hooks for ${output.file}`);\n }\n }\n if (nextCode !== output.code) {\n changed = true;\n }\n outputs.push({\n ...output,\n code: nextCode,\n edits: nextCode === output.code ? output.edits : [],\n });\n } catch (error) {\n failures.push({\n file: output.file,\n message: error instanceof Error ? error.message : String(error),\n results: output.results,\n });\n }\n }\n\n return { outputs, failures, changed };\n}\n","import path from \"node:path\";\nimport process from \"node:process\";\n\nimport { resolveLintConfig } from \"@stillwind/config\";\nimport { AnalysisWorkspace } from \"@stillwind/host\";\n\nimport {\n applyFormatHooks,\n hasActiveHooks,\n ProjectHookSession,\n type HookRunOptions,\n} from \"./hooks.ts\";\nimport type { ActiveLintRule, ProjectInfo } from \"./info.ts\";\nimport {\n RewriteFailure,\n SourceRewriter,\n type RewriteBatchResult,\n type RewriteInput,\n type RewriteOperation,\n} from \"./rewrite.ts\";\nimport type { WorkerRequest } from \"./worker-client.ts\";\n\nlet workspace: AnalysisWorkspace | undefined;\nlet rewriter: SourceRewriter | undefined;\n\nprocess.on(\n \"message\",\n (message: {\n /** Sequence number copied into the IPC reply. */\n id: number;\n /** Operation payload sent by AnalysisWorker. Callers serialize workspace replacement and rewrites. */\n request: WorkerRequest;\n }) => {\n void handle(message.request).then(\n (value) => {\n process.send?.({ id: message.id, value }, () => {\n if (message.request.method === \"close\") {\n process.disconnect?.();\n }\n });\n },\n (error: unknown) => {\n process.send?.({\n id: message.id,\n error: {\n message: error instanceof Error ? error.message : String(error),\n results: error instanceof RewriteFailure ? error.results : undefined,\n },\n });\n },\n );\n },\n);\n\nprocess.on(\"disconnect\", () => {\n void Promise.resolve(workspace?.close()).finally(() => {\n process.exit();\n });\n});\n\n/**\n * Dispatches one IPC operation against the child-owned workspace and rewriter.\n *\n * @param request - Operation payload. Open must complete before other operations except close.\n * @returns The operation result, including a boolean for refresh, or undefined for state changes.\n * The open operation returns the number of configured projects. The targets operation returns\n * sorted, distinct paths.\n * @throws If no workspace is open or the selected workspace operation fails.\n */\nasync function handle(request: WorkerRequest): Promise<unknown> {\n if (request.method === \"open\") {\n await workspace?.close();\n workspace = undefined;\n workspace = await AnalysisWorkspace.open(request.config);\n rewriter = new SourceRewriter(workspace);\n return workspace.projects.length;\n }\n\n if (!workspace) {\n if (request.method === \"close\") {\n return undefined;\n }\n throw new Error(\"Stillwind workspace has not been opened\");\n }\n\n switch (request.method) {\n case \"targets\": {\n const files = await Promise.all(\n workspace.projects.map((project) =>\n workspace!.targets(project, request.patterns ? [...request.patterns] : undefined, {\n stylesheets: request.stylesheets,\n }),\n ),\n );\n return [...new Set(files.flat())].sort();\n }\n\n case \"projectTargets\":\n return Promise.all(\n workspace.projects.map((project) =>\n workspace!.targets(project, request.patterns ? [...request.patterns] : undefined, {\n stylesheets: request.stylesheets,\n }),\n ),\n );\n\n case \"rewrite\":\n return runRewriteWithHooks(\n workspace,\n rewriter!,\n request.inputs,\n request.operation,\n request.hooks,\n );\n\n case \"lint\":\n return workspace.lint(request.patterns ? [...request.patterns] : undefined, request.projects);\n\n case \"analyze\":\n return workspace.analyze(request.file);\n\n case \"prepare\":\n return workspace.prepare(request.files);\n\n case \"query\":\n return workspace.query(request.file, request.request);\n\n case \"info\": {\n const projects: ProjectInfo[] = [];\n for (const [index, project] of workspace.projects.entries()) {\n const matched = await workspace.targets(project);\n const resolved = resolveLintConfig(project.config.lint).rules;\n const lint: Record<string, ActiveLintRule> = {};\n for (const rule of Object.keys(resolved).sort()) {\n const setting = resolved[rule as keyof typeof resolved];\n if (typeof setting === \"string\") {\n if (setting !== \"off\") {\n lint[rule] = setting;\n }\n } else if (setting.severity !== \"off\") {\n lint[rule] = setting as ActiveLintRule;\n }\n }\n projects.push({\n project: index,\n ...(project.config.name ? { name: project.config.name } : {}),\n root: project.analysis.host.root,\n css: path.resolve(project.analysis.host.root, project.config.css),\n files: [...project.config.files],\n exclude: [...(project.config.exclude ?? [])],\n matchedFiles: matched.length,\n plugins: (project.config.plugins ?? []).map((plugin) => plugin.name),\n hooks: (project.config.hooks ?? []).map((hook) => hook.name),\n sort: project.config.sort !== false,\n typeFacts: project.config.typeFacts !== false,\n lint,\n });\n }\n return projects;\n }\n\n case \"designSystem\":\n return workspace.designSystem(request.request);\n\n case \"update\":\n workspace.update(request.file, request.source, request.version);\n return undefined;\n\n case \"closeDocument\":\n workspace.closeDocument(request.file);\n return undefined;\n\n case \"invalidate\":\n workspace.invalidate();\n return undefined;\n\n case \"refresh\":\n return workspace.refresh(request.files);\n\n case \"affects\":\n return workspace.affects(request.files);\n\n case \"close\":\n await workspace.close();\n workspace = undefined;\n return undefined;\n }\n}\n\n/**\n * Runs Stillwind rewriting followed by configured project `format` hooks for CLI `fmt` and `check`\n * commands.\n */\nasync function runRewriteWithHooks(\n currentWorkspace: AnalysisWorkspace,\n currentRewriter: SourceRewriter,\n inputs: readonly RewriteInput[],\n operation: RewriteOperation,\n hooks: HookRunOptions | undefined,\n): Promise<RewriteBatchResult> {\n const batch = await currentRewriter.rewrite(inputs, operation);\n if (!hooks || !hasActiveHooks(currentWorkspace.projects)) {\n return batch;\n }\n\n const originals = new Map(inputs.map((input) => [input.file, input.source]));\n const session = await ProjectHookSession.open(\n currentWorkspace.projects,\n hooks.command,\n hooks.mode,\n hooks.projects,\n );\n try {\n const formatted = await applyFormatHooks(currentWorkspace.projects, batch, originals, session);\n if (\n hooks.mode === \"write\" &&\n hooks.command === \"check\" &&\n formatted.changed &&\n formatted.outputs.length\n ) {\n await currentRewriter.reanalyze(inputs, formatted.outputs);\n }\n return {\n outputs: formatted.outputs,\n failures: formatted.failures,\n };\n } finally {\n await session.close();\n }\n}\n"],"mappings":";;;;;;;;;;;;AAyBA,SAAgB,eAAe,UAAgD;CAC7E,OAAO,SAAS,MAAM,aAAa,QAAQ,OAAO,OAAO,UAAU,KAAK,CAAC;AAC3E;;;;AAKA,IAAa,qBAAb,MAAa,mBAAmB;CAC9B;CACA,WAAoE,CAAC;CAErE,YAAoB,UAAkC;EACpD,KAAK,YAAY;CACnB;;;;;;;;;;;;;;CAeA,aAAa,KACX,UACA,SACA,MACA,UAC6B;EAC7B,MAAM,aAAa,IAAI,gBAAgB;EACvC,MAAM,WAA0B,SAAS,KAAK,aAAa;GACzD,MAAM,QAAQ,SAAS,KAAK;GAC5B,GAAI,QAAQ,OAAO,SAAS,KAAA,IAAY,E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QAAQ,KAAK;EAExC,KAAK,WACH,OAAO,UAAU,QAAQ,QAAQ,KAAK;EAExC,KAAK;GACH,MAAM,UAAU,MAAM;GACtB,YAAY,KAAA;GACZ;CACJ;AACF;;;;;AAMA,eAAe,oBACb,kBACA,iBACA,QACA,WACA,OAC6B;CAC7B,MAAM,QAAQ,MAAM,gBAAgB,QAAQ,QAAQ,SAAS;CAC7D,IAAI,CAAC,SAAS,CAAC,eAAe,iBAAiB,QAAQ,GACrD,OAAO;CAGT,MAAM,YAAY,IAAI,IAAI,OAAO,KAAK,UAAU,CAAC,MAAM,MAAM,MAAM,MAAM,CAAC,CAAC;CAC3E,MAAM,UAAU,MAAM,mBAAmB,KACvC,iBAAiB,UACjB,MAAM,SACN,MAAM,MACN,MAAM,QACR;CACA,IAAI;EACF,MAAM,YAAY,MAAM,iBAAiB,iBAAiB,UAAU,OAAO,WAAW,OAAO;EAC7F,IACE,MAAM,SAAS,WACf,MAAM,YAAY,WAClB,UAAU,WACV,UAAU,QAAQ,QAElB,MAAM,gBAAgB,UAAU,QAAQ,UAAU,OAAO;EAE3D,OAAO;GACL,SAAS,UAAU;GACnB,UAAU,UAAU;EACtB;CACF,UAAU;EACR,MAAM,QAAQ,MAAM;CACtB;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stillwind/analysis",
3
- "version": "0.12.0",
3
+ "version": "0.14.0",
4
4
  "description": "Analysis services for the Stillwind CLI, language server, and editors",
5
5
  "keywords": [
6
6
  "stillwind"
@@ -45,16 +45,16 @@
45
45
  "access": "public"
46
46
  },
47
47
  "dependencies": {
48
- "@stillwind/config": "0.12.0",
49
- "@stillwind/host": "0.12.0",
50
- "@stillwind/native": "0.12.0",
51
- "minimatch": "^11.0.5",
48
+ "@stillwind/config": "0.14.0",
49
+ "@stillwind/host": "0.14.0",
50
+ "@stillwind/native": "0.14.0",
51
+ "minimatch": "^11.0.9",
52
52
  "pathe": "^2.0.3"
53
53
  },
54
54
  "devDependencies": {
55
55
  "@stillwind-internal/tools-workspace": "0.0.0",
56
- "@types/node": "^26.6.6",
56
+ "@types/node": "^26.6.11",
57
57
  "typescript": "^6.0.3",
58
- "vite-plus": "1.6.0"
58
+ "vite-plus": "1.8.0"
59
59
  }
60
60
  }