@stillwind/analysis 0.8.0 → 0.10.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 +102 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/memory.js +4 -0
- package/dist/memory.js.map +1 -1
- package/dist/node.d.ts +12 -3
- package/dist/node.js +12 -2
- package/dist/node.js.map +1 -1
- package/dist/{reports-DN38lybK.js → reports-DvHppcFa.js} +4 -1
- package/dist/reports-DvHppcFa.js.map +1 -0
- package/dist/{reports-BmpsYdDN.d.ts → reports-Dy2Qrbj_.d.ts} +4 -1
- package/package.json +9 -7
- package/dist/reports-DN38lybK.js.map +0 -1
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
# @stillwind/analysis
|
|
2
|
+
|
|
3
|
+
## 0.10.0
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Updated dependencies:
|
|
8
|
+
- @stillwind/config@0.10.0
|
|
9
|
+
- @stillwind/host@0.10.0
|
|
10
|
+
- @stillwind/native@0.10.0
|
|
11
|
+
|
|
12
|
+
## 0.9.0
|
|
13
|
+
|
|
14
|
+
### Patch Changes
|
|
15
|
+
|
|
16
|
+
- Updated dependencies:
|
|
17
|
+
- @stillwind/config@0.9.0
|
|
18
|
+
- @stillwind/host@0.9.0
|
|
19
|
+
- @stillwind/native@0.9.0
|
|
20
|
+
|
|
21
|
+
## 0.8.0
|
|
22
|
+
|
|
23
|
+
### Patch Changes
|
|
24
|
+
|
|
25
|
+
- Updated dependencies:
|
|
26
|
+
- @stillwind/config@0.8.0
|
|
27
|
+
- @stillwind/host@0.8.0
|
|
28
|
+
- @stillwind/native@0.8.0
|
|
29
|
+
|
|
30
|
+
## 0.7.0
|
|
31
|
+
|
|
32
|
+
### Patch Changes
|
|
33
|
+
|
|
34
|
+
- The npm package page now shows that each package includes TypeScript declarations. Packages without a root JavaScript entry declare an empty root module, so TypeScript setups that ignore `exports` report a missing export instead of resolving unrelated types.
|
|
35
|
+
|
|
36
|
+
- Updated dependencies:
|
|
37
|
+
- @stillwind/config@0.7.0
|
|
38
|
+
- @stillwind/host@0.7.0
|
|
39
|
+
- @stillwind/native@0.7.0
|
|
40
|
+
|
|
41
|
+
## 0.6.0
|
|
42
|
+
|
|
43
|
+
### Patch Changes
|
|
44
|
+
|
|
45
|
+
- Updated dependencies:
|
|
46
|
+
- @stillwind/config@0.6.0
|
|
47
|
+
- @stillwind/host@0.6.0
|
|
48
|
+
- @stillwind/native@0.6.0
|
|
49
|
+
|
|
50
|
+
## 0.5.0
|
|
51
|
+
|
|
52
|
+
### Patch Changes
|
|
53
|
+
|
|
54
|
+
- Updated dependencies:
|
|
55
|
+
- @stillwind/config@0.5.0
|
|
56
|
+
- @stillwind/host@0.5.0
|
|
57
|
+
- @stillwind/native@0.5.0
|
|
58
|
+
|
|
59
|
+
## 0.4.1
|
|
60
|
+
|
|
61
|
+
### Patch Changes
|
|
62
|
+
|
|
63
|
+
- Updated dependencies:
|
|
64
|
+
- @stillwind/config@0.4.1
|
|
65
|
+
- @stillwind/host@0.4.1
|
|
66
|
+
- @stillwind/native@0.4.1
|
|
67
|
+
|
|
68
|
+
## 0.4.0
|
|
69
|
+
|
|
70
|
+
### Patch Changes
|
|
71
|
+
|
|
72
|
+
- Updated dependencies:
|
|
73
|
+
- @stillwind/config@0.4.0
|
|
74
|
+
- @stillwind/host@0.4.0
|
|
75
|
+
- @stillwind/native@0.4.0
|
|
76
|
+
|
|
77
|
+
## 0.3.0
|
|
78
|
+
|
|
79
|
+
### Patch Changes
|
|
80
|
+
|
|
81
|
+
- Updated dependencies:
|
|
82
|
+
- @stillwind/config@0.3.0
|
|
83
|
+
- @stillwind/host@0.3.0
|
|
84
|
+
- @stillwind/native@0.3.0
|
|
85
|
+
|
|
86
|
+
## 0.2.0
|
|
87
|
+
|
|
88
|
+
### Patch Changes
|
|
89
|
+
|
|
90
|
+
- Updated dependencies:
|
|
91
|
+
- @stillwind/config@0.2.0
|
|
92
|
+
- @stillwind/host@0.2.0
|
|
93
|
+
- @stillwind/native@0.2.0
|
|
94
|
+
|
|
95
|
+
## 0.1.0
|
|
96
|
+
|
|
97
|
+
### Patch Changes
|
|
98
|
+
|
|
99
|
+
- Updated dependencies:
|
|
100
|
+
- @stillwind/config@0.1.0
|
|
101
|
+
- @stillwind/host@0.1.0
|
|
102
|
+
- @stillwind/native@0.1.0
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
+
import { n as documentationUrl, r as lintReports, t as documentationSection } from "./reports-Dy2Qrbj_.js";
|
|
1
2
|
import { a as DiscoverWorkspace, c as WorkspaceEditorResult, i as AnalysisWorkspaceService, l as WorkspaceResult, n as AnalysisResult, o as OpenAnalysisWorkspaces, r as AnalysisWorkspaceContext, s as OpenWorkspaces, t as AnalysisDependency } from "./workspace-DIADkpZF.js";
|
|
2
|
-
import { n as documentationUrl, r as lintReports, t as documentationSection } from "./reports-BmpsYdDN.js";
|
|
3
3
|
import { DesignCandidate, DesignSystemRequest, DesignToken, DesignTokenSource, EditorRequest, EditorResult } from "@stillwind/host";
|
|
4
4
|
export { type AnalysisDependency, type AnalysisResult, type AnalysisWorkspaceContext, type AnalysisWorkspaceService, type DesignCandidate, type DesignSystemRequest, type DesignToken, type DesignTokenSource, type DiscoverWorkspace, type EditorRequest, type EditorResult, type OpenAnalysisWorkspaces, type OpenWorkspaces, type WorkspaceEditorResult, type WorkspaceResult, documentationSection, documentationUrl, lintReports };
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { t as documentationSection, n as documentationUrl, r as lintReports } from "./reports-
|
|
1
|
+
export { t as documentationSection, n as documentationUrl, r as lintReports } from "./reports-DvHppcFa.js";
|
package/dist/memory.js
CHANGED
|
@@ -15,6 +15,7 @@ function createMemoryAnalysisWorkspace(options) {
|
|
|
15
15
|
return {
|
|
16
16
|
/**
|
|
17
17
|
* Replaces an open buffer and advances the workspace revision when its state changes.
|
|
18
|
+
*
|
|
18
19
|
* @param uri - Original document URI, including dependencies outside the target scope.
|
|
19
20
|
* @param source - Complete unsaved text.
|
|
20
21
|
* @param version - Increasing safe integer. An identical update at the same version is accepted.
|
|
@@ -33,6 +34,7 @@ function createMemoryAnalysisWorkspace(options) {
|
|
|
33
34
|
},
|
|
34
35
|
/**
|
|
35
36
|
* Removes a buffer and advances the revision if it existed.
|
|
37
|
+
*
|
|
36
38
|
* @param uri - Original document URI. Unknown URIs have no effect.
|
|
37
39
|
*/
|
|
38
40
|
closeDocument(uri) {
|
|
@@ -40,6 +42,7 @@ function createMemoryAnalysisWorkspace(options) {
|
|
|
40
42
|
},
|
|
41
43
|
/**
|
|
42
44
|
* Captures open buffers and queues compilation for an included target.
|
|
45
|
+
*
|
|
43
46
|
* @param uri - Target URI tested by the embedding's includes callback.
|
|
44
47
|
* @param signal - Optional cancellation checked before and after compilation.
|
|
45
48
|
* @returns One project result, or no result for an excluded target. Compiler failures become
|
|
@@ -94,6 +97,7 @@ function createMemoryAnalysisWorkspace(options) {
|
|
|
94
97
|
},
|
|
95
98
|
/**
|
|
96
99
|
* Invalidates queued snapshots and invokes the embedding's cleanup after queued work.
|
|
100
|
+
*
|
|
97
101
|
* @returns The same cleanup promise on repeated calls.
|
|
98
102
|
* @throws If the embedding's cleanup fails.
|
|
99
103
|
*/
|
package/dist/memory.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"memory.js","names":[],"sources":["../src/memory.ts"],"sourcesContent":["import type { AnalysisResult, AnalysisWorkspaceService, WorkspaceResult } from \"./workspace.ts\";\n\n/** Compiler input captured from URI documents before asynchronous compilation starts. */\nexport interface MemoryAnalysisInput {\n /** Requested target URI accepted by the embedding's includes callback. */\n uri: string;\n /** Workspace change counter captured when the request was queued. */\n revision: number;\n /** Original text of all open documents, keyed by URI. The snapshot is independent of later updates. */\n documents: ReadonlyMap<string, string>;\n /** Optional cancellation signal. The workspace also checks it before and after calling compile. */\n signal?: AbortSignal;\n}\n\n/** Supplies the browser's WASM compiler, module loader, and type-facts service. */\nexport interface MemoryAnalysisOptions {\n /** Identifies the project in diagnostics. It need not be a filesystem path. */\n config: string;\n /**\n * Tests whether this workspace owns a target. Dependency buffers can be outside this scope.\n *\n * @param uri - Requested target URI.\n * @returns Whether compile should run for this target.\n */\n includes(uri: string): boolean;\n /**\n * Runs the embedding's compiler against one captured snapshot.\n *\n * @param input - Target, revision, open buffers, and optional cancellation signal.\n * @returns Reports and coverage information for the captured revision. Complete describes analysis\n * coverage. It does not imply that every report is successful.\n * @throws If compiler or module services fail. The workspace returns the error as an incomplete result.\n */\n compile(input: MemoryAnalysisInput): Promise<\n Pick<AnalysisResult, \"reports\" | \"dependencies\" | \"unverified\" | \"generation\" | \"error\"> & {\n /** Coverage of the captured snapshot. Compiler error reports can still have complete coverage. */\n status: \"complete\" | \"incomplete\";\n }\n >;\n /**\n * Releases resources after queued compilations finish. Called once during workspace closure.\n *\n * @returns Nothing, or a promise for asynchronous cleanup.\n * @throws If resource cleanup fails. The workspace's close promise rejects.\n */\n close?(): void | Promise<void>;\n}\n\n/**\n * Serializes in-memory analyses and discards reports from obsolete document revisions.\n *\n * @param options - Project membership, compiler operation, and optional resource cleanup.\n * @returns A URI-based service. It supplies snapshots to compile but performs no module resolution\n * itself. Closing waits for queued work and calls the cleanup operation once.\n */\nexport function createMemoryAnalysisWorkspace(\n options: MemoryAnalysisOptions,\n): AnalysisWorkspaceService {\n const documents = new Map<\n string,\n {\n /** Complete unsaved original document text. */\n source: string;\n /** Last accepted safe integer version while this URI is open. */\n version: number;\n }\n >();\n\n let revision = 0;\n let queue: Promise<unknown> = Promise.resolve();\n let closed = false;\n let closing: Promise<void> | undefined;\n\n return {\n /**\n * Replaces an open buffer and advances the workspace revision when its state changes.\n * @param uri - Original document URI, including dependencies outside the target scope.\n * @param source - Complete unsaved text.\n * @param version - Increasing safe integer. An identical update at the same version is accepted.\n * @throws If the service is closed or the version is invalid or does not increase.\n */\n update(uri, source, version) {\n if (closed) {\n throw new Error(\"Analysis workspace is closed\");\n }\n const previous = documents.get(uri);\n if (previous?.version === version && previous.source === source) {\n return;\n }\n if (!Number.isSafeInteger(version) || (previous && previous.version >= version)) {\n throw new Error(\"Analysis document versions must increase\");\n }\n documents.set(uri, { source, version });\n revision++;\n },\n /**\n * Removes a buffer and advances the revision if it existed.\n * @param uri - Original document URI. Unknown URIs have no effect.\n */\n closeDocument(uri) {\n if (documents.delete(uri)) {\n revision++;\n }\n },\n /**\n * Captures open buffers and queues compilation for an included target.\n * @param uri - Target URI tested by the embedding's includes callback.\n * @param signal - Optional cancellation checked before and after compilation.\n * @returns One project result, or no result for an excluded target. Compiler failures become\n * incomplete results, and stale or cancelled results omit reports.\n * @throws If the service is closed or the membership callback fails.\n */\n analyze(uri, signal): Promise<WorkspaceResult[]> {\n if (closed) {\n return Promise.reject(new Error(\"Analysis workspace is closed\"));\n }\n if (!options.includes(uri)) {\n return Promise.resolve([]);\n }\n const captured = revision;\n const snapshot = new Map([...documents].map(([uri, doc]) => [uri, doc.source]));\n const task = queue.then(async () => {\n /**\n * Classifies work that can no longer publish results from the captured revision.\n * @returns `cancelled` for an aborted signal, `stale` for a newer revision, or undefined.\n */\n const obsolete = () =>\n signal?.aborted\n ? (\"cancelled\" as const)\n : captured !== revision\n ? (\"stale\" as const)\n : undefined;\n let result: AnalysisResult = {\n entry: uri,\n revision: captured,\n status: \"incomplete\",\n reports: [],\n };\n if (!obsolete()) {\n try {\n result = {\n ...result,\n ...(await options.compile({\n uri,\n revision: captured,\n documents: snapshot,\n signal,\n })),\n };\n } catch (error) {\n result.error = String(error);\n }\n }\n const status = obsolete();\n if (status) {\n result = {\n entry: uri,\n revision: captured,\n status,\n reports: [],\n };\n }\n return [\n {\n project: 0,\n config: options.config,\n result,\n },\n ];\n });\n queue = task.catch(() => {});\n return task;\n },\n /**\n * Invalidates queued snapshots and invokes the embedding's cleanup after queued work.\n * @returns The same cleanup promise on repeated calls.\n * @throws If the embedding's cleanup fails.\n */\n close() {\n closing ??= (async () => {\n closed = true;\n revision++;\n await queue;\n await options.close?.();\n })();\n return closing;\n },\n };\n}\n"],"mappings":";;;;;;;;AAuDA,SAAgB,8BACd,SAC0B;CAC1B,MAAM,4BAAY,IAAI,IAQpB;CAEF,IAAI,WAAW;CACf,IAAI,QAA0B,QAAQ,QAAQ;CAC9C,IAAI,SAAS;CACb,IAAI;CAEJ,OAAO
|
|
1
|
+
{"version":3,"file":"memory.js","names":[],"sources":["../src/memory.ts"],"sourcesContent":["import type { AnalysisResult, AnalysisWorkspaceService, WorkspaceResult } from \"./workspace.ts\";\n\n/** Compiler input captured from URI documents before asynchronous compilation starts. */\nexport interface MemoryAnalysisInput {\n /** Requested target URI accepted by the embedding's includes callback. */\n uri: string;\n /** Workspace change counter captured when the request was queued. */\n revision: number;\n /** Original text of all open documents, keyed by URI. The snapshot is independent of later updates. */\n documents: ReadonlyMap<string, string>;\n /** Optional cancellation signal. The workspace also checks it before and after calling compile. */\n signal?: AbortSignal;\n}\n\n/** Supplies the browser's WASM compiler, module loader, and type-facts service. */\nexport interface MemoryAnalysisOptions {\n /** Identifies the project in diagnostics. It need not be a filesystem path. */\n config: string;\n /**\n * Tests whether this workspace owns a target. Dependency buffers can be outside this scope.\n *\n * @param uri - Requested target URI.\n * @returns Whether compile should run for this target.\n */\n includes(uri: string): boolean;\n /**\n * Runs the embedding's compiler against one captured snapshot.\n *\n * @param input - Target, revision, open buffers, and optional cancellation signal.\n * @returns Reports and coverage information for the captured revision. Complete describes analysis\n * coverage. It does not imply that every report is successful.\n * @throws If compiler or module services fail. The workspace returns the error as an incomplete result.\n */\n compile(input: MemoryAnalysisInput): Promise<\n Pick<AnalysisResult, \"reports\" | \"dependencies\" | \"unverified\" | \"generation\" | \"error\"> & {\n /** Coverage of the captured snapshot. Compiler error reports can still have complete coverage. */\n status: \"complete\" | \"incomplete\";\n }\n >;\n /**\n * Releases resources after queued compilations finish. Called once during workspace closure.\n *\n * @returns Nothing, or a promise for asynchronous cleanup.\n * @throws If resource cleanup fails. The workspace's close promise rejects.\n */\n close?(): void | Promise<void>;\n}\n\n/**\n * Serializes in-memory analyses and discards reports from obsolete document revisions.\n *\n * @param options - Project membership, compiler operation, and optional resource cleanup.\n * @returns A URI-based service. It supplies snapshots to compile but performs no module resolution\n * itself. Closing waits for queued work and calls the cleanup operation once.\n */\nexport function createMemoryAnalysisWorkspace(\n options: MemoryAnalysisOptions,\n): AnalysisWorkspaceService {\n const documents = new Map<\n string,\n {\n /** Complete unsaved original document text. */\n source: string;\n /** Last accepted safe integer version while this URI is open. */\n version: number;\n }\n >();\n\n let revision = 0;\n let queue: Promise<unknown> = Promise.resolve();\n let closed = false;\n let closing: Promise<void> | undefined;\n\n return {\n /**\n * Replaces an open buffer and advances the workspace revision when its state changes.\n *\n * @param uri - Original document URI, including dependencies outside the target scope.\n * @param source - Complete unsaved text.\n * @param version - Increasing safe integer. An identical update at the same version is accepted.\n * @throws If the service is closed or the version is invalid or does not increase.\n */\n update(uri, source, version) {\n if (closed) {\n throw new Error(\"Analysis workspace is closed\");\n }\n const previous = documents.get(uri);\n if (previous?.version === version && previous.source === source) {\n return;\n }\n if (!Number.isSafeInteger(version) || (previous && previous.version >= version)) {\n throw new Error(\"Analysis document versions must increase\");\n }\n documents.set(uri, { source, version });\n revision++;\n },\n /**\n * Removes a buffer and advances the revision if it existed.\n *\n * @param uri - Original document URI. Unknown URIs have no effect.\n */\n closeDocument(uri) {\n if (documents.delete(uri)) {\n revision++;\n }\n },\n /**\n * Captures open buffers and queues compilation for an included target.\n *\n * @param uri - Target URI tested by the embedding's includes callback.\n * @param signal - Optional cancellation checked before and after compilation.\n * @returns One project result, or no result for an excluded target. Compiler failures become\n * incomplete results, and stale or cancelled results omit reports.\n * @throws If the service is closed or the membership callback fails.\n */\n analyze(uri, signal): Promise<WorkspaceResult[]> {\n if (closed) {\n return Promise.reject(new Error(\"Analysis workspace is closed\"));\n }\n if (!options.includes(uri)) {\n return Promise.resolve([]);\n }\n const captured = revision;\n const snapshot = new Map([...documents].map(([uri, doc]) => [uri, doc.source]));\n const task = queue.then(async () => {\n /**\n * Classifies work that can no longer publish results from the captured revision.\n * @returns `cancelled` for an aborted signal, `stale` for a newer revision, or undefined.\n */\n const obsolete = () =>\n signal?.aborted\n ? (\"cancelled\" as const)\n : captured !== revision\n ? (\"stale\" as const)\n : undefined;\n let result: AnalysisResult = {\n entry: uri,\n revision: captured,\n status: \"incomplete\",\n reports: [],\n };\n if (!obsolete()) {\n try {\n result = {\n ...result,\n ...(await options.compile({\n uri,\n revision: captured,\n documents: snapshot,\n signal,\n })),\n };\n } catch (error) {\n result.error = String(error);\n }\n }\n const status = obsolete();\n if (status) {\n result = {\n entry: uri,\n revision: captured,\n status,\n reports: [],\n };\n }\n return [\n {\n project: 0,\n config: options.config,\n result,\n },\n ];\n });\n queue = task.catch(() => {});\n return task;\n },\n /**\n * Invalidates queued snapshots and invokes the embedding's cleanup after queued work.\n *\n * @returns The same cleanup promise on repeated calls.\n * @throws If the embedding's cleanup fails.\n */\n close() {\n closing ??= (async () => {\n closed = true;\n revision++;\n await queue;\n await options.close?.();\n })();\n return closing;\n },\n };\n}\n"],"mappings":";;;;;;;;AAuDA,SAAgB,8BACd,SAC0B;CAC1B,MAAM,4BAAY,IAAI,IAQpB;CAEF,IAAI,WAAW;CACf,IAAI,QAA0B,QAAQ,QAAQ;CAC9C,IAAI,SAAS;CACb,IAAI;CAEJ,OAAO;;;;;;;;;EASL,OAAO,KAAK,QAAQ,SAAS;GAC3B,IAAI,QACF,MAAM,IAAI,MAAM,8BAA8B;GAEhD,MAAM,WAAW,UAAU,IAAI,GAAG;GAClC,IAAI,UAAU,YAAY,WAAW,SAAS,WAAW,QACvD;GAEF,IAAI,CAAC,OAAO,cAAc,OAAO,KAAM,YAAY,SAAS,WAAW,SACrE,MAAM,IAAI,MAAM,0CAA0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1
1
|
import { o as OpenAnalysisWorkspaces, r as AnalysisWorkspaceContext } from "./workspace-DIADkpZF.js";
|
|
2
|
-
import { r as lintReports } from "./reports-
|
|
2
|
+
import { r as lintReports } from "./reports-Dy2Qrbj_.js";
|
|
3
3
|
import { AnalysisWorkspace, DesignCandidate, DesignSystemRequest, DesignToken, EditorEdit, WorkspaceResult } from "@stillwind/host";
|
|
4
4
|
/** Original buffer and ranges excluded by a formatter adapter. Paths are absolute. */
|
|
5
5
|
interface RewriteInput {
|
|
@@ -35,7 +35,9 @@ interface RewriteFileFailure {
|
|
|
35
35
|
/** Analysis findings captured before planning failed, when available. */
|
|
36
36
|
results: WorkspaceResult[];
|
|
37
37
|
}
|
|
38
|
-
/**
|
|
38
|
+
/**
|
|
39
|
+
* Selects configured source files for CLI analysis and rewriting.
|
|
40
|
+
*/
|
|
39
41
|
interface RewriteOptions {
|
|
40
42
|
/** Explicit configuration path, absolute or relative to cwd. Omission searches upward from cwd. */
|
|
41
43
|
config?: string;
|
|
@@ -59,6 +61,7 @@ interface FormatResult {
|
|
|
59
61
|
}
|
|
60
62
|
/**
|
|
61
63
|
* Sorts configured targets and saves changed files unless check is true.
|
|
64
|
+
*
|
|
62
65
|
* @param options - Configuration discovery, target filters, and optional check mode.
|
|
63
66
|
* @returns Changed paths, original findings, and failures. Healthy targets continue after a failure.
|
|
64
67
|
* @throws If selection, configuration, worker communication, or cleanup fails.
|
|
@@ -237,18 +240,22 @@ export declare function openNodeWorkspaces(context: AnalysisWorkspaceContext, co
|
|
|
237
240
|
* @throws If converting a malformed file URI or closing a failed worker throws.
|
|
238
241
|
*/
|
|
239
242
|
export declare function discoverNodeWorkspace(uri: string, context: AnalysisWorkspaceContext, known: ReadonlySet<string>): Promise<OpenAnalysisWorkspaces | undefined>;
|
|
240
|
-
/**
|
|
243
|
+
/**
|
|
244
|
+
* Reuses an isolated process while refreshing trusted configuration for each formatting request.
|
|
245
|
+
*/
|
|
241
246
|
export declare class SourceFormatter {
|
|
242
247
|
#private;
|
|
243
248
|
private readonly config;
|
|
244
249
|
/**
|
|
245
250
|
* Starts the isolated worker that evaluates configuration on each formatting request.
|
|
251
|
+
*
|
|
246
252
|
* @param config - Configuration path resolved in the worker's inherited working directory.
|
|
247
253
|
*/
|
|
248
254
|
constructor(config: string);
|
|
249
255
|
/**
|
|
250
256
|
* Sorts the supplied buffer with current project settings.
|
|
251
257
|
* Files outside all configured scopes return unchanged text. Requests are serialized and never write files.
|
|
258
|
+
*
|
|
252
259
|
* @param input - Original buffer and optional protected ranges. Relative paths are resolved from cwd.
|
|
253
260
|
* @returns The sorted buffer and original findings after configuration is reopened.
|
|
254
261
|
* @throws If configuration loading, parsing, analysis, project agreement, rewriting, or worker communication fails.
|
|
@@ -256,6 +263,7 @@ export declare class SourceFormatter {
|
|
|
256
263
|
format(input: RewriteInput): Promise<RewriteResult>;
|
|
257
264
|
/**
|
|
258
265
|
* Waits for queued formatting and releases the child process. Stop submitting requests before closure.
|
|
266
|
+
*
|
|
259
267
|
* @returns Completion of worker cleanup.
|
|
260
268
|
* @throws If the worker's cleanup request fails.
|
|
261
269
|
*/
|
|
@@ -263,6 +271,7 @@ export declare class SourceFormatter {
|
|
|
263
271
|
}
|
|
264
272
|
/**
|
|
265
273
|
* Finds a configuration above a source file or resolves an explicit path from cwd.
|
|
274
|
+
*
|
|
266
275
|
* @param file - Source path whose parent starts upward discovery. Relative paths use cwd.
|
|
267
276
|
* @param config - Optional explicit configuration path, returned without an existence check.
|
|
268
277
|
* @returns The absolute configuration path, or undefined when discovery finds none.
|
package/dist/node.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { r as lintReports } from "./reports-DN38lybK.js";
|
|
2
1
|
import { t as RewriteFailure } from "./rewrite-Bdo2ssmD.js";
|
|
2
|
+
import { r as lintReports } from "./reports-DvHppcFa.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";
|
|
@@ -186,6 +186,7 @@ var AnalysisWorker = class {
|
|
|
186
186
|
/**
|
|
187
187
|
* Saves changed bytes once per file. Identical buffers perform no filesystem operations.
|
|
188
188
|
* Checks each original immediately before saving and continues after a target fails.
|
|
189
|
+
*
|
|
189
190
|
* @param changes - Distinct target paths and original/replacement bytes. Buffers remain unchanged.
|
|
190
191
|
* @returns Saved paths and failures. A stale file is left unchanged.
|
|
191
192
|
*/
|
|
@@ -212,6 +213,7 @@ async function writeChangedFiles(changes) {
|
|
|
212
213
|
// src/rewrite-files.ts
|
|
213
214
|
/**
|
|
214
215
|
* Computes all replacements before optionally saving changed files. Fixes return final findings.
|
|
216
|
+
*
|
|
215
217
|
* @param options - Configuration discovery and optional filters within configured target scopes.
|
|
216
218
|
* @param operation - Utility sorting or converged lint fixes.
|
|
217
219
|
* @param write - Whether to verify and save changed bytes after every replacement is planned.
|
|
@@ -277,6 +279,7 @@ async function rewriteFiles(options, operation, write) {
|
|
|
277
279
|
}
|
|
278
280
|
/**
|
|
279
281
|
* Resolves an explicit configuration path or searches above the chosen working directory.
|
|
282
|
+
*
|
|
280
283
|
* @param options - Optional config path and cwd, defaulting to process.cwd().
|
|
281
284
|
* @returns An absolute path. Explicit paths are resolved without evaluating the configuration.
|
|
282
285
|
* @throws If discovery finds no configuration.
|
|
@@ -290,6 +293,7 @@ function resolveRewriteConfig(options) {
|
|
|
290
293
|
// src/format.ts
|
|
291
294
|
/**
|
|
292
295
|
* Sorts configured targets and saves changed files unless check is true.
|
|
296
|
+
*
|
|
293
297
|
* @param options - Configuration discovery, target filters, and optional check mode.
|
|
294
298
|
* @returns Changed paths, original findings, and failures. Healthy targets continue after a failure.
|
|
295
299
|
* @throws If selection, configuration, worker communication, or cleanup fails.
|
|
@@ -732,7 +736,9 @@ async function openConfiguration(file, workspaces, errors) {
|
|
|
732
736
|
}
|
|
733
737
|
}
|
|
734
738
|
// src/source-formatter.ts
|
|
735
|
-
/**
|
|
739
|
+
/**
|
|
740
|
+
* Reuses an isolated process while refreshing trusted configuration for each formatting request.
|
|
741
|
+
*/
|
|
736
742
|
var SourceFormatter = class {
|
|
737
743
|
config;
|
|
738
744
|
/** Child process reused across formatting requests and owned until close completes. */
|
|
@@ -741,6 +747,7 @@ var SourceFormatter = class {
|
|
|
741
747
|
#queue = Promise.resolve();
|
|
742
748
|
/**
|
|
743
749
|
* Starts the isolated worker that evaluates configuration on each formatting request.
|
|
750
|
+
*
|
|
744
751
|
* @param config - Configuration path resolved in the worker's inherited working directory.
|
|
745
752
|
*/
|
|
746
753
|
constructor(config) {
|
|
@@ -749,6 +756,7 @@ var SourceFormatter = class {
|
|
|
749
756
|
/**
|
|
750
757
|
* Sorts the supplied buffer with current project settings.
|
|
751
758
|
* Files outside all configured scopes return unchanged text. Requests are serialized and never write files.
|
|
759
|
+
*
|
|
752
760
|
* @param input - Original buffer and optional protected ranges. Relative paths are resolved from cwd.
|
|
753
761
|
* @returns The sorted buffer and original findings after configuration is reopened.
|
|
754
762
|
* @throws If configuration loading, parsing, analysis, project agreement, rewriting, or worker communication fails.
|
|
@@ -768,6 +776,7 @@ var SourceFormatter = class {
|
|
|
768
776
|
}
|
|
769
777
|
/**
|
|
770
778
|
* Waits for queued formatting and releases the child process. Stop submitting requests before closure.
|
|
779
|
+
*
|
|
771
780
|
* @returns Completion of worker cleanup.
|
|
772
781
|
* @throws If the worker's cleanup request fails.
|
|
773
782
|
*/
|
|
@@ -778,6 +787,7 @@ var SourceFormatter = class {
|
|
|
778
787
|
};
|
|
779
788
|
/**
|
|
780
789
|
* Finds a configuration above a source file or resolves an explicit path from cwd.
|
|
790
|
+
*
|
|
781
791
|
* @param file - Source path whose parent starts upward discovery. Relative paths use cwd.
|
|
782
792
|
* @param config - Optional explicit configuration path, returned without an existence check.
|
|
783
793
|
* @returns The absolute configuration path, or undefined when discovery finds none.
|
package/dist/node.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node.js","names":["process"],"sources":["../src/worker-client.ts","../src/write.ts","../src/rewrite-files.ts","../src/format.ts","../src/design-system.ts","../src/inspect.ts","../src/lint.ts","../src/node-workspace.ts","../src/source-formatter.ts"],"sourcesContent":["import { fork, type ChildProcess } from \"node:child_process\";\nimport process from \"node:process\";\nimport { fileURLToPath } from \"node:url\";\n\nimport type { DesignSystemRequest, EditorRequest, WorkspaceResult } from \"@stillwind/host\";\n\nimport { RewriteFailure, type RewriteInput, type RewriteBatchResult } from \"./rewrite.ts\";\n\n/** Requests sent to the process that owns trusted config evaluation and plugin lifetimes. */\nexport type WorkerRequest =\n | {\n /** Serialized discriminator for replacing the child workspace. */\n method: \"open\";\n /** Configuration path evaluated in the child process, replacing any previously opened workspace. */\n config: string;\n }\n | {\n /** Serialized discriminator for analyzing configured targets. */\n method: \"lint\";\n /** Additional target globs relative to each project root. Omission checks all configured targets. */\n patterns?: readonly string[];\n }\n | {\n /** Serialized discriminator for enumerating distinct targets. */\n method: \"targets\";\n /** Additional project-relative globs. An empty or omitted list keeps every configured target. */\n patterns?: readonly string[];\n /** Adds the stylesheets that each project lints. */\n stylesheets?: boolean;\n }\n | {\n /** Serialized discriminator for computing source replacements. */\n method: \"rewrite\";\n /** Distinct absolute target paths and captured text, retained in result order. */\n inputs: readonly RewriteInput[];\n /** Selects one sort pass or lint fixes that must converge. */\n operation: \"sort\" | \"fixes\";\n }\n | {\n /** Serialized discriminator for preparing a batch of targets. */\n method: \"prepare\";\n /** Absolute target paths. */\n files: readonly string[];\n }\n | {\n /** Serialized discriminator for analyzing one target in matching projects. */\n method: \"analyze\";\n /** Absolute target path. Each project whose scope contains the file returns a result. */\n file: string;\n }\n | {\n /** Serialized discriminator for an editor query against original text. */\n method: \"query\";\n /** Absolute target file path. */\n file: string;\n /** Editor operation in original UTF-16 coordinates. */\n request: EditorRequest;\n }\n | {\n /** Serialized discriminator for a question about each project's design system. */\n method: \"designSystem\";\n /** Theme, utility, or variant request. */\n request: DesignSystemRequest;\n }\n | {\n /** Serialized discriminator for replacing an unsaved buffer. */\n method: \"update\";\n /** Absolute source path, including dependencies outside target scopes. */\n file: string;\n /** Complete unsaved source text. */\n source: string;\n /** Safe integer that increases while this file is open. */\n version: number;\n }\n | {\n /** Serialized discriminator for removing an unsaved buffer. */\n method: \"closeDocument\";\n /** Absolute path of the buffer to remove. Unknown files have no effect. */\n file: string;\n }\n | {\n /** Serialized discriminator for checking whether the caller needs to reopen the workspace. */\n method: \"refresh\";\n /** Absolute file paths reported by save or watch notifications. */\n files: readonly string[];\n }\n | {\n /** Serialized discriminator for checking whether file changes can change results. */\n method: \"affects\";\n /** Absolute file paths reported by watch notifications. */\n files: readonly string[];\n }\n | {\n /** Serialized discriminator for refreshing disk and compiler caches. */\n method: \"invalidate\";\n }\n | {\n /** Serialized discriminator for closing hosts and disconnecting the child. */\n method: \"close\";\n };\n\n/** IPC response correlated with one request. Successful void operations can omit value. */\nexport interface WorkerReply {\n /** Request sequence number assigned by AnalysisWorker. */\n id: number;\n /** Serialized operation result when error is absent. */\n value?: unknown;\n /** Exception message and any analysis results that prevented a rewrite. */\n error?: {\n message: string;\n results?: WorkspaceResult[];\n };\n}\n\n/** Isolates configuration and plugin logs from CLI JSON and the LSP stdout transport. */\nexport class AnalysisWorker {\n /** Owned child with IPC enabled. Both output streams are forwarded to the parent's stderr. */\n readonly #child: ChildProcess;\n /** Unanswered requests keyed by monotonically assigned IPC sequence number. */\n readonly #pending = new Map<\n number,\n {\n /** Settles the request with the child's unvalidated reply value. */\n resolve: (value: unknown) => void;\n /** Rejects the request after delivery, child-operation, or process failure. */\n reject: (error: Error) => void;\n }\n >();\n /** Resolves on process closure after outstanding requests have been rejected. */\n readonly #closed: Promise<void>;\n\n /** Next IPC sequence number, independent of source document versions. */\n #nextId = 0;\n /** Whether process closure has been observed. */\n #exited = false;\n /** Prevents repeated close calls from sending another cleanup request. */\n #closing = false;\n\n /**\n * Starts the child process immediately. Call open before analysis and close when finished.\n */\n constructor() {\n this.#child = fork(fileURLToPath(new URL(\"./worker.js\", import.meta.url)), [], {\n stdio: [\"ignore\", \"pipe\", \"pipe\", \"ipc\"],\n execArgv: [],\n windowsHide: true,\n });\n this.#child.stdout!.on(\"data\", (data: Buffer) => {\n process.stderr.write(data);\n });\n this.#child.stderr!.on(\"data\", (data: Buffer) => {\n process.stderr.write(data);\n });\n this.#child.on(\"message\", (reply: WorkerReply) => {\n const request = this.#pending.get(reply.id);\n this.#pending.delete(reply.id);\n if (reply.error) {\n request?.reject(\n reply.error.results\n ? new RewriteFailure(reply.error.message, reply.error.results)\n : new Error(reply.error.message),\n );\n } else {\n request?.resolve(reply.value);\n }\n });\n this.#child.on(\"error\", (error) => {\n for (const request of this.#pending.values()) {\n request.reject(error);\n }\n this.#pending.clear();\n });\n this.#closed = new Promise((resolve) => {\n this.#child.on(\"close\", (code, signal) => {\n this.#exited = true;\n for (const request of this.#pending.values()) {\n request.reject(new Error(`Stillwind analysis worker closed (${code ?? signal})`));\n }\n this.#pending.clear();\n resolve();\n });\n });\n }\n\n /**\n * Sends an IPC operation and correlates its reply. Calls are not serialized here.\n *\n * @param request - Operation payload. Await open before using workspace operations, and avoid\n * overlapping replacement or closure with analysis requests.\n * @returns The reply value cast to T. The caller must choose T to match the operation's result.\n * @throws If the child is closed, IPC delivery fails, or the child operation reports an error.\n */\n async request<T = void>(request: WorkerRequest): Promise<T> {\n if (this.#exited) {\n throw new Error(\"Stillwind analysis worker is closed\");\n }\n const id = this.#nextId++;\n return (await new Promise<unknown>((resolve, reject) => {\n this.#pending.set(id, { resolve, reject });\n this.#child.send({ id, request }, (error) => {\n if (error) {\n this.#pending.delete(id);\n reject(error);\n }\n });\n })) as T;\n }\n\n /**\n * Replaces the child workspace, closing any previously opened hosts first.\n *\n * @param config - Configuration path. Relative paths use the child's inherited working directory.\n * @returns A promise that resolves after the configuration and project hosts have opened.\n * @throws If configuration evaluation, project initialization, or transport fails.\n */\n async open(config: string): Promise<void> {\n await this.request({\n method: \"open\",\n config,\n });\n }\n\n /**\n * Analyzes a target in each matching project of the opened workspace.\n *\n * @param file - Absolute target path. Unsaved buffers use preceding update requests.\n * @returns Scoped results in project order, or an empty list when no scope includes the target.\n * @throws If the workspace has not opened or transport fails.\n */\n analyze(file: string): Promise<WorkspaceResult[]> {\n return this.request({\n method: \"analyze\",\n file,\n });\n }\n\n /**\n * Enumerates and analyzes targets in the opened workspace.\n *\n * @param patterns - Additional globs relative to each project root. Empty or omitted filters\n * retain every configured target.\n * @returns Results in project order and sorted target order within each project.\n * @throws If the workspace has not opened, enumeration fails, or transport fails.\n */\n lint(patterns?: readonly string[]): Promise<WorkspaceResult[]> {\n return this.request({\n method: \"lint\",\n patterns,\n });\n }\n\n /**\n * Enumerates distinct targets in the opened workspace.\n *\n * @param patterns - Additional project-relative globs. Omission or an empty list retains all targets.\n * @param stylesheets - Adds the stylesheets that each project lints.\n * @returns Sorted absolute paths, deduplicated across projects.\n * @throws If the workspace has not opened, enumeration fails, or transport fails.\n */\n targets(patterns?: readonly string[], stylesheets?: boolean): Promise<string[]> {\n return this.request({\n method: \"targets\",\n patterns,\n stylesheets,\n });\n }\n\n /**\n * Computes replacements from captured buffers without writing files.\n *\n * @param inputs - Distinct absolute target paths and complete original text.\n * @param operation - Utility sorting or lint fixes, limited to ten changing passes per target.\n * @returns Successful replacements and target failures in input order. Captured buffers are removed after planning.\n * @throws If workspace setup, buffer installation, cleanup, or transport fails.\n */\n rewrite(\n inputs: readonly RewriteInput[],\n operation: \"sort\" | \"fixes\",\n ): Promise<RewriteBatchResult> {\n return this.request({\n method: \"rewrite\",\n inputs,\n operation,\n });\n }\n\n /**\n * Requests host cleanup and waits for the child process to close. After the cleanup request\n * settles, a child that remains alive for five seconds is terminated.\n *\n * @returns A promise that resolves after process closure. Repeated calls wait for that closure.\n * @throws If the initial cleanup request or its transport fails.\n */\n async close(): Promise<void> {\n if (this.#closing || this.#exited) {\n await this.#closed;\n return;\n }\n this.#closing = true;\n try {\n await this.request({\n method: \"close\",\n });\n } finally {\n const timer = setTimeout(() => {\n this.#child.kill();\n }, 5000);\n await this.#closed;\n clearTimeout(timer);\n }\n }\n}\n","import { readFile, writeFile } from \"node:fs/promises\";\n\nimport type { RewriteFileFailure } from \"./rewrite.ts\";\n\n/** A replacement with the original bytes retained for verification before saving. */\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 * @param changes - Distinct target paths and original/replacement bytes. Buffers remain unchanged.\n * @returns Saved paths and failures. A stale file is left unchanged.\n */\nexport async function writeChangedFiles(changes: readonly FileChange[]): Promise<{\n changed: string[];\n failures: RewriteFileFailure[];\n}> {\n const changed = changes.filter((change) => !change.before.equals(change.after));\n const saved: string[] = [];\n const failures: RewriteFileFailure[] = [];\n for (const change of changed) {\n try {\n if (!(await readFile(change.file)).equals(change.before)) {\n throw new Error(`Source changed before saving ${change.file}`);\n }\n await writeFile(change.file, change.after);\n saved.push(change.file);\n } catch (error) {\n failures.push({\n file: change.file,\n message: error instanceof Error ? error.message : String(error),\n results: [],\n });\n }\n }\n return {\n changed: saved,\n failures,\n };\n}\n","import { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { findConfiguration } from \"@stillwind/config/node\";\nimport type { WorkspaceResult } from \"@stillwind/host\";\n\nimport type { RewriteFileFailure, RewriteInput } from \"./rewrite.ts\";\nimport { AnalysisWorker } from \"./worker-client.ts\";\nimport { writeChangedFiles } from \"./write.ts\";\n\n/** Selects configured source files for CLI analysis and rewriting. */\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/** A completed rewrite batch with findings kept separately for each owning project. */\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 * @param options - Configuration discovery and optional filters within configured target scopes.\n * @param operation - Utility sorting or converged lint fixes.\n * @param write - Whether to verify and save changed bytes after every replacement is planned.\n * @returns Configuration, sorted changed paths, findings, and independent target failures.\n * Saving reports only paths whose writes succeeded. Check mode reports planned changes.\n * @throws If selection is empty, configuration, worker communication, or cleanup fails.\n */\nexport async function rewriteFiles(\n options: RewriteOptions,\n operation: \"sort\" | \"fixes\",\n write: boolean,\n): Promise<RewriteFilesResult> {\n const config = resolveRewriteConfig(options);\n const worker = new AnalysisWorker();\n try {\n await worker.open(config);\n const files = await worker.targets(options.patterns, true);\n if (!files.length) {\n throw new Error(\"No analysis targets matched the configured scopes\");\n }\n const failures: RewriteFileFailure[] = [];\n const originals = new Map<string, Buffer>();\n const inputs: RewriteInput[] = [];\n const reads = await Promise.allSettled(files.map((file) => readFile(file)));\n for (const [index, read] of reads.entries()) {\n const file = files[index];\n try {\n if (read.status === \"rejected\") {\n throw read.reason;\n }\n const source = read.value.toString(\"utf8\");\n if (!Buffer.from(source).equals(read.value)) {\n throw new Error(`Source is not valid UTF-8: ${file}`);\n }\n originals.set(file, read.value);\n inputs.push({\n file,\n source,\n });\n } catch (error) {\n failures.push({\n file,\n message: error instanceof Error ? error.message : String(error),\n results: [],\n });\n }\n }\n const batch = await worker.rewrite(inputs, operation);\n failures.push(...batch.failures);\n const changes = batch.outputs.map((output) => ({\n file: output.file,\n before: originals.get(output.file)!,\n after: Buffer.from(output.code),\n }));\n let changed = changes\n .filter((change) => !change.before.equals(change.after))\n .map((change) => change.file);\n if (write) {\n const saved = await writeChangedFiles(changes);\n changed = saved.changed;\n failures.push(...saved.failures);\n }\n changed.sort();\n failures.sort((a, b) => a.file.localeCompare(b.file));\n const results = [...batch.outputs, ...batch.failures]\n .flatMap((output) => output.results)\n .sort((a, b) => a.project - b.project || a.result.entry.localeCompare(b.result.entry));\n return {\n config,\n changed,\n results,\n failures,\n };\n } finally {\n await worker.close();\n }\n}\n\n/**\n * Resolves an explicit configuration path or searches above the chosen working directory.\n * @param options - Optional config path and cwd, defaulting to process.cwd().\n * @returns An absolute path. Explicit paths are resolved without evaluating the configuration.\n * @throws If discovery finds no configuration.\n */\nexport function resolveRewriteConfig(options: RewriteOptions): string {\n const cwd = options.cwd ?? process.cwd();\n const config = options.config ? path.resolve(cwd, options.config) : findConfiguration(cwd);\n if (!config) {\n throw new Error(`Cannot find Stillwind configuration above ${cwd}`);\n }\n return config;\n}\n","import type { WorkspaceResult } from \"@stillwind/host\";\n\nimport { rewriteFiles, type RewriteOptions } from \"./rewrite-files.ts\";\nimport type { RewriteFileFailure } from \"./rewrite.ts\";\n\n/** Sorting results whose changed paths compare original and final source bytes. */\nexport interface FormatResult {\n /** Absolute path of the evaluated configuration. */\n config: string;\n /** Absolute paths that changed or would change, in sorted order. */\n changed: string[];\n /** Findings from the original sources, in configured project and target order. */\n results: WorkspaceResult[];\n /** Targets that could not be read, rewritten, or saved. */\n failures: RewriteFileFailure[];\n /** Failures return 2. Check mode otherwise returns 1 when any file would change. */\n exitCode: 0 | 1 | 2;\n}\n\n/**\n * Sorts configured targets and saves changed files unless check is true.\n * @param options - Configuration discovery, target filters, and optional check mode.\n * @returns Changed paths, original findings, and failures. Healthy targets continue after a failure.\n * @throws If selection, configuration, worker communication, or cleanup fails.\n */\nexport async function format(\n options: RewriteOptions & {\n /** Whether to report changes without saving them. Defaults to false. */\n check?: boolean;\n } = {},\n): Promise<FormatResult> {\n const result = await rewriteFiles(options, \"sort\", !options.check);\n return {\n ...result,\n exitCode: result.failures.length ? 2 : options.check && result.changed.length ? 1 : 0,\n };\n}\n","import type { DesignCandidate, DesignSystemRequest, DesignToken } from \"@stillwind/host\";\n\nimport { resolveRewriteConfig, type RewriteOptions } from \"./rewrite-files.ts\";\nimport { AnalysisWorker } from \"./worker-client.ts\";\n\n/**\n * Design-system answers from every project of one configuration.\n */\nexport interface DesignSystemAnswer {\n /** Absolute path of the evaluated configuration. */\n config: string;\n /** Tokens in project and name order. */\n tokens: (DesignToken & {\n /** Zero-based project index in the evaluated configuration. */\n project: number;\n })[];\n /** Candidates in project order. */\n candidates: (DesignCandidate & {\n /** Zero-based project index in the evaluated configuration. */\n project: number;\n })[];\n /** Targets without a match in any project. */\n unmatched: string[];\n}\n\n/**\n * Answers a question about each project's design system in a child process.\n *\n * @param options - Configuration discovery. Target globs do not apply.\n * @param request - Theme, utility, or variant request.\n * @returns Answers from every project. Unknown names and unmatched targets are data.\n * @throws If configuration discovery, worker initialization, CSS loading, a plugin, or cleanup fails.\n */\nexport async function designSystem(\n options: Omit<RewriteOptions, \"patterns\">,\n request: DesignSystemRequest,\n): Promise<DesignSystemAnswer> {\n const config = resolveRewriteConfig(options);\n const worker = new AnalysisWorker();\n try {\n await worker.open(config);\n const answers = await worker.request<\n {\n project: number;\n result: {\n tokens: DesignToken[];\n candidates: DesignCandidate[];\n unmatched: string[];\n };\n }[]\n >({\n method: \"designSystem\",\n request,\n });\n return {\n config,\n tokens: answers.flatMap(({ project, result }) =>\n result.tokens.map((token) => ({\n ...token,\n project,\n })),\n ),\n candidates: answers.flatMap(({ project, result }) =>\n result.candidates.map((candidate) => ({\n ...candidate,\n project,\n })),\n ),\n unmatched: request.targets.filter((target) =>\n answers.every(({ result }) => result.unmatched.includes(target)),\n ),\n };\n } finally {\n await worker.close();\n }\n}\n","import { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\n\nimport {\n isStylesheet,\n type EditorRequest,\n type EditorResult,\n type WorkspaceResult,\n} from \"@stillwind/host\";\n\nimport { lintReports } from \"./reports.ts\";\nimport { resolveRewriteConfig, type RewriteOptions } from \"./rewrite-files.ts\";\nimport { AnalysisWorker } from \"./worker-client.ts\";\nimport type { WorkspaceEditorResult } from \"./workspace.ts\";\n\n/**\n * Selects generated CSS by file, line, or position.\n */\nexport interface InspectTarget {\n /** Path or glob accepted by target selection. */\n pattern: string;\n /** One-based line. Omission selects the whole file. */\n line?: number;\n /** One-based UTF-16 column. It requires line. */\n column?: number;\n}\n\n/**\n * Generated CSS for one source range in one project.\n */\nexport interface InspectPreview {\n /** Zero-based project index in the evaluated configuration. */\n project: number;\n /** Original document range with zero-based lines and UTF-16 columns, and an exclusive end. */\n location: {\n uri: string;\n startLine: number;\n startColumn: number;\n endLine: number;\n endColumn: number;\n };\n /** Original source text in the range. */\n source: string;\n /** Formatted CSS. It is empty for a failed occurrence or a marker class. */\n css: string;\n /** False when diagnostics contains an error, or when a required style failed. */\n valid: boolean;\n /** Reports whose primary range overlaps this range. CSS omits the utilities that they reject. */\n diagnostics: {\n /** Report severity, as in the reports of lint. */\n severity: string;\n /** Stable compiler code or lint rule. */\n code: string;\n /** Description of the finding. */\n message: string;\n }[];\n /** Markdown for a marker class. */\n documentation?: string;\n /** Authored runtime key expressions that the CSS depends on. */\n runtimeNames?: string[];\n}\n\n/**\n * An editor answer with a source range. Hovers omit valid because they describe generated CSS.\n */\ntype PreviewRange = NonNullable<EditorResult[\"hover\"]> & {\n valid?: boolean;\n};\n\n/**\n * A target that could not be read.\n */\nexport interface InspectFailure {\n /** Absolute path of the target. */\n file: string;\n /** Reason for the failure. */\n message: string;\n}\n\n/**\n * Inspection results with analysis outcomes retained for each project.\n */\nexport interface InspectResult {\n /** Absolute path of the evaluated configuration. */\n config: string;\n /** Analysis of each selected file, in file and project order. */\n results: WorkspaceResult[];\n /** Selected previews in file, project, and source order, without repeated ranges. */\n previews: InspectPreview[];\n /** Targets that could not be read. */\n failures: InspectFailure[];\n}\n\n/**\n * Parses a command-line target with an optional `:line` or `:line:column` suffix.\n *\n * @param target - Path or glob, including absolute Windows paths.\n * @returns The pattern and any one-based position.\n * @throws If the position is not positive or the target names a stylesheet.\n */\nexport function parseInspectTarget(target: string): InspectTarget {\n const [, pattern, line, column] = /^(.+?)(?::(\\d+)(?::(\\d+))?)?$/s.exec(target) ?? [];\n if (!pattern || /^0+$/.test(line ?? \"\") || /^0+$/.test(column ?? \"\")) {\n throw new Error(`Invalid inspect target: ${target}`);\n }\n if (isStylesheet(pattern)) {\n throw new Error(`inspect does not accept stylesheets: ${target}`);\n }\n return {\n pattern,\n ...(line ? { line: Number(line) } : {}),\n ...(column ? { column: Number(column) } : {}),\n };\n}\n\n/**\n * Finds the UTF-16 offset of the start of each line.\n *\n * @param source - Document text. Lines end at `\\n`, so `\\r\\n` remains one line break.\n * @returns Ascending offsets, beginning with zero.\n */\nfunction lineOffsets(source: string): number[] {\n const offsets = [0];\n for (let index = source.indexOf(\"\\n\"); index >= 0; index = source.indexOf(\"\\n\", index + 1)) {\n offsets.push(index + 1);\n }\n return offsets;\n}\n\n/**\n * Converts an offset to a position.\n *\n * @param lines - Result of {@link lineOffsets}.\n * @param offset - UTF-16 offset in the same document.\n * @returns The zero-based line and column.\n */\nfunction position(lines: readonly number[], offset: number) {\n let line = lines.length - 1;\n while (lines[line] > offset) {\n line--;\n }\n return {\n line,\n column: offset - lines[line],\n };\n}\n\n/**\n * Checks whether a report location belongs to a file.\n *\n * @param uri - File URI or path.\n * @param file - Absolute path.\n * @returns Whether both name the same path.\n */\nfunction isDocument(uri: string, file: string): boolean {\n return path.resolve(uri.startsWith(\"file:\") ? fileURLToPath(uri) : uri) === path.resolve(file);\n}\n\n/**\n * Answers one target for one file.\n *\n * @param worker - Opened worker that owns the file's analysis.\n * @param file - Absolute target path.\n * @param source - Text of the file.\n * @param target - Position to select. Positions outside the file select nothing.\n * @param reports - Reports with a range in this file, for each project.\n * @returns Previews with their project, in project and source order.\n * @throws If the editor query fails.\n */\nasync function selectPreviews(\n worker: AnalysisWorker,\n file: string,\n source: string,\n target: InspectTarget,\n reports: ReturnType<typeof lintReports>,\n): Promise<InspectPreview[]> {\n const lines = lineOffsets(source);\n const line = target.line === undefined ? undefined : target.line - 1;\n const lineStart = line === undefined ? undefined : lines[line];\n const lineEnd = line === undefined ? undefined : (lines[line + 1] ?? source.length + 1) - 1;\n if (line !== undefined && lineStart === undefined) {\n return [];\n }\n const offset = target.column === undefined ? undefined : lineStart! + target.column - 1;\n if (offset !== undefined && offset > lineEnd!) {\n return [];\n }\n const query = (request: EditorRequest) =>\n worker.request<WorkspaceEditorResult[]>({ method: \"query\", file, request });\n const uri = pathToFileURL(file).href;\n let selected: { project: number; range: PreviewRange }[];\n if (offset === undefined) {\n selected = (\n await query({\n kind: \"previews\",\n })\n ).flatMap(({ project, result }) =>\n (result.previews ?? [])\n .filter(({ start, end }) => line === undefined || (end > lineStart! && start <= lineEnd!))\n .map((range) => ({\n project,\n range,\n })),\n );\n } else {\n const hovers = await query({\n kind: \"hover\",\n offset,\n });\n selected = hovers.flatMap(({ project, result }) =>\n result.hover ? [{ project, range: result.hover }] : [],\n );\n if (selected.length < hovers.length) {\n // Failed occurrences and Vue template expressions have no hover, so the listing supplies them.\n const answered = new Set(selected.map(({ project }) => project));\n selected.push(\n ...(\n await query({\n kind: \"previews\",\n })\n ).flatMap(({ project, result }) =>\n answered.has(project)\n ? []\n : (result.previews ?? [])\n .filter(({ start, end }) => start <= offset && offset <= end)\n .map((range) => ({\n project,\n range,\n })),\n ),\n );\n }\n }\n return selected.flatMap(\n ({ project, range: { start, end, css, valid = true, documentation, runtimeNames } }) => {\n const diagnostics = reports\n .filter(\n ({ project: owner, report: { primary } }) =>\n owner === project &&\n primary.location.startUtf16 < end &&\n start < Math.max(primary.location.endUtf16, primary.location.startUtf16 + 1),\n )\n .map(({ report: { severity, code, message } }) => ({ severity, code, message }));\n if (!css && valid && !diagnostics.length && !documentation) {\n return [];\n }\n const first = position(lines, start);\n const last = position(lines, end);\n return [\n {\n project,\n location: {\n uri,\n startLine: first.line,\n startColumn: first.column,\n endLine: last.line,\n endColumn: last.column,\n },\n source: source.slice(start, end),\n css,\n valid: valid && !diagnostics.some(({ severity }) => severity === \"error\"),\n diagnostics,\n ...(documentation ? { documentation } : {}),\n ...(runtimeNames ? { runtimeNames } : {}),\n },\n ];\n },\n );\n}\n\n/**\n * Reports the generated CSS of configured source files in a child process.\n *\n * @param options - Configuration discovery and targets. Paths and globs follow the target rules\n * of lint. Stylesheets are not accepted, and an empty list selects every configured source file.\n * @returns Previews and analysis results. A file with incomplete analysis has no previews.\n * @throws If a target is invalid or matches no file, or if configuration discovery, worker\n * initialization, target enumeration, or cleanup fails.\n */\nexport async function inspect(\n options: Omit<RewriteOptions, \"patterns\"> & {\n /** Targets as written on the command line. */\n targets?: readonly string[];\n } = {},\n): Promise<InspectResult> {\n const targets = (options.targets ?? []).map(parseInspectTarget);\n const config = resolveRewriteConfig(options);\n const worker = new AnalysisWorker();\n try {\n await worker.open(config);\n const selections = new Map<string, InspectTarget[]>();\n for (const target of targets.length ? targets : [undefined]) {\n const files = (await worker.targets(target ? [target.pattern] : undefined)).filter(\n (file) => !isStylesheet(file),\n );\n if (!files.length) {\n throw new Error(\n target\n ? `No analysis targets matched ${target.pattern}`\n : \"No analysis targets matched the configured scopes\",\n );\n }\n for (const file of files) {\n selections.set(file, [\n ...(selections.get(file) ?? []),\n target ?? {\n pattern: file,\n },\n ]);\n }\n }\n const files = [...selections.keys()].sort();\n await worker.request({\n method: \"prepare\",\n files,\n });\n\n const result: InspectResult = {\n config,\n results: [],\n previews: [],\n failures: [],\n };\n for (const file of files) {\n const analyses = await worker.analyze(file);\n result.results.push(...analyses);\n const complete = new Set(\n analyses.filter(({ result }) => result.status === \"complete\").map(({ project }) => project),\n );\n let source: string;\n try {\n const bytes = await readFile(file);\n source = bytes.toString(\"utf8\");\n if (!Buffer.from(source).equals(bytes)) {\n throw new Error(`Source is not valid UTF-8: ${file}`);\n }\n } catch (error) {\n result.failures.push({\n file,\n message: error instanceof Error ? error.message : String(error),\n });\n continue;\n }\n const reports = lintReports(analyses).filter(\n ({ report }) =>\n report.primary.scope === \"range\" && isDocument(report.primary.location.uri, file),\n );\n const seen = new Set<string>();\n const previews: InspectPreview[] = [];\n for (const target of selections.get(file)!) {\n for (const preview of await selectPreviews(worker, file, source, target, reports)) {\n const { startLine, startColumn, endLine, endColumn } = preview.location;\n const key = [preview.project, startLine, startColumn, endLine, endColumn].join();\n if (complete.has(preview.project) && !seen.has(key)) {\n seen.add(key);\n previews.push(preview);\n }\n }\n }\n result.previews.push(\n ...previews.sort(\n (a, b) =>\n a.project - b.project ||\n a.location.startLine - b.location.startLine ||\n a.location.startColumn - b.location.startColumn,\n ),\n );\n }\n return result;\n } finally {\n await worker.close();\n }\n}\n","import type { WorkspaceResult } from \"@stillwind/host\";\n\nimport { lintReports } from \"./reports.ts\";\nimport { resolveRewriteConfig, rewriteFiles, type RewriteOptions } from \"./rewrite-files.ts\";\nimport type { RewriteFileFailure } from \"./rewrite.ts\";\nimport { AnalysisWorker } from \"./worker-client.ts\";\n\n/** Lint results preserve project membership and identify incomplete analysis. */\nexport interface LintResult {\n /** Absolute path of the evaluated configuration. */\n config: string;\n /** Target results in configured project order, including overlapping project memberships. */\n results: WorkspaceResult[];\n /** Files whose bytes changed when fix was requested. */\n changed?: string[];\n /** Targets that could not be read, fixed, or saved when fix was requested. */\n failures?: RewriteFileFailure[];\n /**\n * - 0: successful checks\n * - 1: compiler errors or denied lint\n * - 2: incomplete execution\n */\n exitCode: 0 | 1 | 2;\n}\n\n/**\n * Analyzes configured target scopes in a child process and closes it before returning.\n *\n * @param options - Configuration discovery and optional target filters. Omission checks all\n * configured targets from the process working directory.\n * @returns Results and an exit code. Readonly lint returns code 2 for empty selection or incomplete analysis.\n * @throws If configuration discovery, worker initialization, target enumeration, or cleanup fails.\n * Fix mode reports failures per target and continues with healthy targets. Empty selection throws.\n */\nexport async function lint(\n options: RewriteOptions & {\n /** Applies converged fixes and reports findings from the final source buffers. */\n fix?: boolean;\n } = {},\n): Promise<LintResult> {\n if (options.fix) {\n const result = await rewriteFiles(options, \"fixes\", true);\n return {\n ...result,\n exitCode: result.failures.length\n ? 2\n : result.results.some(({ result }) =>\n result.reports.some((report) => report.severity === \"error\"),\n )\n ? 1\n : 0,\n };\n }\n const config = resolveRewriteConfig(options);\n const worker = new AnalysisWorker();\n try {\n await worker.open(config);\n const results = await worker.lint(options.patterns);\n const exitCode =\n !results.length || results.some(({ result }) => result.status !== \"complete\")\n ? 2\n : results.some(({ result }) => result.reports.some((report) => report.severity === \"error\"))\n ? 1\n : 0;\n return { config, results, exitCode };\n } finally {\n await worker.close();\n }\n}\n\n/**\n * Formats findings and incomplete analysis for terminal output.\n *\n * @param result - Lint results whose reports use original document locations.\n * @returns Text with one-based line and column positions. Duplicate findings are removed per\n * project. Findings from overlapping projects remain separate. Successful results can return empty text.\n */\nexport function formatLint(result: LintResult): string {\n const lines: string[] = [];\n for (const { project, report } of lintReports(result.results)) {\n const location = report.primary.location;\n const at =\n report.primary.scope === \"document\"\n ? location.uri\n : `${location.uri}:${location.startLine + 1}:${location.startColumn + 1}`;\n lines.push(\n `[project ${project + 1}] ${at}: ${report.severity} ${report.code}: ${report.message}`,\n );\n for (const related of report.related) {\n lines.push(\n ` ${related.location.uri}:${related.location.startLine + 1}:${related.location.startColumn + 1}${related.message ? `: ${related.message}` : \"\"}`,\n );\n }\n lines.push(...report.notes.map((note) => ` ${note}`));\n }\n for (const entry of result.results) {\n if (entry.result.status !== \"complete\") {\n lines.push(\n `[project ${entry.project + 1}] ${entry.result.entry}: incomplete analysis${entry.result.error ? `: ${entry.result.error}` : \"\"}`,\n );\n for (const dependency of entry.result.graph?.dependencies ?? []) {\n if (dependency.status === \"unresolved\" || dependency.status === \"unsupported\") {\n lines.push(` ${dependency.status}: ${dependency.specifier} from ${dependency.importer}`);\n }\n }\n for (const range of entry.result.graph?.unverified ?? []) {\n lines.push(\n ` unverified: ${range.moduleId}${range.start === undefined ? \"\" : `:${range.start}-${range.end}`}: ${range.reason}`,\n );\n }\n }\n }\n for (const failure of result.failures ?? []) {\n if (!failure.results.some(({ result }) => result.status !== \"complete\")) {\n lines.push(`${failure.file}: ${failure.message}`);\n }\n }\n if (!result.results.length && !result.failures?.length) {\n lines.push(\"No analysis targets matched the configured scopes\");\n }\n return lines.join(\"\\n\");\n}\n","import path from \"node:path\";\nimport process from \"node:process\";\nimport { fileURLToPath } from \"node:url\";\n\nimport { findConfiguration, findDocumentConfiguration } from \"@stillwind/config/node\";\n\nimport { AnalysisWorker } from \"./worker-client.ts\";\nimport type {\n AnalysisWorkspaceContext,\n AnalysisWorkspaceService,\n OpenAnalysisWorkspaces,\n WorkspaceEditorResult,\n} from \"./workspace.ts\";\n\n/**\n * Lists the directories that bound configuration discovery.\n *\n * @param context - Workspace directory URIs.\n * @returns Absolute paths of the file URIs, or the process working directory for an empty list.\n * @throws If converting a malformed file URI fails.\n */\nfunction folderPaths(context: AnalysisWorkspaceContext): string[] {\n return context.workspaceFolders.length\n ? context.workspaceFolders\n .filter((uri) => uri.startsWith(\"file:\"))\n .map((uri) => fileURLToPath(uri))\n : [process.cwd()];\n}\n\n/**\n * Opens one isolated Node analysis process for each distinct configuration.\n *\n * @param context - Workspace directory URIs. File URIs use upward configuration discovery, and a\n * folder without a configuration opens no service. Other URI schemes cannot open Node workspaces.\n * An empty list uses the process working directory.\n * @param config - Optional explicit configuration path, resolved from the process working directory.\n * When supplied, it replaces discovery from workspace folders.\n * @returns Services keyed by absolute configuration path and separate initialization errors.\n * Services accept file URIs, forward buffers to their workers, and discard cancelled results.\n * @throws If converting a malformed file URI or closing a failed worker throws.\n */\nexport async function openNodeWorkspaces(\n context: AnalysisWorkspaceContext,\n config?: string,\n): Promise<OpenAnalysisWorkspaces> {\n const workspaces = new Map<string, AnalysisWorkspaceService>();\n const errors = new Map<string, string>();\n\n const paths = config\n ? [path.resolve(config)]\n : folderPaths(context).map((folder) => findConfiguration(folder));\n for (const file of new Set(paths.filter((file): file is string => Boolean(file)))) {\n await openConfiguration(file, workspaces, errors);\n }\n\n return {\n workspaces,\n errors,\n };\n}\n\n/**\n * Opens the nearest configuration of a document that no open service covers.\n *\n * @param uri - Document URI. Other schemes than `file:` open nothing.\n * @param context - Workspace directory URIs that bound the search.\n * @param known - Configuration paths that already have a service or an attempt.\n * @returns The new service and any initialization error, or undefined when the document has no\n * new configuration.\n * @throws If converting a malformed file URI or closing a failed worker throws.\n */\nexport async function discoverNodeWorkspace(\n uri: string,\n context: AnalysisWorkspaceContext,\n known: ReadonlySet<string>,\n): Promise<OpenAnalysisWorkspaces | undefined> {\n if (!uri.startsWith(\"file:\")) {\n return undefined;\n }\n const file = findDocumentConfiguration(fileURLToPath(uri), folderPaths(context));\n if (!file || known.has(file)) {\n return undefined;\n }\n const workspaces = new Map<string, AnalysisWorkspaceService>();\n const errors = new Map<string, string>();\n await openConfiguration(file, workspaces, errors);\n return {\n workspaces,\n errors,\n };\n}\n\n/**\n * Starts one analysis process and records its service or its initialization failure.\n *\n * @param file - Absolute configuration path.\n * @param workspaces - Receives the service keyed by file.\n * @param errors - Receives the failure message keyed by file.\n * @throws If closing a failed worker throws.\n */\nasync function openConfiguration(\n file: string,\n workspaces: Map<string, AnalysisWorkspaceService>,\n errors: Map<string, string>,\n): Promise<void> {\n const worker = new AnalysisWorker();\n try {\n await worker.open(file);\n /**\n * Selects document identities that can be forwarded to the filesystem worker.\n *\n * @param uri - Document URI whose syntax is validated later by `fileURLToPath`.\n * @returns Whether the URI begins with the `file:` scheme.\n */\n const accepts = (uri: string) => uri.startsWith(\"file:\");\n workspaces.set(file, {\n refresh: (uris) =>\n worker.request<boolean>({\n method: \"refresh\",\n files: uris.filter(accepts).map((uri) => fileURLToPath(uri)),\n }),\n affects: (uris) =>\n worker.request<boolean>({\n method: \"affects\",\n files: uris.filter(accepts).map((uri) => fileURLToPath(uri)),\n }),\n prepare: async (uris, signal) => {\n if (!signal?.aborted) {\n await worker.request({\n method: \"prepare\",\n files: uris.filter(accepts).map((uri) => fileURLToPath(uri)),\n });\n }\n },\n query: async (uri, request, signal) => {\n if (!accepts(uri) || signal?.aborted) {\n return [];\n }\n const results = await worker.request<WorkspaceEditorResult[]>({\n method: \"query\",\n file: fileURLToPath(uri),\n request,\n });\n return signal?.aborted ? [] : results;\n },\n update: async (uri, source, version) => {\n if (accepts(uri)) {\n await worker.request({\n method: \"update\",\n file: fileURLToPath(uri),\n source,\n version,\n });\n }\n },\n analyze: async (uri, signal) => {\n if (!accepts(uri) || signal?.aborted) {\n return [];\n }\n const results = await worker.analyze(fileURLToPath(uri));\n return signal?.aborted\n ? []\n : results.map(({ project, config, result }) => ({\n project,\n config,\n result: {\n entry: result.entry,\n revision: result.revision,\n status: result.status,\n reports: result.reports,\n error: result.error,\n dependencies: result.graph?.dependencies,\n unverified: result.graph?.unverified,\n generation: result.graph?.generation,\n },\n }));\n },\n closeDocument: async (uri) => {\n if (accepts(uri)) {\n await worker.request({\n method: \"closeDocument\",\n file: fileURLToPath(uri),\n });\n }\n },\n close: async () => {\n await worker.close();\n },\n });\n } catch (error) {\n errors.set(file, String(error));\n await worker.close();\n }\n}\n","import path from \"node:path\";\n\nimport { findConfiguration } from \"@stillwind/config/node\";\n\nimport { RewriteFailure, type RewriteInput, type RewriteResult } from \"./rewrite.ts\";\nimport { AnalysisWorker } from \"./worker-client.ts\";\n\n/** Reuses an isolated process while refreshing trusted configuration for each formatting request. */\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 * @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 * @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 * @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 * @param file - Source path whose parent starts upward discovery. Relative paths use cwd.\n * @param config - Optional explicit configuration path, returned without an existence check.\n * @returns The absolute configuration path, or undefined when discovery finds none.\n */\nexport function findFormatterConfig(file: string, config?: string): string | undefined {\n if (config) {\n return path.resolve(config);\n }\n return findConfiguration(path.dirname(path.resolve(file)));\n}\n"],"mappings":";;;;;;;;;;;AAmHA,IAAa,iBAAb,MAA4B;;CAE1B;;CAEA,2BAAoB,IAAI,IAQtB;;CAEF;;CAGA,UAAU;;CAEV,UAAU;;CAEV,WAAW;;;;CAKX,cAAc;EACZ,KAAK,SAAS,KAAK,cAAc,IAAI,IAAI,eAAe,YAAY,GAAG,CAAC,GAAG,CAAC,GAAG;GAC7E,OAAO;IAAC;IAAU;IAAQ;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,IA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M,KAAK,QAAQ,MAAM;CAC3B;AACF;;;;;;;AAQA,SAAgB,oBAAoB,MAAc,QAAqC;CACrF,IAAI,QACF,OAAO,KAAK,QAAQ,MAAM;CAE5B,OAAO,kBAAkB,KAAK,QAAQ,KAAK,QAAQ,IAAI,CAAC,CAAC;AAC3D"}
|
|
1
|
+
{"version":3,"file":"node.js","names":["process"],"sources":["../src/worker-client.ts","../src/write.ts","../src/rewrite-files.ts","../src/format.ts","../src/design-system.ts","../src/inspect.ts","../src/lint.ts","../src/node-workspace.ts","../src/source-formatter.ts"],"sourcesContent":["import { fork, type ChildProcess } from \"node:child_process\";\nimport process from \"node:process\";\nimport { fileURLToPath } from \"node:url\";\n\nimport type { DesignSystemRequest, EditorRequest, WorkspaceResult } from \"@stillwind/host\";\n\nimport { RewriteFailure, type RewriteInput, type RewriteBatchResult } from \"./rewrite.ts\";\n\n/** Requests sent to the process that owns trusted config evaluation and plugin lifetimes. */\nexport type WorkerRequest =\n | {\n /** Serialized discriminator for replacing the child workspace. */\n method: \"open\";\n /** Configuration path evaluated in the child process, replacing any previously opened workspace. */\n config: string;\n }\n | {\n /** Serialized discriminator for analyzing configured targets. */\n method: \"lint\";\n /** Additional target globs relative to each project root. Omission checks all configured targets. */\n patterns?: readonly string[];\n }\n | {\n /** Serialized discriminator for enumerating distinct targets. */\n method: \"targets\";\n /** Additional project-relative globs. An empty or omitted list keeps every configured target. */\n patterns?: readonly string[];\n /** Adds the stylesheets that each project lints. */\n stylesheets?: boolean;\n }\n | {\n /** Serialized discriminator for computing source replacements. */\n method: \"rewrite\";\n /** Distinct absolute target paths and captured text, retained in result order. */\n inputs: readonly RewriteInput[];\n /** Selects one sort pass or lint fixes that must converge. */\n operation: \"sort\" | \"fixes\";\n }\n | {\n /** Serialized discriminator for preparing a batch of targets. */\n method: \"prepare\";\n /** Absolute target paths. */\n files: readonly string[];\n }\n | {\n /** Serialized discriminator for analyzing one target in matching projects. */\n method: \"analyze\";\n /** Absolute target path. Each project whose scope contains the file returns a result. */\n file: string;\n }\n | {\n /** Serialized discriminator for an editor query against original text. */\n method: \"query\";\n /** Absolute target file path. */\n file: string;\n /** Editor operation in original UTF-16 coordinates. */\n request: EditorRequest;\n }\n | {\n /** Serialized discriminator for a question about each project's design system. */\n method: \"designSystem\";\n /** Theme, utility, or variant request. */\n request: DesignSystemRequest;\n }\n | {\n /** Serialized discriminator for replacing an unsaved buffer. */\n method: \"update\";\n /** Absolute source path, including dependencies outside target scopes. */\n file: string;\n /** Complete unsaved source text. */\n source: string;\n /** Safe integer that increases while this file is open. */\n version: number;\n }\n | {\n /** Serialized discriminator for removing an unsaved buffer. */\n method: \"closeDocument\";\n /** Absolute path of the buffer to remove. Unknown files have no effect. */\n file: string;\n }\n | {\n /** Serialized discriminator for checking whether the caller needs to reopen the workspace. */\n method: \"refresh\";\n /** Absolute file paths reported by save or watch notifications. */\n files: readonly string[];\n }\n | {\n /** Serialized discriminator for checking whether file changes can change results. */\n method: \"affects\";\n /** Absolute file paths reported by watch notifications. */\n files: readonly string[];\n }\n | {\n /** Serialized discriminator for refreshing disk and compiler caches. */\n method: \"invalidate\";\n }\n | {\n /** Serialized discriminator for closing hosts and disconnecting the child. */\n method: \"close\";\n };\n\n/** IPC response correlated with one request. Successful void operations can omit value. */\nexport interface WorkerReply {\n /** Request sequence number assigned by AnalysisWorker. */\n id: number;\n /** Serialized operation result when error is absent. */\n value?: unknown;\n /** Exception message and any analysis results that prevented a rewrite. */\n error?: {\n message: string;\n results?: WorkspaceResult[];\n };\n}\n\n/** Isolates configuration and plugin logs from CLI JSON and the LSP stdout transport. */\nexport class AnalysisWorker {\n /** Owned child with IPC enabled. Both output streams are forwarded to the parent's stderr. */\n readonly #child: ChildProcess;\n /** Unanswered requests keyed by monotonically assigned IPC sequence number. */\n readonly #pending = new Map<\n number,\n {\n /** Settles the request with the child's unvalidated reply value. */\n resolve: (value: unknown) => void;\n /** Rejects the request after delivery, child-operation, or process failure. */\n reject: (error: Error) => void;\n }\n >();\n /** Resolves on process closure after outstanding requests have been rejected. */\n readonly #closed: Promise<void>;\n\n /** Next IPC sequence number, independent of source document versions. */\n #nextId = 0;\n /** Whether process closure has been observed. */\n #exited = false;\n /** Prevents repeated close calls from sending another cleanup request. */\n #closing = false;\n\n /**\n * Starts the child process immediately. Call open before analysis and close when finished.\n */\n constructor() {\n this.#child = fork(fileURLToPath(new URL(\"./worker.js\", import.meta.url)), [], {\n stdio: [\"ignore\", \"pipe\", \"pipe\", \"ipc\"],\n execArgv: [],\n windowsHide: true,\n });\n this.#child.stdout!.on(\"data\", (data: Buffer) => {\n process.stderr.write(data);\n });\n this.#child.stderr!.on(\"data\", (data: Buffer) => {\n process.stderr.write(data);\n });\n this.#child.on(\"message\", (reply: WorkerReply) => {\n const request = this.#pending.get(reply.id);\n this.#pending.delete(reply.id);\n if (reply.error) {\n request?.reject(\n reply.error.results\n ? new RewriteFailure(reply.error.message, reply.error.results)\n : new Error(reply.error.message),\n );\n } else {\n request?.resolve(reply.value);\n }\n });\n this.#child.on(\"error\", (error) => {\n for (const request of this.#pending.values()) {\n request.reject(error);\n }\n this.#pending.clear();\n });\n this.#closed = new Promise((resolve) => {\n this.#child.on(\"close\", (code, signal) => {\n this.#exited = true;\n for (const request of this.#pending.values()) {\n request.reject(new Error(`Stillwind analysis worker closed (${code ?? signal})`));\n }\n this.#pending.clear();\n resolve();\n });\n });\n }\n\n /**\n * Sends an IPC operation and correlates its reply. Calls are not serialized here.\n *\n * @param request - Operation payload. Await open before using workspace operations, and avoid\n * overlapping replacement or closure with analysis requests.\n * @returns The reply value cast to T. The caller must choose T to match the operation's result.\n * @throws If the child is closed, IPC delivery fails, or the child operation reports an error.\n */\n async request<T = void>(request: WorkerRequest): Promise<T> {\n if (this.#exited) {\n throw new Error(\"Stillwind analysis worker is closed\");\n }\n const id = this.#nextId++;\n return (await new Promise<unknown>((resolve, reject) => {\n this.#pending.set(id, { resolve, reject });\n this.#child.send({ id, request }, (error) => {\n if (error) {\n this.#pending.delete(id);\n reject(error);\n }\n });\n })) as T;\n }\n\n /**\n * Replaces the child workspace, closing any previously opened hosts first.\n *\n * @param config - Configuration path. Relative paths use the child's inherited working directory.\n * @returns A promise that resolves after the configuration and project hosts have opened.\n * @throws If configuration evaluation, project initialization, or transport fails.\n */\n async open(config: string): Promise<void> {\n await this.request({\n method: \"open\",\n config,\n });\n }\n\n /**\n * Analyzes a target in each matching project of the opened workspace.\n *\n * @param file - Absolute target path. Unsaved buffers use preceding update requests.\n * @returns Scoped results in project order, or an empty list when no scope includes the target.\n * @throws If the workspace has not opened or transport fails.\n */\n analyze(file: string): Promise<WorkspaceResult[]> {\n return this.request({\n method: \"analyze\",\n file,\n });\n }\n\n /**\n * Enumerates and analyzes targets in the opened workspace.\n *\n * @param patterns - Additional globs relative to each project root. Empty or omitted filters\n * retain every configured target.\n * @returns Results in project order and sorted target order within each project.\n * @throws If the workspace has not opened, enumeration fails, or transport fails.\n */\n lint(patterns?: readonly string[]): Promise<WorkspaceResult[]> {\n return this.request({\n method: \"lint\",\n patterns,\n });\n }\n\n /**\n * Enumerates distinct targets in the opened workspace.\n *\n * @param patterns - Additional project-relative globs. Omission or an empty list retains all targets.\n * @param stylesheets - Adds the stylesheets that each project lints.\n * @returns Sorted absolute paths, deduplicated across projects.\n * @throws If the workspace has not opened, enumeration fails, or transport fails.\n */\n targets(patterns?: readonly string[], stylesheets?: boolean): Promise<string[]> {\n return this.request({\n method: \"targets\",\n patterns,\n stylesheets,\n });\n }\n\n /**\n * Computes replacements from captured buffers without writing files.\n *\n * @param inputs - Distinct absolute target paths and complete original text.\n * @param operation - Utility sorting or lint fixes, limited to ten changing passes per target.\n * @returns Successful replacements and target failures in input order. Captured buffers are removed after planning.\n * @throws If workspace setup, buffer installation, cleanup, or transport fails.\n */\n rewrite(\n inputs: readonly RewriteInput[],\n operation: \"sort\" | \"fixes\",\n ): Promise<RewriteBatchResult> {\n return this.request({\n method: \"rewrite\",\n inputs,\n operation,\n });\n }\n\n /**\n * Requests host cleanup and waits for the child process to close. After the cleanup request\n * settles, a child that remains alive for five seconds is terminated.\n *\n * @returns A promise that resolves after process closure. Repeated calls wait for that closure.\n * @throws If the initial cleanup request or its transport fails.\n */\n async close(): Promise<void> {\n if (this.#closing || this.#exited) {\n await this.#closed;\n return;\n }\n this.#closing = true;\n try {\n await this.request({\n method: \"close\",\n });\n } finally {\n const timer = setTimeout(() => {\n this.#child.kill();\n }, 5000);\n await this.#closed;\n clearTimeout(timer);\n }\n }\n}\n","import { readFile, writeFile } from \"node:fs/promises\";\n\nimport type { RewriteFileFailure } from \"./rewrite.ts\";\n\n/**\n * A replacement with the original bytes retained for verification before saving.\n */\nexport interface FileChange {\n /** Target path. The caller must provide at most one change per file. */\n file: string;\n /** Bytes captured before planning, compared against disk before saving. */\n before: Buffer;\n /** Planned replacement bytes. Equal bytes skip verification and writing. */\n after: Buffer;\n}\n\n/**\n * Saves changed bytes once per file. Identical buffers perform no filesystem operations.\n * Checks each original immediately before saving and continues after a target fails.\n *\n * @param changes - Distinct target paths and original/replacement bytes. Buffers remain unchanged.\n * @returns Saved paths and failures. A stale file is left unchanged.\n */\nexport async function writeChangedFiles(changes: readonly FileChange[]): Promise<{\n changed: string[];\n failures: RewriteFileFailure[];\n}> {\n const changed = changes.filter((change) => !change.before.equals(change.after));\n const saved: string[] = [];\n const failures: RewriteFileFailure[] = [];\n for (const change of changed) {\n try {\n if (!(await readFile(change.file)).equals(change.before)) {\n throw new Error(`Source changed before saving ${change.file}`);\n }\n await writeFile(change.file, change.after);\n saved.push(change.file);\n } catch (error) {\n failures.push({\n file: change.file,\n message: error instanceof Error ? error.message : String(error),\n results: [],\n });\n }\n }\n return {\n changed: saved,\n failures,\n };\n}\n","import { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { findConfiguration } from \"@stillwind/config/node\";\nimport type { WorkspaceResult } from \"@stillwind/host\";\n\nimport type { RewriteFileFailure, RewriteInput } from \"./rewrite.ts\";\nimport { AnalysisWorker } from \"./worker-client.ts\";\nimport { writeChangedFiles } from \"./write.ts\";\n\n/**\n * Selects configured source files for CLI analysis and rewriting.\n */\nexport interface RewriteOptions {\n /** Explicit configuration path, absolute or relative to cwd. Omission searches upward from cwd. */\n config?: string;\n /** Directory for configuration discovery and relative config paths. Defaults to process.cwd(). */\n cwd?: string;\n /** Additional globs relative to each project root. Omission or an empty list retains all configured targets. */\n patterns?: string[];\n}\n\n/**\n * A completed rewrite batch with findings kept separately for each owning project.\n */\ninterface RewriteFilesResult {\n /** Absolute configuration path used by the isolated worker. */\n config: string;\n /** Absolute paths whose original and final bytes differ, in sorted order. */\n changed: string[];\n /** Original findings for sorting and final findings for lint fixes, in project and target order. */\n results: WorkspaceResult[];\n /** Targets that could not be read, rewritten, or saved. */\n failures: RewriteFileFailure[];\n}\n\n/**\n * Computes all replacements before optionally saving changed files. Fixes return final findings.\n *\n * @param options - Configuration discovery and optional filters within configured target scopes.\n * @param operation - Utility sorting or converged lint fixes.\n * @param write - Whether to verify and save changed bytes after every replacement is planned.\n * @returns Configuration, sorted changed paths, findings, and independent target failures.\n * Saving reports only paths whose writes succeeded. Check mode reports planned changes.\n * @throws If selection is empty, configuration, worker communication, or cleanup fails.\n */\nexport async function rewriteFiles(\n options: RewriteOptions,\n operation: \"sort\" | \"fixes\",\n write: boolean,\n): Promise<RewriteFilesResult> {\n const config = resolveRewriteConfig(options);\n const worker = new AnalysisWorker();\n try {\n await worker.open(config);\n const files = await worker.targets(options.patterns, true);\n if (!files.length) {\n throw new Error(\"No analysis targets matched the configured scopes\");\n }\n const failures: RewriteFileFailure[] = [];\n const originals = new Map<string, Buffer>();\n const inputs: RewriteInput[] = [];\n const reads = await Promise.allSettled(files.map((file) => readFile(file)));\n for (const [index, read] of reads.entries()) {\n const file = files[index];\n try {\n if (read.status === \"rejected\") {\n throw read.reason;\n }\n const source = read.value.toString(\"utf8\");\n if (!Buffer.from(source).equals(read.value)) {\n throw new Error(`Source is not valid UTF-8: ${file}`);\n }\n originals.set(file, read.value);\n inputs.push({\n file,\n source,\n });\n } catch (error) {\n failures.push({\n file,\n message: error instanceof Error ? error.message : String(error),\n results: [],\n });\n }\n }\n const batch = await worker.rewrite(inputs, operation);\n failures.push(...batch.failures);\n const changes = batch.outputs.map((output) => ({\n file: output.file,\n before: originals.get(output.file)!,\n after: Buffer.from(output.code),\n }));\n let changed = changes\n .filter((change) => !change.before.equals(change.after))\n .map((change) => change.file);\n if (write) {\n const saved = await writeChangedFiles(changes);\n changed = saved.changed;\n failures.push(...saved.failures);\n }\n changed.sort();\n failures.sort((a, b) => a.file.localeCompare(b.file));\n const results = [...batch.outputs, ...batch.failures]\n .flatMap((output) => output.results)\n .sort((a, b) => a.project - b.project || a.result.entry.localeCompare(b.result.entry));\n return {\n config,\n changed,\n results,\n failures,\n };\n } finally {\n await worker.close();\n }\n}\n\n/**\n * Resolves an explicit configuration path or searches above the chosen working directory.\n *\n * @param options - Optional config path and cwd, defaulting to process.cwd().\n * @returns An absolute path. Explicit paths are resolved without evaluating the configuration.\n * @throws If discovery finds no configuration.\n */\nexport function resolveRewriteConfig(options: RewriteOptions): string {\n const cwd = options.cwd ?? process.cwd();\n const config = options.config ? path.resolve(cwd, options.config) : findConfiguration(cwd);\n if (!config) {\n throw new Error(`Cannot find Stillwind configuration above ${cwd}`);\n }\n return config;\n}\n","import type { WorkspaceResult } from \"@stillwind/host\";\n\nimport { rewriteFiles, type RewriteOptions } from \"./rewrite-files.ts\";\nimport type { RewriteFileFailure } from \"./rewrite.ts\";\n\n/** Sorting results whose changed paths compare original and final source bytes. */\nexport interface FormatResult {\n /** Absolute path of the evaluated configuration. */\n config: string;\n /** Absolute paths that changed or would change, in sorted order. */\n changed: string[];\n /** Findings from the original sources, in configured project and target order. */\n results: WorkspaceResult[];\n /** Targets that could not be read, rewritten, or saved. */\n failures: RewriteFileFailure[];\n /** Failures return 2. Check mode otherwise returns 1 when any file would change. */\n exitCode: 0 | 1 | 2;\n}\n\n/**\n * Sorts configured targets and saves changed files unless check is true.\n *\n * @param options - Configuration discovery, target filters, and optional check mode.\n * @returns Changed paths, original findings, and failures. Healthy targets continue after a failure.\n * @throws If selection, configuration, worker communication, or cleanup fails.\n */\nexport async function format(\n options: RewriteOptions & {\n /** Whether to report changes without saving them. Defaults to false. */\n check?: boolean;\n } = {},\n): Promise<FormatResult> {\n const result = await rewriteFiles(options, \"sort\", !options.check);\n return {\n ...result,\n exitCode: result.failures.length ? 2 : options.check && result.changed.length ? 1 : 0,\n };\n}\n","import type { DesignCandidate, DesignSystemRequest, DesignToken } from \"@stillwind/host\";\n\nimport { resolveRewriteConfig, type RewriteOptions } from \"./rewrite-files.ts\";\nimport { AnalysisWorker } from \"./worker-client.ts\";\n\n/**\n * Design-system answers from every project of one configuration.\n */\nexport interface DesignSystemAnswer {\n /** Absolute path of the evaluated configuration. */\n config: string;\n /** Tokens in project and name order. */\n tokens: (DesignToken & {\n /** Zero-based project index in the evaluated configuration. */\n project: number;\n })[];\n /** Candidates in project order. */\n candidates: (DesignCandidate & {\n /** Zero-based project index in the evaluated configuration. */\n project: number;\n })[];\n /** Targets without a match in any project. */\n unmatched: string[];\n}\n\n/**\n * Answers a question about each project's design system in a child process.\n *\n * @param options - Configuration discovery. Target globs do not apply.\n * @param request - Theme, utility, or variant request.\n * @returns Answers from every project. Unknown names and unmatched targets are data.\n * @throws If configuration discovery, worker initialization, CSS loading, a plugin, or cleanup fails.\n */\nexport async function designSystem(\n options: Omit<RewriteOptions, \"patterns\">,\n request: DesignSystemRequest,\n): Promise<DesignSystemAnswer> {\n const config = resolveRewriteConfig(options);\n const worker = new AnalysisWorker();\n try {\n await worker.open(config);\n const answers = await worker.request<\n {\n project: number;\n result: {\n tokens: DesignToken[];\n candidates: DesignCandidate[];\n unmatched: string[];\n };\n }[]\n >({\n method: \"designSystem\",\n request,\n });\n return {\n config,\n tokens: answers.flatMap(({ project, result }) =>\n result.tokens.map((token) => ({\n ...token,\n project,\n })),\n ),\n candidates: answers.flatMap(({ project, result }) =>\n result.candidates.map((candidate) => ({\n ...candidate,\n project,\n })),\n ),\n unmatched: request.targets.filter((target) =>\n answers.every(({ result }) => result.unmatched.includes(target)),\n ),\n };\n } finally {\n await worker.close();\n }\n}\n","import { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\n\nimport {\n isStylesheet,\n type EditorRequest,\n type EditorResult,\n type WorkspaceResult,\n} from \"@stillwind/host\";\n\nimport { lintReports } from \"./reports.ts\";\nimport { resolveRewriteConfig, type RewriteOptions } from \"./rewrite-files.ts\";\nimport { AnalysisWorker } from \"./worker-client.ts\";\nimport type { WorkspaceEditorResult } from \"./workspace.ts\";\n\n/**\n * Selects generated CSS by file, line, or position.\n */\nexport interface InspectTarget {\n /** Path or glob accepted by target selection. */\n pattern: string;\n /** One-based line. Omission selects the whole file. */\n line?: number;\n /** One-based UTF-16 column. It requires line. */\n column?: number;\n}\n\n/**\n * Generated CSS for one source range in one project.\n */\nexport interface InspectPreview {\n /** Zero-based project index in the evaluated configuration. */\n project: number;\n /** Original document range with zero-based lines and UTF-16 columns, and an exclusive end. */\n location: {\n uri: string;\n startLine: number;\n startColumn: number;\n endLine: number;\n endColumn: number;\n };\n /** Original source text in the range. */\n source: string;\n /** Formatted CSS. It is empty for a failed occurrence or a marker class. */\n css: string;\n /** False when diagnostics contains an error, or when a required style failed. */\n valid: boolean;\n /** Reports whose primary range overlaps this range. CSS omits the utilities that they reject. */\n diagnostics: {\n /** Report severity, as in the reports of lint. */\n severity: string;\n /** Stable compiler code or lint rule. */\n code: string;\n /** Description of the finding. */\n message: string;\n }[];\n /** Markdown for a marker class. */\n documentation?: string;\n /** Authored runtime key expressions that the CSS depends on. */\n runtimeNames?: string[];\n}\n\n/**\n * An editor answer with a source range. Hovers omit valid because they describe generated CSS.\n */\ntype PreviewRange = NonNullable<EditorResult[\"hover\"]> & {\n valid?: boolean;\n};\n\n/**\n * A target that could not be read.\n */\nexport interface InspectFailure {\n /** Absolute path of the target. */\n file: string;\n /** Reason for the failure. */\n message: string;\n}\n\n/**\n * Inspection results with analysis outcomes retained for each project.\n */\nexport interface InspectResult {\n /** Absolute path of the evaluated configuration. */\n config: string;\n /** Analysis of each selected file, in file and project order. */\n results: WorkspaceResult[];\n /** Selected previews in file, project, and source order, without repeated ranges. */\n previews: InspectPreview[];\n /** Targets that could not be read. */\n failures: InspectFailure[];\n}\n\n/**\n * Parses a command-line target with an optional `:line` or `:line:column` suffix.\n *\n * @param target - Path or glob, including absolute Windows paths.\n * @returns The pattern and any one-based position.\n * @throws If the position is not positive or the target names a stylesheet.\n */\nexport function parseInspectTarget(target: string): InspectTarget {\n const [, pattern, line, column] = /^(.+?)(?::(\\d+)(?::(\\d+))?)?$/s.exec(target) ?? [];\n if (!pattern || /^0+$/.test(line ?? \"\") || /^0+$/.test(column ?? \"\")) {\n throw new Error(`Invalid inspect target: ${target}`);\n }\n if (isStylesheet(pattern)) {\n throw new Error(`inspect does not accept stylesheets: ${target}`);\n }\n return {\n pattern,\n ...(line ? { line: Number(line) } : {}),\n ...(column ? { column: Number(column) } : {}),\n };\n}\n\n/**\n * Finds the UTF-16 offset of the start of each line.\n *\n * @param source - Document text. Lines end at `\\n`, so `\\r\\n` remains one line break.\n * @returns Ascending offsets, beginning with zero.\n */\nfunction lineOffsets(source: string): number[] {\n const offsets = [0];\n for (let index = source.indexOf(\"\\n\"); index >= 0; index = source.indexOf(\"\\n\", index + 1)) {\n offsets.push(index + 1);\n }\n return offsets;\n}\n\n/**\n * Converts an offset to a position.\n *\n * @param lines - Result of {@link lineOffsets}.\n * @param offset - UTF-16 offset in the same document.\n * @returns The zero-based line and column.\n */\nfunction position(lines: readonly number[], offset: number) {\n let line = lines.length - 1;\n while (lines[line] > offset) {\n line--;\n }\n return {\n line,\n column: offset - lines[line],\n };\n}\n\n/**\n * Checks whether a report location belongs to a file.\n *\n * @param uri - File URI or path.\n * @param file - Absolute path.\n * @returns Whether both name the same path.\n */\nfunction isDocument(uri: string, file: string): boolean {\n return path.resolve(uri.startsWith(\"file:\") ? fileURLToPath(uri) : uri) === path.resolve(file);\n}\n\n/**\n * Answers one target for one file.\n *\n * @param worker - Opened worker that owns the file's analysis.\n * @param file - Absolute target path.\n * @param source - Text of the file.\n * @param target - Position to select. Positions outside the file select nothing.\n * @param reports - Reports with a range in this file, for each project.\n * @returns Previews with their project, in project and source order.\n * @throws If the editor query fails.\n */\nasync function selectPreviews(\n worker: AnalysisWorker,\n file: string,\n source: string,\n target: InspectTarget,\n reports: ReturnType<typeof lintReports>,\n): Promise<InspectPreview[]> {\n const lines = lineOffsets(source);\n const line = target.line === undefined ? undefined : target.line - 1;\n const lineStart = line === undefined ? undefined : lines[line];\n const lineEnd = line === undefined ? undefined : (lines[line + 1] ?? source.length + 1) - 1;\n if (line !== undefined && lineStart === undefined) {\n return [];\n }\n const offset = target.column === undefined ? undefined : lineStart! + target.column - 1;\n if (offset !== undefined && offset > lineEnd!) {\n return [];\n }\n const query = (request: EditorRequest) =>\n worker.request<WorkspaceEditorResult[]>({ method: \"query\", file, request });\n const uri = pathToFileURL(file).href;\n let selected: { project: number; range: PreviewRange }[];\n if (offset === undefined) {\n selected = (\n await query({\n kind: \"previews\",\n })\n ).flatMap(({ project, result }) =>\n (result.previews ?? [])\n .filter(({ start, end }) => line === undefined || (end > lineStart! && start <= lineEnd!))\n .map((range) => ({\n project,\n range,\n })),\n );\n } else {\n const hovers = await query({\n kind: \"hover\",\n offset,\n });\n selected = hovers.flatMap(({ project, result }) =>\n result.hover ? [{ project, range: result.hover }] : [],\n );\n if (selected.length < hovers.length) {\n // Failed occurrences and Vue template expressions have no hover, so the listing supplies them.\n const answered = new Set(selected.map(({ project }) => project));\n selected.push(\n ...(\n await query({\n kind: \"previews\",\n })\n ).flatMap(({ project, result }) =>\n answered.has(project)\n ? []\n : (result.previews ?? [])\n .filter(({ start, end }) => start <= offset && offset <= end)\n .map((range) => ({\n project,\n range,\n })),\n ),\n );\n }\n }\n return selected.flatMap(\n ({ project, range: { start, end, css, valid = true, documentation, runtimeNames } }) => {\n const diagnostics = reports\n .filter(\n ({ project: owner, report: { primary } }) =>\n owner === project &&\n primary.location.startUtf16 < end &&\n start < Math.max(primary.location.endUtf16, primary.location.startUtf16 + 1),\n )\n .map(({ report: { severity, code, message } }) => ({ severity, code, message }));\n if (!css && valid && !diagnostics.length && !documentation) {\n return [];\n }\n const first = position(lines, start);\n const last = position(lines, end);\n return [\n {\n project,\n location: {\n uri,\n startLine: first.line,\n startColumn: first.column,\n endLine: last.line,\n endColumn: last.column,\n },\n source: source.slice(start, end),\n css,\n valid: valid && !diagnostics.some(({ severity }) => severity === \"error\"),\n diagnostics,\n ...(documentation ? { documentation } : {}),\n ...(runtimeNames ? { runtimeNames } : {}),\n },\n ];\n },\n );\n}\n\n/**\n * Reports the generated CSS of configured source files in a child process.\n *\n * @param options - Configuration discovery and targets. Paths and globs follow the target rules\n * of lint. Stylesheets are not accepted, and an empty list selects every configured source file.\n * @returns Previews and analysis results. A file with incomplete analysis has no previews.\n * @throws If a target is invalid or matches no file, or if configuration discovery, worker\n * initialization, target enumeration, or cleanup fails.\n */\nexport async function inspect(\n options: Omit<RewriteOptions, \"patterns\"> & {\n /** Targets as written on the command line. */\n targets?: readonly string[];\n } = {},\n): Promise<InspectResult> {\n const targets = (options.targets ?? []).map(parseInspectTarget);\n const config = resolveRewriteConfig(options);\n const worker = new AnalysisWorker();\n try {\n await worker.open(config);\n const selections = new Map<string, InspectTarget[]>();\n for (const target of targets.length ? targets : [undefined]) {\n const files = (await worker.targets(target ? [target.pattern] : undefined)).filter(\n (file) => !isStylesheet(file),\n );\n if (!files.length) {\n throw new Error(\n target\n ? `No analysis targets matched ${target.pattern}`\n : \"No analysis targets matched the configured scopes\",\n );\n }\n for (const file of files) {\n selections.set(file, [\n ...(selections.get(file) ?? []),\n target ?? {\n pattern: file,\n },\n ]);\n }\n }\n const files = [...selections.keys()].sort();\n await worker.request({\n method: \"prepare\",\n files,\n });\n\n const result: InspectResult = {\n config,\n results: [],\n previews: [],\n failures: [],\n };\n for (const file of files) {\n const analyses = await worker.analyze(file);\n result.results.push(...analyses);\n const complete = new Set(\n analyses.filter(({ result }) => result.status === \"complete\").map(({ project }) => project),\n );\n let source: string;\n try {\n const bytes = await readFile(file);\n source = bytes.toString(\"utf8\");\n if (!Buffer.from(source).equals(bytes)) {\n throw new Error(`Source is not valid UTF-8: ${file}`);\n }\n } catch (error) {\n result.failures.push({\n file,\n message: error instanceof Error ? error.message : String(error),\n });\n continue;\n }\n const reports = lintReports(analyses).filter(\n ({ report }) =>\n report.primary.scope === \"range\" && isDocument(report.primary.location.uri, file),\n );\n const seen = new Set<string>();\n const previews: InspectPreview[] = [];\n for (const target of selections.get(file)!) {\n for (const preview of await selectPreviews(worker, file, source, target, reports)) {\n const { startLine, startColumn, endLine, endColumn } = preview.location;\n const key = [preview.project, startLine, startColumn, endLine, endColumn].join();\n if (complete.has(preview.project) && !seen.has(key)) {\n seen.add(key);\n previews.push(preview);\n }\n }\n }\n result.previews.push(\n ...previews.sort(\n (a, b) =>\n a.project - b.project ||\n a.location.startLine - b.location.startLine ||\n a.location.startColumn - b.location.startColumn,\n ),\n );\n }\n return result;\n } finally {\n await worker.close();\n }\n}\n","import type { WorkspaceResult } from \"@stillwind/host\";\n\nimport { lintReports } from \"./reports.ts\";\nimport { resolveRewriteConfig, rewriteFiles, type RewriteOptions } from \"./rewrite-files.ts\";\nimport type { RewriteFileFailure } from \"./rewrite.ts\";\nimport { AnalysisWorker } from \"./worker-client.ts\";\n\n/** Lint results preserve project membership and identify incomplete analysis. */\nexport interface LintResult {\n /** Absolute path of the evaluated configuration. */\n config: string;\n /** Target results in configured project order, including overlapping project memberships. */\n results: WorkspaceResult[];\n /** Files whose bytes changed when fix was requested. */\n changed?: string[];\n /** Targets that could not be read, fixed, or saved when fix was requested. */\n failures?: RewriteFileFailure[];\n /**\n * - 0: successful checks\n * - 1: compiler errors or denied lint\n * - 2: incomplete execution\n */\n exitCode: 0 | 1 | 2;\n}\n\n/**\n * Analyzes configured target scopes in a child process and closes it before returning.\n *\n * @param options - Configuration discovery and optional target filters. Omission checks all\n * configured targets from the process working directory.\n * @returns Results and an exit code. Readonly lint returns code 2 for empty selection or incomplete analysis.\n * @throws If configuration discovery, worker initialization, target enumeration, or cleanup fails.\n * Fix mode reports failures per target and continues with healthy targets. Empty selection throws.\n */\nexport async function lint(\n options: RewriteOptions & {\n /** Applies converged fixes and reports findings from the final source buffers. */\n fix?: boolean;\n } = {},\n): Promise<LintResult> {\n if (options.fix) {\n const result = await rewriteFiles(options, \"fixes\", true);\n return {\n ...result,\n exitCode: result.failures.length\n ? 2\n : result.results.some(({ result }) =>\n result.reports.some((report) => report.severity === \"error\"),\n )\n ? 1\n : 0,\n };\n }\n const config = resolveRewriteConfig(options);\n const worker = new AnalysisWorker();\n try {\n await worker.open(config);\n const results = await worker.lint(options.patterns);\n const exitCode =\n !results.length || results.some(({ result }) => result.status !== \"complete\")\n ? 2\n : results.some(({ result }) => result.reports.some((report) => report.severity === \"error\"))\n ? 1\n : 0;\n return { config, results, exitCode };\n } finally {\n await worker.close();\n }\n}\n\n/**\n * Formats findings and incomplete analysis for terminal output.\n *\n * @param result - Lint results whose reports use original document locations.\n * @returns Text with one-based line and column positions. Duplicate findings are removed per\n * project. Findings from overlapping projects remain separate. Successful results can return empty text.\n */\nexport function formatLint(result: LintResult): string {\n const lines: string[] = [];\n for (const { project, report } of lintReports(result.results)) {\n const location = report.primary.location;\n const at =\n report.primary.scope === \"document\"\n ? location.uri\n : `${location.uri}:${location.startLine + 1}:${location.startColumn + 1}`;\n lines.push(\n `[project ${project + 1}] ${at}: ${report.severity} ${report.code}: ${report.message}`,\n );\n for (const related of report.related) {\n lines.push(\n ` ${related.location.uri}:${related.location.startLine + 1}:${related.location.startColumn + 1}${related.message ? `: ${related.message}` : \"\"}`,\n );\n }\n lines.push(...report.notes.map((note) => ` ${note}`));\n }\n for (const entry of result.results) {\n if (entry.result.status !== \"complete\") {\n lines.push(\n `[project ${entry.project + 1}] ${entry.result.entry}: incomplete analysis${entry.result.error ? `: ${entry.result.error}` : \"\"}`,\n );\n for (const dependency of entry.result.graph?.dependencies ?? []) {\n if (dependency.status === \"unresolved\" || dependency.status === \"unsupported\") {\n lines.push(` ${dependency.status}: ${dependency.specifier} from ${dependency.importer}`);\n }\n }\n for (const range of entry.result.graph?.unverified ?? []) {\n lines.push(\n ` unverified: ${range.moduleId}${range.start === undefined ? \"\" : `:${range.start}-${range.end}`}: ${range.reason}`,\n );\n }\n }\n }\n for (const failure of result.failures ?? []) {\n if (!failure.results.some(({ result }) => result.status !== \"complete\")) {\n lines.push(`${failure.file}: ${failure.message}`);\n }\n }\n if (!result.results.length && !result.failures?.length) {\n lines.push(\"No analysis targets matched the configured scopes\");\n }\n return lines.join(\"\\n\");\n}\n","import path from \"node:path\";\nimport process from \"node:process\";\nimport { fileURLToPath } from \"node:url\";\n\nimport { findConfiguration, findDocumentConfiguration } from \"@stillwind/config/node\";\n\nimport { AnalysisWorker } from \"./worker-client.ts\";\nimport type {\n AnalysisWorkspaceContext,\n AnalysisWorkspaceService,\n OpenAnalysisWorkspaces,\n WorkspaceEditorResult,\n} from \"./workspace.ts\";\n\n/**\n * Lists the directories that bound configuration discovery.\n *\n * @param context - Workspace directory URIs.\n * @returns Absolute paths of the file URIs, or the process working directory for an empty list.\n * @throws If converting a malformed file URI fails.\n */\nfunction folderPaths(context: AnalysisWorkspaceContext): string[] {\n return context.workspaceFolders.length\n ? context.workspaceFolders\n .filter((uri) => uri.startsWith(\"file:\"))\n .map((uri) => fileURLToPath(uri))\n : [process.cwd()];\n}\n\n/**\n * Opens one isolated Node analysis process for each distinct configuration.\n *\n * @param context - Workspace directory URIs. File URIs use upward configuration discovery, and a\n * folder without a configuration opens no service. Other URI schemes cannot open Node workspaces.\n * An empty list uses the process working directory.\n * @param config - Optional explicit configuration path, resolved from the process working directory.\n * When supplied, it replaces discovery from workspace folders.\n * @returns Services keyed by absolute configuration path and separate initialization errors.\n * Services accept file URIs, forward buffers to their workers, and discard cancelled results.\n * @throws If converting a malformed file URI or closing a failed worker throws.\n */\nexport async function openNodeWorkspaces(\n context: AnalysisWorkspaceContext,\n config?: string,\n): Promise<OpenAnalysisWorkspaces> {\n const workspaces = new Map<string, AnalysisWorkspaceService>();\n const errors = new Map<string, string>();\n\n const paths = config\n ? [path.resolve(config)]\n : folderPaths(context).map((folder) => findConfiguration(folder));\n for (const file of new Set(paths.filter((file): file is string => Boolean(file)))) {\n await openConfiguration(file, workspaces, errors);\n }\n\n return {\n workspaces,\n errors,\n };\n}\n\n/**\n * Opens the nearest configuration of a document that no open service covers.\n *\n * @param uri - Document URI. Other schemes than `file:` open nothing.\n * @param context - Workspace directory URIs that bound the search.\n * @param known - Configuration paths that already have a service or an attempt.\n * @returns The new service and any initialization error, or undefined when the document has no\n * new configuration.\n * @throws If converting a malformed file URI or closing a failed worker throws.\n */\nexport async function discoverNodeWorkspace(\n uri: string,\n context: AnalysisWorkspaceContext,\n known: ReadonlySet<string>,\n): Promise<OpenAnalysisWorkspaces | undefined> {\n if (!uri.startsWith(\"file:\")) {\n return undefined;\n }\n const file = findDocumentConfiguration(fileURLToPath(uri), folderPaths(context));\n if (!file || known.has(file)) {\n return undefined;\n }\n const workspaces = new Map<string, AnalysisWorkspaceService>();\n const errors = new Map<string, string>();\n await openConfiguration(file, workspaces, errors);\n return {\n workspaces,\n errors,\n };\n}\n\n/**\n * Starts one analysis process and records its service or its initialization failure.\n *\n * @param file - Absolute configuration path.\n * @param workspaces - Receives the service keyed by file.\n * @param errors - Receives the failure message keyed by file.\n * @throws If closing a failed worker throws.\n */\nasync function openConfiguration(\n file: string,\n workspaces: Map<string, AnalysisWorkspaceService>,\n errors: Map<string, string>,\n): Promise<void> {\n const worker = new AnalysisWorker();\n try {\n await worker.open(file);\n /**\n * Selects document identities that can be forwarded to the filesystem worker.\n *\n * @param uri - Document URI whose syntax is validated later by `fileURLToPath`.\n * @returns Whether the URI begins with the `file:` scheme.\n */\n const accepts = (uri: string) => uri.startsWith(\"file:\");\n workspaces.set(file, {\n refresh: (uris) =>\n worker.request<boolean>({\n method: \"refresh\",\n files: uris.filter(accepts).map((uri) => fileURLToPath(uri)),\n }),\n affects: (uris) =>\n worker.request<boolean>({\n method: \"affects\",\n files: uris.filter(accepts).map((uri) => fileURLToPath(uri)),\n }),\n prepare: async (uris, signal) => {\n if (!signal?.aborted) {\n await worker.request({\n method: \"prepare\",\n files: uris.filter(accepts).map((uri) => fileURLToPath(uri)),\n });\n }\n },\n query: async (uri, request, signal) => {\n if (!accepts(uri) || signal?.aborted) {\n return [];\n }\n const results = await worker.request<WorkspaceEditorResult[]>({\n method: \"query\",\n file: fileURLToPath(uri),\n request,\n });\n return signal?.aborted ? [] : results;\n },\n update: async (uri, source, version) => {\n if (accepts(uri)) {\n await worker.request({\n method: \"update\",\n file: fileURLToPath(uri),\n source,\n version,\n });\n }\n },\n analyze: async (uri, signal) => {\n if (!accepts(uri) || signal?.aborted) {\n return [];\n }\n const results = await worker.analyze(fileURLToPath(uri));\n return signal?.aborted\n ? []\n : results.map(({ project, config, result }) => ({\n project,\n config,\n result: {\n entry: result.entry,\n revision: result.revision,\n status: result.status,\n reports: result.reports,\n error: result.error,\n dependencies: result.graph?.dependencies,\n unverified: result.graph?.unverified,\n generation: result.graph?.generation,\n },\n }));\n },\n closeDocument: async (uri) => {\n if (accepts(uri)) {\n await worker.request({\n method: \"closeDocument\",\n file: fileURLToPath(uri),\n });\n }\n },\n close: async () => {\n await worker.close();\n },\n });\n } catch (error) {\n errors.set(file, String(error));\n await worker.close();\n }\n}\n","import path from \"node:path\";\n\nimport { findConfiguration } from \"@stillwind/config/node\";\n\nimport { RewriteFailure, type RewriteInput, type RewriteResult } from \"./rewrite.ts\";\nimport { AnalysisWorker } from \"./worker-client.ts\";\n\n/**\n * Reuses an isolated process while refreshing trusted configuration for each formatting request.\n */\nexport class SourceFormatter {\n /** Child process reused across formatting requests and owned until close completes. */\n readonly #worker = new AnalysisWorker();\n /** Serializes requests while allowing a new request after a preceding failure. */\n #queue: Promise<unknown> = Promise.resolve();\n\n /**\n * Starts the isolated worker that evaluates configuration on each formatting request.\n *\n * @param config - Configuration path resolved in the worker's inherited working directory.\n */\n constructor(private readonly config: string) {}\n\n /**\n * Sorts the supplied buffer with current project settings.\n * Files outside all configured scopes return unchanged text. Requests are serialized and never write files.\n *\n * @param input - Original buffer and optional protected ranges. Relative paths are resolved from cwd.\n * @returns The sorted buffer and original findings after configuration is reopened.\n * @throws If configuration loading, parsing, analysis, project agreement, rewriting, or worker communication fails.\n */\n format(input: RewriteInput): Promise<RewriteResult> {\n const task = this.#queue.then(async () => {\n await this.#worker.open(this.config);\n const { outputs, failures } = await this.#worker.rewrite(\n [\n {\n ...input,\n file: path.resolve(input.file),\n },\n ],\n \"sort\",\n );\n if (failures.length) {\n throw new RewriteFailure(failures[0].message, failures[0].results);\n }\n return outputs[0];\n });\n this.#queue = task.catch(() => {});\n return task;\n }\n\n /**\n * Waits for queued formatting and releases the child process. Stop submitting requests before closure.\n *\n * @returns Completion of worker cleanup.\n * @throws If the worker's cleanup request fails.\n */\n async close(): Promise<void> {\n await this.#queue;\n await this.#worker.close();\n }\n}\n\n/**\n * Finds a configuration above a source file or resolves an explicit path from cwd.\n *\n * @param file - Source path whose parent starts upward discovery. Relative paths use cwd.\n * @param config - Optional explicit configuration path, returned without an existence check.\n * @returns The absolute configuration path, or undefined when discovery finds none.\n */\nexport function findFormatterConfig(file: string, config?: string): string | undefined {\n if (config) {\n return path.resolve(config);\n }\n return findConfiguration(path.dirname(path.resolve(file)));\n}\n"],"mappings":";;;;;;;;;;;AAmHA,IAAa,iBAAb,MAA4B;;CAE1B;;CAEA,2BAAoB,IAAI,IAQtB;;CAEF;;CAGA,UAAU;;CAEV,UAAU;;CAEV,WAAW;;;;CAKX,cAAc;EACZ,KAAK,SAAS,KAAK,cAAc,IAAI,IAAI,eAAe,YAAY,GAAG,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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,6 +1,7 @@
|
|
|
1
1
|
// src/reports.ts
|
|
2
2
|
/**
|
|
3
3
|
* Collects distinct reports per project while preserving their analysis order.
|
|
4
|
+
*
|
|
4
5
|
* @param results - Analysis results with their project membership.
|
|
5
6
|
* @returns Reports in first-occurrence order. Equal reports from different projects remain separate.
|
|
6
7
|
*/
|
|
@@ -18,6 +19,7 @@ function lintReports(results) {
|
|
|
18
19
|
}
|
|
19
20
|
/**
|
|
20
21
|
* Returns the website page that explains a report code.
|
|
22
|
+
*
|
|
21
23
|
* @param code - Compiler code, such as `SW01001`, or lint rule name, such as `unknown-utility`.
|
|
22
24
|
* @returns The page URL, or undefined for codes without a page, such as `SW_UNVERIFIED`.
|
|
23
25
|
*/
|
|
@@ -27,6 +29,7 @@ function documentationUrl(code) {
|
|
|
27
29
|
}
|
|
28
30
|
/**
|
|
29
31
|
* Returns the documentation section of a report code.
|
|
32
|
+
*
|
|
30
33
|
* @param code - Report code of a diagnostic.
|
|
31
34
|
* @returns `errors` for compiler codes, `lints` for lint rule names, and otherwise undefined.
|
|
32
35
|
*/
|
|
@@ -35,4 +38,4 @@ function documentationSection(code) {
|
|
|
35
38
|
}
|
|
36
39
|
export { documentationUrl as n, lintReports as r, documentationSection as t };
|
|
37
40
|
|
|
38
|
-
//# sourceMappingURL=reports-
|
|
41
|
+
//# sourceMappingURL=reports-DvHppcFa.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"reports-DvHppcFa.js","names":[],"sources":["../src/reports.ts"],"sourcesContent":["import type { WorkspaceResult } from \"./workspace.ts\";\n\n/**\n * Collects distinct reports per project while preserving their analysis order.\n *\n * @param results - Analysis results with their project membership.\n * @returns Reports in first-occurrence order. Equal reports from different projects remain separate.\n */\nexport function lintReports(results: readonly WorkspaceResult[]) {\n const seen = new Set<string>();\n return results.flatMap((entry) =>\n entry.result.reports.flatMap((report) => {\n const key = JSON.stringify([entry.project, report]);\n if (seen.has(key)) {\n return [];\n }\n seen.add(key);\n return [\n {\n project: entry.project,\n report,\n },\n ];\n }),\n );\n}\n\n/**\n * Returns the website page that explains a report code.\n *\n * @param code - Compiler code, such as `SW01001`, or lint rule name, such as `unknown-utility`.\n * @returns The page URL, or undefined for codes without a page, such as `SW_UNVERIFIED`.\n */\nexport function documentationUrl(code: string): string | undefined {\n const section = documentationSection(code);\n return section && `https://stillwind.dev/docs/${section}/${code}`;\n}\n\n/**\n * Returns the documentation section of a report code.\n *\n * @param code - Report code of a diagnostic.\n * @returns `errors` for compiler codes, `lints` for lint rule names, and otherwise undefined.\n */\nexport function documentationSection(code: string): \"errors\" | \"lints\" | undefined {\n return /^SW\\d+$/.test(code) ? \"errors\" : /^[a-z][a-z-]*$/.test(code) ? \"lints\" : undefined;\n}\n"],"mappings":";;;;;;;AAQA,SAAgB,YAAY,SAAqC;CAC/D,MAAM,uBAAO,IAAI,IAAY;CAC7B,OAAO,QAAQ,SAAS,UACtB,MAAM,OAAO,QAAQ,SAAS,WAAW;EACvC,MAAM,MAAM,KAAK,UAAU,CAAC,MAAM,SAAS,MAAM,CAAC;EAClD,IAAI,KAAK,IAAI,GAAG,GACd,OAAO,CAAC;EAEV,KAAK,IAAI,GAAG;EACZ,OAAO,CACL;GACE,SAAS,MAAM;GACf;EACF,CACF;CACF,CAAC,CACH;AACF;;;;;;;AAQA,SAAgB,iBAAiB,MAAkC;CACjE,MAAM,UAAU,qBAAqB,IAAI;CACzC,OAAO,WAAW,8BAA8B,QAAQ,GAAG;AAC7D;;;;;;;AAQA,SAAgB,qBAAqB,MAA8C;CACjF,OAAO,UAAU,KAAK,IAAI,IAAI,WAAW,iBAAiB,KAAK,IAAI,IAAI,UAAU,KAAA;AACnF"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { l as WorkspaceResult } from "./workspace-DIADkpZF.js";
|
|
2
2
|
/**
|
|
3
3
|
* Collects distinct reports per project while preserving their analysis order.
|
|
4
|
+
*
|
|
4
5
|
* @param results - Analysis results with their project membership.
|
|
5
6
|
* @returns Reports in first-occurrence order. Equal reports from different projects remain separate.
|
|
6
7
|
*/
|
|
@@ -10,15 +11,17 @@ declare function lintReports(results: readonly WorkspaceResult[]): {
|
|
|
10
11
|
}[];
|
|
11
12
|
/**
|
|
12
13
|
* Returns the website page that explains a report code.
|
|
14
|
+
*
|
|
13
15
|
* @param code - Compiler code, such as `SW01001`, or lint rule name, such as `unknown-utility`.
|
|
14
16
|
* @returns The page URL, or undefined for codes without a page, such as `SW_UNVERIFIED`.
|
|
15
17
|
*/
|
|
16
18
|
declare function documentationUrl(code: string): string | undefined;
|
|
17
19
|
/**
|
|
18
20
|
* Returns the documentation section of a report code.
|
|
21
|
+
*
|
|
19
22
|
* @param code - Report code of a diagnostic.
|
|
20
23
|
* @returns `errors` for compiler codes, `lints` for lint rule names, and otherwise undefined.
|
|
21
24
|
*/
|
|
22
25
|
declare function documentationSection(code: string): "errors" | "lints" | undefined;
|
|
23
26
|
export { documentationUrl as n, lintReports as r, documentationSection as t };
|
|
24
|
-
//# sourceMappingURL=reports-
|
|
27
|
+
//# sourceMappingURL=reports-Dy2Qrbj_.d.ts.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@stillwind/analysis",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.0",
|
|
4
4
|
"description": "Analysis services for the Stillwind CLI, language server, and editors",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"stillwind"
|
|
@@ -16,7 +16,9 @@
|
|
|
16
16
|
"directory": "packages/analysis"
|
|
17
17
|
},
|
|
18
18
|
"files": [
|
|
19
|
-
"dist"
|
|
19
|
+
"dist",
|
|
20
|
+
"README.md",
|
|
21
|
+
"CHANGELOG.md"
|
|
20
22
|
],
|
|
21
23
|
"type": "module",
|
|
22
24
|
"types": "./dist/index.d.ts",
|
|
@@ -43,16 +45,16 @@
|
|
|
43
45
|
"access": "public"
|
|
44
46
|
},
|
|
45
47
|
"dependencies": {
|
|
46
|
-
"@stillwind/config": "0.
|
|
47
|
-
"@stillwind/host": "0.
|
|
48
|
-
"@stillwind/native": "0.
|
|
49
|
-
"minimatch": "^11.0.
|
|
48
|
+
"@stillwind/config": "0.10.0",
|
|
49
|
+
"@stillwind/host": "0.10.0",
|
|
50
|
+
"@stillwind/native": "0.10.0",
|
|
51
|
+
"minimatch": "^11.0.5",
|
|
50
52
|
"pathe": "^2.0.3"
|
|
51
53
|
},
|
|
52
54
|
"devDependencies": {
|
|
53
55
|
"@stillwind-internal/tools-workspace": "0.0.0",
|
|
54
56
|
"@types/node": "^26.6.6",
|
|
55
57
|
"typescript": "^6.0.3",
|
|
56
|
-
"vite-plus": "1.
|
|
58
|
+
"vite-plus": "1.6.0"
|
|
57
59
|
}
|
|
58
60
|
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"reports-DN38lybK.js","names":[],"sources":["../src/reports.ts"],"sourcesContent":["import type { WorkspaceResult } from \"./workspace.ts\";\n\n/**\n * Collects distinct reports per project while preserving their analysis order.\n * @param results - Analysis results with their project membership.\n * @returns Reports in first-occurrence order. Equal reports from different projects remain separate.\n */\nexport function lintReports(results: readonly WorkspaceResult[]) {\n const seen = new Set<string>();\n return results.flatMap((entry) =>\n entry.result.reports.flatMap((report) => {\n const key = JSON.stringify([entry.project, report]);\n if (seen.has(key)) {\n return [];\n }\n seen.add(key);\n return [\n {\n project: entry.project,\n report,\n },\n ];\n }),\n );\n}\n\n/**\n * Returns the website page that explains a report code.\n * @param code - Compiler code, such as `SW01001`, or lint rule name, such as `unknown-utility`.\n * @returns The page URL, or undefined for codes without a page, such as `SW_UNVERIFIED`.\n */\nexport function documentationUrl(code: string): string | undefined {\n const section = documentationSection(code);\n return section && `https://stillwind.dev/docs/${section}/${code}`;\n}\n\n/**\n * Returns the documentation section of a report code.\n * @param code - Report code of a diagnostic.\n * @returns `errors` for compiler codes, `lints` for lint rule names, and otherwise undefined.\n */\nexport function documentationSection(code: string): \"errors\" | \"lints\" | undefined {\n return /^SW\\d+$/.test(code) ? \"errors\" : /^[a-z][a-z-]*$/.test(code) ? \"lints\" : undefined;\n}\n"],"mappings":";;;;;;AAOA,SAAgB,YAAY,SAAqC;CAC/D,MAAM,uBAAO,IAAI,IAAY;CAC7B,OAAO,QAAQ,SAAS,UACtB,MAAM,OAAO,QAAQ,SAAS,WAAW;EACvC,MAAM,MAAM,KAAK,UAAU,CAAC,MAAM,SAAS,MAAM,CAAC;EAClD,IAAI,KAAK,IAAI,GAAG,GACd,OAAO,CAAC;EAEV,KAAK,IAAI,GAAG;EACZ,OAAO,CACL;GACE,SAAS,MAAM;GACf;EACF,CACF;CACF,CAAC,CACH;AACF;;;;;;AAOA,SAAgB,iBAAiB,MAAkC;CACjE,MAAM,UAAU,qBAAqB,IAAI;CACzC,OAAO,WAAW,8BAA8B,QAAQ,GAAG;AAC7D;;;;;;AAOA,SAAgB,qBAAqB,MAA8C;CACjF,OAAO,UAAU,KAAK,IAAI,IAAI,WAAW,iBAAiB,KAAK,IAAI,IAAI,UAAU,KAAA;AACnF"}
|