@stillwind/analysis 0.11.0 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +19 -0
- package/dist/index.js +1 -1
- package/dist/node.d.ts +107 -16
- package/dist/node.js +109 -37
- package/dist/node.js.map +1 -1
- package/dist/{reports-DvHppcFa.js → reports-Bu0OQg-C.js} +3 -2
- package/dist/reports-Bu0OQg-C.js.map +1 -0
- package/dist/{rewrite-Bdo2ssmD.js → rewrite-daiEBUgj.js} +94 -16
- package/dist/rewrite-daiEBUgj.js.map +1 -0
- package/dist/worker.js +228 -2
- package/dist/worker.js.map +1 -1
- package/package.json +4 -4
- package/dist/reports-DvHppcFa.js.map +0 -1
- package/dist/rewrite-Bdo2ssmD.js.map +0 -1
package/dist/worker.js
CHANGED
|
@@ -1,6 +1,183 @@
|
|
|
1
|
-
import { n as SourceRewriter, t as RewriteFailure } from "./rewrite-
|
|
1
|
+
import { n as SourceRewriter, t as RewriteFailure } from "./rewrite-daiEBUgj.js";
|
|
2
|
+
import { resolveLintConfig } from "@stillwind/config";
|
|
3
|
+
import path from "node:path";
|
|
2
4
|
import process from "node:process";
|
|
3
5
|
import { AnalysisWorkspace } from "@stillwind/host";
|
|
6
|
+
// src/hooks.ts
|
|
7
|
+
/**
|
|
8
|
+
* Tests whether any project in the workspace declares at least one hook.
|
|
9
|
+
*
|
|
10
|
+
* @param projects - Opened workspace projects.
|
|
11
|
+
* @returns True when at least one project has a configured hook.
|
|
12
|
+
*/
|
|
13
|
+
function hasActiveHooks(projects) {
|
|
14
|
+
return projects.some((project) => (project.config.hooks?.length ?? 0) > 0);
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Manages per-project hook contexts and `setup` / `teardown` lifetimes for one command run.
|
|
18
|
+
*/
|
|
19
|
+
var ProjectHookSession = class ProjectHookSession {
|
|
20
|
+
#contexts;
|
|
21
|
+
#started = [];
|
|
22
|
+
constructor(contexts) {
|
|
23
|
+
this.#contexts = contexts;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Creates contexts for all projects and runs `setup` in project and array order.
|
|
27
|
+
* If a `setup` callback throws, earlier initialized hooks are torn down before rethrowing.
|
|
28
|
+
*
|
|
29
|
+
* @param projects - Opened workspace projects.
|
|
30
|
+
* @param command - Invoking CLI command.
|
|
31
|
+
* @param mode - Write or check mode.
|
|
32
|
+
* @returns An open session whose `close()` must be awaited in a `finally` block.
|
|
33
|
+
* @throws If any hook's `setup` callback throws.
|
|
34
|
+
*/
|
|
35
|
+
static async open(projects, command, mode) {
|
|
36
|
+
const controller = new AbortController();
|
|
37
|
+
const contexts = projects.map((project) => ({
|
|
38
|
+
root: project.analysis.host.root,
|
|
39
|
+
...project.config.name !== void 0 ? { project: project.config.name } : {},
|
|
40
|
+
command,
|
|
41
|
+
mode,
|
|
42
|
+
signal: controller.signal
|
|
43
|
+
}));
|
|
44
|
+
const session = new ProjectHookSession(contexts);
|
|
45
|
+
try {
|
|
46
|
+
for (const [index, project] of projects.entries()) {
|
|
47
|
+
const context = contexts[index];
|
|
48
|
+
for (const hook of project.config.hooks ?? []) {
|
|
49
|
+
if (hook.setup) try {
|
|
50
|
+
await hook.setup(context);
|
|
51
|
+
} catch (error) {
|
|
52
|
+
throw new Error(`Hook "${hook.name}" setup failed: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
53
|
+
}
|
|
54
|
+
session.#started.push({
|
|
55
|
+
hook,
|
|
56
|
+
context
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return session;
|
|
61
|
+
} catch (error) {
|
|
62
|
+
await session.close().catch(() => void 0);
|
|
63
|
+
throw error;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Returns the immutable hook context for a project index.
|
|
68
|
+
*
|
|
69
|
+
* @param projectIndex - Zero-based project index in the workspace.
|
|
70
|
+
* @returns The project's hook context.
|
|
71
|
+
*/
|
|
72
|
+
context(projectIndex) {
|
|
73
|
+
return this.#contexts[projectIndex];
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Runs `teardown` in reverse initialization order for all hooks whose `setup` succeeded.
|
|
77
|
+
*
|
|
78
|
+
* @throws The first teardown error after attempting to tear down every remaining hook.
|
|
79
|
+
*/
|
|
80
|
+
async close() {
|
|
81
|
+
let firstError;
|
|
82
|
+
for (let index = this.#started.length - 1; index >= 0; index -= 1) {
|
|
83
|
+
const { hook, context } = this.#started[index];
|
|
84
|
+
if (!hook.teardown) continue;
|
|
85
|
+
try {
|
|
86
|
+
await hook.teardown(context);
|
|
87
|
+
} catch (error) {
|
|
88
|
+
firstError ??= new Error(`Hook "${hook.name}" teardown failed: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
this.#started.length = 0;
|
|
92
|
+
if (firstError !== void 0) throw firstError;
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
/**
|
|
96
|
+
* Tests whether two hook arrays contain the exact same hook object references in the same order.
|
|
97
|
+
*/
|
|
98
|
+
function sameHookList(a, b) {
|
|
99
|
+
return a.length === b.length && a.every((hook, index) => hook === b[index]);
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Runs one project's format hook pipeline over a single buffer.
|
|
103
|
+
*/
|
|
104
|
+
async function runProjectFormatHooks(hooks, file, initialCode, original, context) {
|
|
105
|
+
let code = initialCode;
|
|
106
|
+
for (const hook of hooks) {
|
|
107
|
+
let next;
|
|
108
|
+
try {
|
|
109
|
+
next = await hook.format({
|
|
110
|
+
path: file,
|
|
111
|
+
code,
|
|
112
|
+
original,
|
|
113
|
+
changed: code !== original
|
|
114
|
+
}, context);
|
|
115
|
+
} catch (error) {
|
|
116
|
+
throw new Error(`Hook "${hook.name}" failed for ${file}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
117
|
+
}
|
|
118
|
+
if (typeof next === "string") code = next;
|
|
119
|
+
else if (next !== void 0) throw new Error(`Hook "${hook.name}" format must return a string or undefined`);
|
|
120
|
+
}
|
|
121
|
+
return code;
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Applies project `format` hooks in memory to surviving rewrite outputs.
|
|
125
|
+
*
|
|
126
|
+
* When a file belongs to multiple projects:
|
|
127
|
+
* - If every owning project has the exact same format hook list (by object identity), the pipeline
|
|
128
|
+
* runs once.
|
|
129
|
+
* - Otherwise, each owning project runs its own pipeline and conflicting results fail that file.
|
|
130
|
+
*
|
|
131
|
+
* @param projects - Opened workspace projects.
|
|
132
|
+
* @param batch - Rewrite outputs and existing failures.
|
|
133
|
+
* @param originals - Original file text read from disk, keyed by absolute file path.
|
|
134
|
+
* @param session - Open hook session supplying per-project contexts.
|
|
135
|
+
* @returns Updated outputs, combined failures, and whether any output buffer changed.
|
|
136
|
+
*/
|
|
137
|
+
async function applyFormatHooks(projects, batch, originals, session) {
|
|
138
|
+
const outputs = [];
|
|
139
|
+
const failures = [...batch.failures];
|
|
140
|
+
let changed = false;
|
|
141
|
+
for (const output of batch.outputs) {
|
|
142
|
+
const pipelines = [...new Set(output.results.map((entry) => entry.project))].map((projectIndex) => ({
|
|
143
|
+
projectIndex,
|
|
144
|
+
hooks: (projects[projectIndex]?.config.hooks ?? []).filter((hook) => typeof hook.format === "function")
|
|
145
|
+
}));
|
|
146
|
+
if (!pipelines.some((entry) => entry.hooks.length > 0)) {
|
|
147
|
+
outputs.push(output);
|
|
148
|
+
continue;
|
|
149
|
+
}
|
|
150
|
+
const original = originals.get(output.file) ?? output.code;
|
|
151
|
+
try {
|
|
152
|
+
let nextCode;
|
|
153
|
+
const first = pipelines[0];
|
|
154
|
+
if (pipelines.every((entry) => sameHookList(entry.hooks, first.hooks))) nextCode = await runProjectFormatHooks(first.hooks, output.file, output.code, original, session.context(first.projectIndex));
|
|
155
|
+
else {
|
|
156
|
+
const candidates = [];
|
|
157
|
+
for (const entry of pipelines) candidates.push(entry.hooks.length ? await runProjectFormatHooks(entry.hooks, output.file, output.code, original, session.context(entry.projectIndex)) : output.code);
|
|
158
|
+
nextCode = candidates[0];
|
|
159
|
+
if (candidates.some((candidate) => candidate !== nextCode)) throw new Error(`Conflicting project format hooks for ${output.file}`);
|
|
160
|
+
}
|
|
161
|
+
if (nextCode !== output.code) changed = true;
|
|
162
|
+
outputs.push({
|
|
163
|
+
...output,
|
|
164
|
+
code: nextCode,
|
|
165
|
+
edits: nextCode === output.code ? output.edits : []
|
|
166
|
+
});
|
|
167
|
+
} catch (error) {
|
|
168
|
+
failures.push({
|
|
169
|
+
file: output.file,
|
|
170
|
+
message: error instanceof Error ? error.message : String(error),
|
|
171
|
+
results: output.results
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
return {
|
|
176
|
+
outputs,
|
|
177
|
+
failures,
|
|
178
|
+
changed
|
|
179
|
+
};
|
|
180
|
+
}
|
|
4
181
|
// src/worker.ts
|
|
5
182
|
let workspace;
|
|
6
183
|
let rewriter;
|
|
@@ -52,11 +229,40 @@ async function handle(request) {
|
|
|
52
229
|
const files = await Promise.all(workspace.projects.map((project) => workspace.targets(project, request.patterns ? [...request.patterns] : void 0, { stylesheets: request.stylesheets })));
|
|
53
230
|
return [...new Set(files.flat())].sort();
|
|
54
231
|
}
|
|
55
|
-
case "rewrite": return rewriter
|
|
232
|
+
case "rewrite": return runRewriteWithHooks(workspace, rewriter, request.inputs, request.operation, request.hooks);
|
|
56
233
|
case "lint": return workspace.lint(request.patterns ? [...request.patterns] : void 0);
|
|
57
234
|
case "analyze": return workspace.analyze(request.file);
|
|
58
235
|
case "prepare": return workspace.prepare(request.files);
|
|
59
236
|
case "query": return workspace.query(request.file, request.request);
|
|
237
|
+
case "info": {
|
|
238
|
+
const projects = [];
|
|
239
|
+
for (const [index, project] of workspace.projects.entries()) {
|
|
240
|
+
const matched = await workspace.targets(project);
|
|
241
|
+
const resolved = resolveLintConfig(project.config.lint).rules;
|
|
242
|
+
const lint = {};
|
|
243
|
+
for (const rule of Object.keys(resolved).sort()) {
|
|
244
|
+
const setting = resolved[rule];
|
|
245
|
+
if (typeof setting === "string") {
|
|
246
|
+
if (setting !== "off") lint[rule] = setting;
|
|
247
|
+
} else if (setting.severity !== "off") lint[rule] = setting;
|
|
248
|
+
}
|
|
249
|
+
projects.push({
|
|
250
|
+
project: index,
|
|
251
|
+
...project.config.name ? { name: project.config.name } : {},
|
|
252
|
+
root: project.analysis.host.root,
|
|
253
|
+
css: path.resolve(project.analysis.host.root, project.config.css),
|
|
254
|
+
files: [...project.config.files],
|
|
255
|
+
exclude: [...project.config.exclude ?? []],
|
|
256
|
+
matchedFiles: matched.length,
|
|
257
|
+
plugins: (project.config.plugins ?? []).map((plugin) => plugin.name),
|
|
258
|
+
hooks: (project.config.hooks ?? []).map((hook) => hook.name),
|
|
259
|
+
sort: project.config.sort !== false,
|
|
260
|
+
typeFacts: project.config.typeFacts !== false,
|
|
261
|
+
lint
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
return projects;
|
|
265
|
+
}
|
|
60
266
|
case "designSystem": return workspace.designSystem(request.request);
|
|
61
267
|
case "update":
|
|
62
268
|
workspace.update(request.file, request.source, request.version);
|
|
@@ -75,6 +281,26 @@ async function handle(request) {
|
|
|
75
281
|
return;
|
|
76
282
|
}
|
|
77
283
|
}
|
|
284
|
+
/**
|
|
285
|
+
* Runs Stillwind rewriting followed by configured project `format` hooks for CLI `fmt` and `check`
|
|
286
|
+
* commands.
|
|
287
|
+
*/
|
|
288
|
+
async function runRewriteWithHooks(currentWorkspace, currentRewriter, inputs, operation, hooks) {
|
|
289
|
+
const batch = await currentRewriter.rewrite(inputs, operation);
|
|
290
|
+
if (!hooks || !hasActiveHooks(currentWorkspace.projects)) return batch;
|
|
291
|
+
const originals = new Map(inputs.map((input) => [input.file, input.source]));
|
|
292
|
+
const session = await ProjectHookSession.open(currentWorkspace.projects, hooks.command, hooks.mode);
|
|
293
|
+
try {
|
|
294
|
+
const formatted = await applyFormatHooks(currentWorkspace.projects, batch, originals, session);
|
|
295
|
+
if (hooks.mode === "write" && hooks.command === "check" && formatted.changed && formatted.outputs.length) await currentRewriter.reanalyze(inputs, formatted.outputs);
|
|
296
|
+
return {
|
|
297
|
+
outputs: formatted.outputs,
|
|
298
|
+
failures: formatted.failures
|
|
299
|
+
};
|
|
300
|
+
} finally {
|
|
301
|
+
await session.close();
|
|
302
|
+
}
|
|
303
|
+
}
|
|
78
304
|
export {};
|
|
79
305
|
|
|
80
306
|
//# sourceMappingURL=worker.js.map
|
package/dist/worker.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worker.js","names":[],"sources":["../src/worker.ts"],"sourcesContent":["import process from \"node:process\";\n\nimport { AnalysisWorkspace } from \"@stillwind/host\";\n\nimport { RewriteFailure, SourceRewriter } from \"./rewrite.ts\";\nimport type { WorkerRequest } from \"./worker-client.ts\";\n\nlet workspace: AnalysisWorkspace | undefined;\nlet rewriter: SourceRewriter | undefined;\n\nprocess.on(\n \"message\",\n (message: {\n /** Sequence number copied into the IPC reply. */\n id: number;\n /** Operation payload sent by AnalysisWorker. Callers serialize workspace replacement and rewrites. */\n request: WorkerRequest;\n }) => {\n void handle(message.request).then(\n (value) => {\n process.send?.({ id: message.id, value }, () => {\n if (message.request.method === \"close\") {\n process.disconnect?.();\n }\n });\n },\n (error: unknown) => {\n process.send?.({\n id: message.id,\n error: {\n message: error instanceof Error ? error.message : String(error),\n results: error instanceof RewriteFailure ? error.results : undefined,\n },\n });\n },\n );\n },\n);\n\nprocess.on(\"disconnect\", () => {\n void Promise.resolve(workspace?.close()).finally(() => {\n process.exit();\n });\n});\n\n/**\n * Dispatches one IPC operation against the child-owned workspace and rewriter.\n *\n * @param request - Operation payload. Open must complete before other operations except close.\n * @returns The operation result, including a boolean for refresh, or undefined for state changes.\n * The targets operation returns sorted, distinct paths.\n * @throws If no workspace is open or the selected workspace operation fails.\n */\nasync function handle(request: WorkerRequest): Promise<unknown> {\n if (request.method === \"open\") {\n await workspace?.close();\n workspace = undefined;\n workspace = await AnalysisWorkspace.open(request.config);\n rewriter = new SourceRewriter(workspace);\n return undefined;\n }\n\n if (!workspace) {\n if (request.method === \"close\") {\n return undefined;\n }\n throw new Error(\"Stillwind workspace has not been opened\");\n }\n\n switch (request.method) {\n case \"targets\": {\n const files = await Promise.all(\n workspace.projects.map((project) =>\n workspace!.targets(project, request.patterns ? [...request.patterns] : undefined, {\n stylesheets: request.stylesheets,\n }),\n ),\n );\n return [...new Set(files.flat())].sort();\n }\n\n case \"rewrite\":\n return rewriter!.rewrite(request.inputs, request.operation);\n\n case \"lint\":\n return workspace.lint(request.patterns ? [...request.patterns] : undefined);\n\n case \"analyze\":\n return workspace.analyze(request.file);\n\n case \"prepare\":\n return workspace.prepare(request.files);\n\n case \"query\":\n return workspace.query(request.file, request.request);\n\n case \"designSystem\":\n return workspace.designSystem(request.request);\n\n case \"update\":\n workspace.update(request.file, request.source, request.version);\n return undefined;\n\n case \"closeDocument\":\n workspace.closeDocument(request.file);\n return undefined;\n\n case \"invalidate\":\n workspace.invalidate();\n return undefined;\n\n case \"refresh\":\n return workspace.refresh(request.files);\n\n case \"affects\":\n return workspace.affects(request.files);\n\n case \"close\":\n await workspace.close();\n workspace = undefined;\n return undefined;\n }\n}\n"],"mappings":";;;;AAOA,IAAI;AACJ,IAAI;AAEJ,QAAQ,GACN,YACC,YAKK;CACJ,OAAY,QAAQ,OAAO,CAAC,CAAC,MAC1B,UAAU;EACT,QAAQ,OAAO;GAAE,IAAI,QAAQ;GAAI;EAAM,SAAS;GAC9C,IAAI,QAAQ,QAAQ,WAAW,SAC7B,QAAQ,aAAa;EAEzB,CAAC;CACH,IACC,UAAmB;EAClB,QAAQ,OAAO;GACb,IAAI,QAAQ;GACZ,OAAO;IACL,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;IAC9D,SAAS,iBAAiB,iBAAiB,MA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,KAAK;GACH,UAAU,cAAc,QAAQ,IAAI;GACpC;EAEF,KAAK;GACH,UAAU,WAAW;GACrB;EAEF,KAAK,WACH,OAAO,UAAU,QAAQ,QAAQ,KAAK;EAExC,KAAK,WACH,OAAO,UAAU,QAAQ,QAAQ,KAAK;EAExC,KAAK;GACH,MAAM,UAAU,MAAM;GACtB,YAAY,KAAA;GACZ;CACJ;AACF"}
|
|
1
|
+
{"version":3,"file":"worker.js","names":[],"sources":["../src/hooks.ts","../src/worker.ts"],"sourcesContent":["import type { AnalysisHook, HookCommand, HookContext, HookMode } from \"@stillwind/config\";\nimport type { WorkspaceProject } from \"@stillwind/host\";\n\nimport type { RewriteBatchResult, RewriteFileFailure, RewriteResult } from \"./rewrite.ts\";\n\n/** Options selecting which project hooks run for a worker rewrite operation. */\nexport interface HookRunOptions {\n /** CLI command invoking the hooks. */\n command: HookCommand;\n /** Whether modified buffers will be written to disk or only checked. */\n mode: HookMode;\n}\n\n/**\n * Tests whether any project in the workspace declares at least one hook.\n *\n * @param projects - Opened workspace projects.\n * @returns True when at least one project has a configured hook.\n */\nexport function hasActiveHooks(projects: readonly WorkspaceProject[]): boolean {\n return projects.some((project) => (project.config.hooks?.length ?? 0) > 0);\n}\n\n/**\n * Manages per-project hook contexts and `setup` / `teardown` lifetimes for one command run.\n */\nexport class ProjectHookSession {\n readonly #contexts: readonly HookContext[];\n readonly #started: { hook: AnalysisHook; context: HookContext }[] = [];\n\n private constructor(contexts: readonly HookContext[]) {\n this.#contexts = contexts;\n }\n\n /**\n * Creates contexts for all projects and runs `setup` in project and array order.\n * If a `setup` callback throws, earlier initialized hooks are torn down before rethrowing.\n *\n * @param projects - Opened workspace projects.\n * @param command - Invoking CLI command.\n * @param mode - Write or check mode.\n * @returns An open session whose `close()` must be awaited in a `finally` block.\n * @throws If any hook's `setup` callback throws.\n */\n static async open(\n projects: readonly WorkspaceProject[],\n command: HookCommand,\n mode: HookMode,\n ): Promise<ProjectHookSession> {\n const controller = new AbortController();\n const contexts: HookContext[] = projects.map((project) => ({\n root: project.analysis.host.root,\n ...(project.config.name !== undefined ? { project: project.config.name } : {}),\n command,\n mode,\n signal: controller.signal,\n }));\n const session = new ProjectHookSession(contexts);\n try {\n for (const [index, project] of projects.entries()) {\n const context = contexts[index];\n for (const hook of project.config.hooks ?? []) {\n if (hook.setup) {\n try {\n await hook.setup(context);\n } catch (error) {\n throw new Error(\n `Hook \"${hook.name}\" setup failed: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n }\n session.#started.push({ hook, context });\n }\n }\n return session;\n } catch (error) {\n await session.close().catch(() => undefined);\n throw error;\n }\n }\n\n /**\n * Returns the immutable hook context for a project index.\n *\n * @param projectIndex - Zero-based project index in the workspace.\n * @returns The project's hook context.\n */\n context(projectIndex: number): HookContext {\n return this.#contexts[projectIndex];\n }\n\n /**\n * Runs `teardown` in reverse initialization order for all hooks whose `setup` succeeded.\n *\n * @throws The first teardown error after attempting to tear down every remaining hook.\n */\n async close(): Promise<void> {\n let firstError: unknown;\n for (let index = this.#started.length - 1; index >= 0; index -= 1) {\n const { hook, context } = this.#started[index];\n if (!hook.teardown) {\n continue;\n }\n try {\n await hook.teardown(context);\n } catch (error) {\n firstError ??= new Error(\n `Hook \"${hook.name}\" teardown failed: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n }\n this.#started.length = 0;\n if (firstError !== undefined) {\n throw firstError;\n }\n }\n}\n\n/**\n * Tests whether two hook arrays contain the exact same hook object references in the same order.\n */\nfunction sameHookList(a: readonly AnalysisHook[], b: readonly AnalysisHook[]): boolean {\n return a.length === b.length && a.every((hook, index) => hook === b[index]);\n}\n\n/**\n * Runs one project's format hook pipeline over a single buffer.\n */\nasync function runProjectFormatHooks(\n hooks: readonly AnalysisHook[],\n file: string,\n initialCode: string,\n original: string,\n context: HookContext,\n): Promise<string> {\n let code = initialCode;\n for (const hook of hooks) {\n let next: unknown;\n try {\n next = await hook.format!(\n {\n path: file,\n code,\n original,\n changed: code !== original,\n },\n context,\n );\n } catch (error) {\n throw new Error(\n `Hook \"${hook.name}\" failed for ${file}: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n if (typeof next === \"string\") {\n code = next;\n } else if (next !== undefined) {\n throw new Error(`Hook \"${hook.name}\" format must return a string or undefined`);\n }\n }\n return code;\n}\n\n/**\n * Applies project `format` hooks in memory to surviving rewrite outputs.\n *\n * When a file belongs to multiple projects:\n * - If every owning project has the exact same format hook list (by object identity), the pipeline\n * runs once.\n * - Otherwise, each owning project runs its own pipeline and conflicting results fail that file.\n *\n * @param projects - Opened workspace projects.\n * @param batch - Rewrite outputs and existing failures.\n * @param originals - Original file text read from disk, keyed by absolute file path.\n * @param session - Open hook session supplying per-project contexts.\n * @returns Updated outputs, combined failures, and whether any output buffer changed.\n */\nexport async function applyFormatHooks(\n projects: readonly WorkspaceProject[],\n batch: RewriteBatchResult,\n originals: ReadonlyMap<string, string>,\n session: ProjectHookSession,\n): Promise<{\n outputs: RewriteResult[];\n failures: RewriteFileFailure[];\n changed: boolean;\n}> {\n const outputs: RewriteResult[] = [];\n const failures: RewriteFileFailure[] = [...batch.failures];\n let changed = false;\n\n for (const output of batch.outputs) {\n const projectIndices = [...new Set(output.results.map((entry) => entry.project))];\n const pipelines = projectIndices.map((projectIndex) => ({\n projectIndex,\n hooks: (projects[projectIndex]?.config.hooks ?? []).filter(\n (hook) => typeof hook.format === \"function\",\n ),\n }));\n if (!pipelines.some((entry) => entry.hooks.length > 0)) {\n outputs.push(output);\n continue;\n }\n\n const original = originals.get(output.file) ?? output.code;\n try {\n let nextCode: string;\n const first = pipelines[0];\n if (pipelines.every((entry) => sameHookList(entry.hooks, first.hooks))) {\n nextCode = await runProjectFormatHooks(\n first.hooks,\n output.file,\n output.code,\n original,\n session.context(first.projectIndex),\n );\n } else {\n const candidates: string[] = [];\n for (const entry of pipelines) {\n candidates.push(\n entry.hooks.length\n ? await runProjectFormatHooks(\n entry.hooks,\n output.file,\n output.code,\n original,\n session.context(entry.projectIndex),\n )\n : output.code,\n );\n }\n nextCode = candidates[0];\n if (candidates.some((candidate) => candidate !== nextCode)) {\n throw new Error(`Conflicting project format hooks for ${output.file}`);\n }\n }\n if (nextCode !== output.code) {\n changed = true;\n }\n outputs.push({\n ...output,\n code: nextCode,\n edits: nextCode === output.code ? output.edits : [],\n });\n } catch (error) {\n failures.push({\n file: output.file,\n message: error instanceof Error ? error.message : String(error),\n results: output.results,\n });\n }\n }\n\n return { outputs, failures, changed };\n}\n","import path from \"node:path\";\nimport process from \"node:process\";\n\nimport { resolveLintConfig } from \"@stillwind/config\";\nimport { AnalysisWorkspace } from \"@stillwind/host\";\n\nimport {\n applyFormatHooks,\n hasActiveHooks,\n ProjectHookSession,\n type HookRunOptions,\n} from \"./hooks.ts\";\nimport type { ActiveLintRule, ProjectInfo } from \"./info.ts\";\nimport {\n RewriteFailure,\n SourceRewriter,\n type RewriteBatchResult,\n type RewriteInput,\n type RewriteOperation,\n} from \"./rewrite.ts\";\nimport type { WorkerRequest } from \"./worker-client.ts\";\n\nlet workspace: AnalysisWorkspace | undefined;\nlet rewriter: SourceRewriter | undefined;\n\nprocess.on(\n \"message\",\n (message: {\n /** Sequence number copied into the IPC reply. */\n id: number;\n /** Operation payload sent by AnalysisWorker. Callers serialize workspace replacement and rewrites. */\n request: WorkerRequest;\n }) => {\n void handle(message.request).then(\n (value) => {\n process.send?.({ id: message.id, value }, () => {\n if (message.request.method === \"close\") {\n process.disconnect?.();\n }\n });\n },\n (error: unknown) => {\n process.send?.({\n id: message.id,\n error: {\n message: error instanceof Error ? error.message : String(error),\n results: error instanceof RewriteFailure ? error.results : undefined,\n },\n });\n },\n );\n },\n);\n\nprocess.on(\"disconnect\", () => {\n void Promise.resolve(workspace?.close()).finally(() => {\n process.exit();\n });\n});\n\n/**\n * Dispatches one IPC operation against the child-owned workspace and rewriter.\n *\n * @param request - Operation payload. Open must complete before other operations except close.\n * @returns The operation result, including a boolean for refresh, or undefined for state changes.\n * The targets operation returns sorted, distinct paths.\n * @throws If no workspace is open or the selected workspace operation fails.\n */\nasync function handle(request: WorkerRequest): Promise<unknown> {\n if (request.method === \"open\") {\n await workspace?.close();\n workspace = undefined;\n workspace = await AnalysisWorkspace.open(request.config);\n rewriter = new SourceRewriter(workspace);\n return undefined;\n }\n\n if (!workspace) {\n if (request.method === \"close\") {\n return undefined;\n }\n throw new Error(\"Stillwind workspace has not been opened\");\n }\n\n switch (request.method) {\n case \"targets\": {\n const files = await Promise.all(\n workspace.projects.map((project) =>\n workspace!.targets(project, request.patterns ? [...request.patterns] : undefined, {\n stylesheets: request.stylesheets,\n }),\n ),\n );\n return [...new Set(files.flat())].sort();\n }\n\n case \"rewrite\":\n return runRewriteWithHooks(\n workspace,\n rewriter!,\n request.inputs,\n request.operation,\n request.hooks,\n );\n\n case \"lint\":\n return workspace.lint(request.patterns ? [...request.patterns] : undefined);\n\n case \"analyze\":\n return workspace.analyze(request.file);\n\n case \"prepare\":\n return workspace.prepare(request.files);\n\n case \"query\":\n return workspace.query(request.file, request.request);\n\n case \"info\": {\n const projects: ProjectInfo[] = [];\n for (const [index, project] of workspace.projects.entries()) {\n const matched = await workspace.targets(project);\n const resolved = resolveLintConfig(project.config.lint).rules;\n const lint: Record<string, ActiveLintRule> = {};\n for (const rule of Object.keys(resolved).sort()) {\n const setting = resolved[rule as keyof typeof resolved];\n if (typeof setting === \"string\") {\n if (setting !== \"off\") {\n lint[rule] = setting;\n }\n } else if (setting.severity !== \"off\") {\n lint[rule] = setting as ActiveLintRule;\n }\n }\n projects.push({\n project: index,\n ...(project.config.name ? { name: project.config.name } : {}),\n root: project.analysis.host.root,\n css: path.resolve(project.analysis.host.root, project.config.css),\n files: [...project.config.files],\n exclude: [...(project.config.exclude ?? [])],\n matchedFiles: matched.length,\n plugins: (project.config.plugins ?? []).map((plugin) => plugin.name),\n hooks: (project.config.hooks ?? []).map((hook) => hook.name),\n sort: project.config.sort !== false,\n typeFacts: project.config.typeFacts !== false,\n lint,\n });\n }\n return projects;\n }\n\n case \"designSystem\":\n return workspace.designSystem(request.request);\n\n case \"update\":\n workspace.update(request.file, request.source, request.version);\n return undefined;\n\n case \"closeDocument\":\n workspace.closeDocument(request.file);\n return undefined;\n\n case \"invalidate\":\n workspace.invalidate();\n return undefined;\n\n case \"refresh\":\n return workspace.refresh(request.files);\n\n case \"affects\":\n return workspace.affects(request.files);\n\n case \"close\":\n await workspace.close();\n workspace = undefined;\n return undefined;\n }\n}\n\n/**\n * Runs Stillwind rewriting followed by configured project `format` hooks for CLI `fmt` and `check`\n * commands.\n */\nasync function runRewriteWithHooks(\n currentWorkspace: AnalysisWorkspace,\n currentRewriter: SourceRewriter,\n inputs: readonly RewriteInput[],\n operation: RewriteOperation,\n hooks: HookRunOptions | undefined,\n): Promise<RewriteBatchResult> {\n const batch = await currentRewriter.rewrite(inputs, operation);\n if (!hooks || !hasActiveHooks(currentWorkspace.projects)) {\n return batch;\n }\n\n const originals = new Map(inputs.map((input) => [input.file, input.source]));\n const session = await ProjectHookSession.open(\n currentWorkspace.projects,\n hooks.command,\n hooks.mode,\n );\n try {\n const formatted = await applyFormatHooks(currentWorkspace.projects, batch, originals, session);\n if (\n hooks.mode === \"write\" &&\n hooks.command === \"check\" &&\n formatted.changed &&\n formatted.outputs.length\n ) {\n await currentRewriter.reanalyze(inputs, formatted.outputs);\n }\n return {\n outputs: formatted.outputs,\n failures: formatted.failures,\n };\n } finally {\n await session.close();\n }\n}\n"],"mappings":";;;;;;;;;;;;AAmBA,SAAgB,eAAe,UAAgD;CAC7E,OAAO,SAAS,MAAM,aAAa,QAAQ,OAAO,OAAO,UAAU,KAAK,CAAC;AAC3E;;;;AAKA,IAAa,qBAAb,MAAa,mBAAmB;CAC9B;CACA,WAAoE,CAAC;CAErE,YAAoB,UAAkC;EACpD,KAAK,YAAY;CACnB;;;;;;;;;;;CAYA,aAAa,KACX,UACA,SACA,MAC6B;EAC7B,MAAM,aAAa,IAAI,gBAAgB;EAC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BACb,kBACA,iBACA,QACA,WACA,OAC6B;CAC7B,MAAM,QAAQ,MAAM,gBAAgB,QAAQ,QAAQ,SAAS;CAC7D,IAAI,CAAC,SAAS,CAAC,eAAe,iBAAiB,QAAQ,GACrD,OAAO;CAGT,MAAM,YAAY,IAAI,IAAI,OAAO,KAAK,UAAU,CAAC,MAAM,MAAM,MAAM,MAAM,CAAC,CAAC;CAC3E,MAAM,UAAU,MAAM,mBAAmB,KACvC,iBAAiB,UACjB,MAAM,SACN,MAAM,IACR;CACA,IAAI;EACF,MAAM,YAAY,MAAM,iBAAiB,iBAAiB,UAAU,OAAO,WAAW,OAAO;EAC7F,IACE,MAAM,SAAS,WACf,MAAM,YAAY,WAClB,UAAU,WACV,UAAU,QAAQ,QAElB,MAAM,gBAAgB,UAAU,QAAQ,UAAU,OAAO;EAE3D,OAAO;GACL,SAAS,UAAU;GACnB,UAAU,UAAU;EACtB;CACF,UAAU;EACR,MAAM,QAAQ,MAAM;CACtB;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@stillwind/analysis",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.12.0",
|
|
4
4
|
"description": "Analysis services for the Stillwind CLI, language server, and editors",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"stillwind"
|
|
@@ -45,9 +45,9 @@
|
|
|
45
45
|
"access": "public"
|
|
46
46
|
},
|
|
47
47
|
"dependencies": {
|
|
48
|
-
"@stillwind/config": "0.
|
|
49
|
-
"@stillwind/host": "0.
|
|
50
|
-
"@stillwind/native": "0.
|
|
48
|
+
"@stillwind/config": "0.12.0",
|
|
49
|
+
"@stillwind/host": "0.12.0",
|
|
50
|
+
"@stillwind/native": "0.12.0",
|
|
51
51
|
"minimatch": "^11.0.5",
|
|
52
52
|
"pathe": "^2.0.3"
|
|
53
53
|
},
|
|
@@ -1 +0,0 @@
|
|
|
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 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"rewrite-Bdo2ssmD.js","names":[],"sources":["../src/rewrite.ts"],"sourcesContent":["import type { AnalysisWorkspace, EditorEdit, WorkspaceResult } from \"@stillwind/host\";\nimport { fingerprint } from \"@stillwind/native\";\n\n/** Failed rewrite planning with the analysis results that prevented writing. */\nexport class RewriteFailure extends Error {\n constructor(\n message: string,\n readonly results: WorkspaceResult[],\n ) {\n super(message);\n this.name = \"RewriteFailure\";\n }\n}\n\n/** Original buffer and ranges excluded by a formatter adapter. Paths are absolute. */\nexport interface RewriteInput {\n /** Absolute target path used for workspace membership and dependency resolution. */\n file: string;\n /** Complete original text against which edits are measured. */\n source: string;\n /** Half-open UTF-16 ranges in source. Only sorting accepts protected ranges. */\n protectedRanges?: readonly {\n /** Inclusive original UTF-16 offset. */\n start: number;\n /** Exclusive original UTF-16 offset. */\n end: number;\n }[];\n}\n\n/** Replacement text and independent project findings for one original buffer. */\nexport interface RewriteResult {\n /** Absolute path copied from the corresponding input. */\n file: string;\n /** Final text after sorting or converged fixes. */\n code: string;\n /** Sorting edits in the input buffer. Iterated lint fixes omit these edits. */\n edits: EditorEdit[];\n /** Findings for the analyzed input of the final pass, in project order. */\n results: WorkspaceResult[];\n}\n\n/** A target that could not be read, rewritten, or saved. */\nexport interface RewriteFileFailure {\n /** Absolute path of the failed target. */\n file: string;\n /** Reason that reading, planning, or saving this target failed. */\n message: string;\n /** Analysis findings captured before planning failed, when available. */\n results: WorkspaceResult[];\n}\n\n/** Independent target outcomes from a shared set of captured buffers. */\nexport interface RewriteBatchResult {\n /** Successful replacements in input order. */\n outputs: RewriteResult[];\n /** Failed targets in input order. */\n failures: RewriteFileFailure[];\n}\n\n/** Owns buffer versions while computing changes against one workspace. Calls must be serialized. */\nexport class SourceRewriter {\n /** Increasing version assigned to every buffer in each rewrite pass. */\n #version = 0;\n\n /**\n * Attaches rewriting to a workspace whose buffers the caller reserves for this rewriter.\n *\n * @param workspace - Open workspace. Serialize rewrite calls and avoid concurrent updates to input paths.\n * When prepare is available, the rewriter calls it after installing each pass's buffers.\n */\n constructor(\n private readonly workspace: Pick<\n AnalysisWorkspace,\n \"invalidate\" | \"update\" | \"analyze\" | \"query\" | \"closeDocument\"\n > &\n Partial<Pick<AnalysisWorkspace, \"prepare\">>,\n ) {}\n\n /**\n * Computes sorting or converged lint fixes without saving files. All input buffers are visible\n * to dependency analysis. After distinct paths are validated, captured\n * buffers are removed even when rewriting fails. Preparation runs once before each pass's per-file queries.\n *\n * @param inputs - Distinct absolute paths and complete text. Only sorting uses protected ranges.\n * @param operation - One sort pass or lint-fix passes until the text stops changing.\n * @returns Successful buffers and failures in input order. Failed buffers retain their original\n * text in subsequent passes. Fixes return no edits because their offsets span several passes.\n * @throws If paths repeat or workspace invalidation, preparation, buffer installation, or cleanup fails.\n */\n async rewrite(\n inputs: readonly RewriteInput[],\n operation: \"sort\" | \"fixes\",\n ): Promise<RewriteBatchResult> {\n if (new Set(inputs.map((input) => input.file)).size !== inputs.length) {\n throw new Error(\"Rewrite inputs must have distinct file paths\");\n }\n let buffers = inputs;\n const failures = new Map<string, RewriteFileFailure>();\n const originals = new Map(inputs.map((input) => [input.file, input.source]));\n const seen = new Map(inputs.map((input) => [input.file, new Set<string>()]));\n try {\n this.workspace.invalidate();\n for (;;) {\n const snapshot = JSON.stringify([\n buffers.map((input) => input.source),\n [...failures.keys()],\n ]);\n const version = ++this.#version;\n for (const input of buffers) {\n this.workspace.update(input.file, input.source, version);\n }\n await this.workspace.prepare?.(\n buffers.filter((input) => !failures.has(input.file)).map((input) => input.file),\n );\n const outputs: RewriteResult[] = [];\n let changed = false;\n for (const input of buffers) {\n if (failures.has(input.file)) {\n continue;\n }\n try {\n const output = await this.#rewriteBuffer(input, operation);\n if (operation === \"fixes\" && output.code !== input.source) {\n const history = seen.get(input.file)!;\n if (history.has(snapshot)) {\n throw new RewriteFailure(\"Stillwind fixes did not converge\", output.results);\n }\n if (history.size >= 10) {\n throw new RewriteFailure(\"Stillwind fixes exceeded ten passes\", output.results);\n }\n history.add(snapshot);\n changed = true;\n }\n outputs.push(output);\n } catch (error) {\n failures.set(input.file, {\n file: input.file,\n message: error instanceof Error ? error.message : String(error),\n results: error instanceof RewriteFailure ? error.results : [],\n });\n changed ||= input.source !== originals.get(input.file);\n }\n }\n if (operation === \"sort\" || !changed) {\n return {\n outputs: outputs.map((output) => ({\n ...output,\n edits: operation === \"sort\" ? output.edits : [],\n })),\n failures: inputs.flatMap((input) => {\n const failure = failures.get(input.file);\n return failure ? [failure] : [];\n }),\n };\n }\n const replacements = new Map(outputs.map((output) => [output.file, output.code]));\n buffers = inputs.map((input) => ({\n file: input.file,\n source: replacements.get(input.file) ?? input.source,\n }));\n }\n } finally {\n for (const input of inputs) {\n this.workspace.closeDocument(input.file);\n }\n }\n }\n\n /**\n * Analyzes one installed buffer and requires matching project answers to produce the same text.\n *\n * @param input - Buffer already installed in the workspace for the current pass.\n * @param operation - Sort or fixes query to apply to the original text of this pass.\n * @returns The first project's edits and all project findings, or unchanged text outside every scope.\n * @throws If analysis is incomplete, syntax is invalid, answers are missing or stale, or projects disagree.\n */\n async #rewriteBuffer(input: RewriteInput, operation: \"sort\" | \"fixes\"): Promise<RewriteResult> {\n const results = await this.workspace.analyze(input.file);\n if (results.some(({ result }) => result.status !== \"complete\")) {\n const reasons = results.flatMap(({ result }) =>\n result.status === \"complete\"\n ? []\n : [result.error ?? result.graph?.unverified[0]?.reason ?? result.status],\n );\n throw new RewriteFailure(\n `Incomplete analysis for ${input.file}: ${reasons.join(\"; \")}`,\n results,\n );\n }\n const syntaxErrors = results.flatMap(({ result }) =>\n result.reports.filter((report) => [\"SW10001\", \"SW10002\"].includes(report.code)),\n );\n if (syntaxErrors.length) {\n throw new RewriteFailure(\n `Cannot rewrite ${input.file}: ${syntaxErrors.map((report) => report.message).join(\"; \")}`,\n results,\n );\n }\n const answers = await this.workspace.query(\n input.file,\n operation === \"sort\"\n ? {\n kind: \"sort\",\n protectedRanges: input.protectedRanges,\n }\n : {\n kind: \"fixes\",\n },\n );\n if (answers.length !== results.length) {\n throw new Error(`Missing rewrite result for ${input.file}`);\n }\n const revision = fingerprint(input.source);\n const candidates = answers.map(({ result }) => {\n if (result.revision !== revision) {\n throw new Error(`Stale edits for ${input.file}`);\n }\n const edits = result.edits ?? [];\n return {\n code: applySourceEdits(input.source, edits),\n edits,\n };\n });\n const first = candidates[0] ?? {\n code: input.source,\n edits: [],\n };\n if (candidates.some((candidate) => candidate.code !== first.code)) {\n throw new Error(`Conflicting project rewrites for ${input.file}`);\n }\n return {\n file: input.file,\n ...first,\n results,\n };\n }\n}\n\n/**\n * Applies edits from the end of the original text after validating their ranges.\n *\n * @param source - Original text from which all edit offsets were measured.\n * @param edits - Half-open ranges with safe integer UTF-16 offsets, in any order. The array is unchanged.\n * @returns Text with every replacement applied.\n * @throws If a range is invalid, outside the source, or overlaps another range.\n */\nexport function applySourceEdits(source: string, edits: readonly EditorEdit[]): string {\n const ordered = [...edits].sort((a, b) => a.start - b.start || a.end - b.end);\n let end = 0;\n for (const edit of ordered) {\n if (\n !Number.isSafeInteger(edit.start) ||\n !Number.isSafeInteger(edit.end) ||\n edit.start < end ||\n edit.end < edit.start ||\n edit.end > source.length\n ) {\n throw new Error(\"Invalid or overlapping source edits\");\n }\n end = edit.end;\n }\n for (const edit of ordered.reverse()) {\n source = source.slice(0, edit.start) + edit.newText + source.slice(edit.end);\n }\n return source;\n}\n"],"mappings":";;;AAIA,IAAa,iBAAb,cAAoC,MAAM;CAG7B;CAFX,YACE,SACA,SACA;EACA,MAAM,OAAO;EAFJ,KAAA,UAAA;EAGT,KAAK,OAAO;CACd;AACF;;AAgDA,IAAa,iBAAb,MAA4B;CAWP;;CATnB,WAAW;;;;;;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