@stillwind/host 0.0.0-stage → 0.1.0-rc.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +13 -2
- package/dist/browser.d.ts +220 -0
- package/dist/browser.js +1066 -0
- package/dist/browser.js.map +1 -0
- package/dist/configuration-CnrzO-F3.js +405 -0
- package/dist/configuration-CnrzO-F3.js.map +1 -0
- package/dist/index-CprPvXxv.d.ts +844 -0
- package/dist/index.d.ts +1243 -0
- package/dist/index.js +2672 -0
- package/dist/index.js.map +1 -0
- package/dist/options-BrXyddsL.js +4770 -0
- package/dist/options-BrXyddsL.js.map +1 -0
- package/dist/plugin-DvCyhK1k.js +1410 -0
- package/dist/plugin-DvCyhK1k.js.map +1 -0
- package/dist/projection.d.ts +2 -0
- package/dist/projection.js +1 -0
- package/dist/resolution-BI5eZllL.d.ts +12 -0
- package/dist/resolution-C3cvLPzx.js +100 -0
- package/dist/resolution-C3cvLPzx.js.map +1 -0
- package/dist/resolution.d.ts +2 -0
- package/dist/resolution.js +1 -0
- package/package.json +77 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,2672 @@
|
|
|
1
|
+
import { A as prepareSourcePlugins, C as CompilationFailure, D as attachPlugins, E as TypeFactsError, O as compileWithPlugins, S as warnRejectedNames, T as fileSourceKind, _ as defaultPluginExport, a as pluginDirectory, b as analyzeModule, c as EditorSnapshot, d as withRequestedProbes, f as isStylesheet, g as PluginRuntime, h as loadEditorCssGraph, i as completePluginPaths, k as pluginLoader, l as CheckerSource, m as loadCssGraph, n as cssEntrypoint, o as queryPluginPaths, p as lintsStylesheet, r as StylesheetEditor, s as CompilationProject, t as compilerOptions, u as checkerId, v as cssBannerPrefix, w as cleanModuleId, x as compileModule, y as finalizeCss } from "./options-BrXyddsL.js";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import { NativeProjectSession, fingerprint } from "@stillwind/native";
|
|
4
|
+
import path, { isAbsolute, relative, resolve } from "node:path";
|
|
5
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
6
|
+
import { GenMapping, addSegment, setSourceContent, toEncodedMap } from "@jridgewell/gen-mapping";
|
|
7
|
+
import remapping from "@jridgewell/remapping";
|
|
8
|
+
import { TraceMap, decodedMappings, originalPositionFor, sourceContentFor } from "@jridgewell/trace-mapping";
|
|
9
|
+
import { createHash } from "node:crypto";
|
|
10
|
+
import { existsSync } from "node:fs";
|
|
11
|
+
import process from "node:process";
|
|
12
|
+
import { isCallExpression, isExportDeclaration, isExpression, isImportDeclaration, isSourceFile, isStringLiteral } from "typescript-7/unstable/ast/is";
|
|
13
|
+
import { API, SignatureKind, TypeFlags } from "typescript-7/unstable/sync";
|
|
14
|
+
import { captureProjectConfig } from "@stillwind/config";
|
|
15
|
+
import { readFile, readdir, stat } from "node:fs/promises";
|
|
16
|
+
import { evaluateModule, loadConfiguration, resolveProjectConfig } from "@stillwind/config/node";
|
|
17
|
+
import { ResolverFactory } from "oxc-resolver";
|
|
18
|
+
import { minimatch } from "minimatch";
|
|
19
|
+
import { glob } from "tinyglobby";
|
|
20
|
+
// src/compilation/filesystem.ts
|
|
21
|
+
/**
|
|
22
|
+
* Derives a compiler module identity relative to a filesystem root.
|
|
23
|
+
*
|
|
24
|
+
* @param root - Filesystem directory from which the identity is made relative.
|
|
25
|
+
* @param id - Filesystem path to identify. Callers remove resolver queries before using this
|
|
26
|
+
* helper.
|
|
27
|
+
* @returns A relative path with forward slashes. Paths outside the root retain `..` segments. This
|
|
28
|
+
* function does not enforce containment.
|
|
29
|
+
*/
|
|
30
|
+
function compilerModuleId(root, id) {
|
|
31
|
+
return relative(root, id).replaceAll("\\", "/");
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Infers parser metadata from a filesystem path and assigns compiler and checker identities.
|
|
35
|
+
*
|
|
36
|
+
* @param root - Project directory used for relative compiler identities.
|
|
37
|
+
* @param id - Absolute source path, optionally followed by a query or fragment suffix.
|
|
38
|
+
* @returns Metadata for the file after removing its query or fragment suffix.
|
|
39
|
+
*/
|
|
40
|
+
function fileModuleDescriptor(root, id) {
|
|
41
|
+
const file = cleanModuleId(id);
|
|
42
|
+
const { syntax, format } = fileSourceKind(file);
|
|
43
|
+
return {
|
|
44
|
+
moduleId: compilerModuleId(root, file),
|
|
45
|
+
document: {
|
|
46
|
+
uri: pathToFileURL(file).href,
|
|
47
|
+
format
|
|
48
|
+
},
|
|
49
|
+
checkerFileName: file,
|
|
50
|
+
projectionFileName: file.replaceAll("\\", "/"),
|
|
51
|
+
syntax
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
// src/compilation/finalize.ts
|
|
55
|
+
/**
|
|
56
|
+
* Finalizes compiled JavaScript and describes the inserted prefix for source-map generation.
|
|
57
|
+
*
|
|
58
|
+
* @param code - Compiled JavaScript before host finalization.
|
|
59
|
+
* @param stylesheetSpecifier - Optional side-effect import specifier. A falsy value inserts no
|
|
60
|
+
* import.
|
|
61
|
+
* @returns Final code, the exact prefix inserted before it, and an empty list of removed ranges.
|
|
62
|
+
*/
|
|
63
|
+
function finalizeModuleWithMap(code, stylesheetSpecifier) {
|
|
64
|
+
const stylesheetImport = stylesheetSpecifier ? `import ${JSON.stringify(stylesheetSpecifier)};\n` : "";
|
|
65
|
+
return {
|
|
66
|
+
code: stylesheetImport + code,
|
|
67
|
+
prefix: stylesheetImport,
|
|
68
|
+
removed: []
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
// src/compilation/source-map.ts
|
|
72
|
+
/**
|
|
73
|
+
* Traces framework output through a Stillwind transform when embedded source text identifies the
|
|
74
|
+
* transformed input.
|
|
75
|
+
*
|
|
76
|
+
* @param generated - Framework output map.
|
|
77
|
+
* @param original - Map or map chain from the Stillwind-transformed input back to original sources.
|
|
78
|
+
* @param transformedSource - Exact text to match against the generated map's `sourcesContent`.
|
|
79
|
+
* @returns A composed map. Only matching immediate sources are replaced. Other sources retain their
|
|
80
|
+
* mappings.
|
|
81
|
+
* @throws If a supplied source map cannot be decoded or composed.
|
|
82
|
+
*/
|
|
83
|
+
function composeFrameworkSourceMap(generated, original, transformedSource) {
|
|
84
|
+
const traced = new TraceMap(generated);
|
|
85
|
+
const matches = new Set(traced.resolvedSources.filter((_source, index) => traced.sourcesContent?.[index] === transformedSource));
|
|
86
|
+
return remapping(generated, (source, context) => context.depth === 1 && matches.has(source) ? original : null);
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Traces a CSS pipeline map through the original map of its carrier resource.
|
|
90
|
+
*
|
|
91
|
+
* @param generated - Pipeline output map, or a map chain accepted by the composition library.
|
|
92
|
+
* @param original - Map or chain from the CSS carrier back to authored sources.
|
|
93
|
+
* @param resource - Absolute carrier path with forward slashes. File URLs are decoded, and relative
|
|
94
|
+
* source paths are resolved against the process working directory before comparison.
|
|
95
|
+
* @returns A composed map that replaces only immediate sources resolving to the carrier path.
|
|
96
|
+
* @throws If a supplied source map cannot be decoded or composed.
|
|
97
|
+
*/
|
|
98
|
+
function composeCarrierSourceMap(generated, original, resource) {
|
|
99
|
+
return remapping(generated, (source, context) => context.depth === 1 && resolve(source.startsWith("file:") ? fileURLToPath(source) : source).replaceAll("\\", "/") === resource ? original : null);
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Composes the native output map with the upstream loader map or ordered map chain
|
|
103
|
+
* describing its input. Without upstream, returns the generated object unchanged.
|
|
104
|
+
* Invalid maps or incompatible chains may throw from the mapping library.
|
|
105
|
+
*
|
|
106
|
+
* @param generated - Map from compiled JavaScript back to the input received by Stillwind.
|
|
107
|
+
* @param upstream - Optional map or ordered map chain from that input back to original sources.
|
|
108
|
+
* @returns The generated map unchanged when no upstream map is supplied, otherwise a composed map.
|
|
109
|
+
* @throws If map decoding fails or a supplied map chain is incompatible.
|
|
110
|
+
*/
|
|
111
|
+
function composeModuleSourceMap(generated, upstream) {
|
|
112
|
+
return upstream ? remapping([JSON.stringify(generated), ...Array.isArray(upstream) ? upstream : [upstream]], () => null) : generated;
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Builds a JavaScript source map from compiler replacements and host finalization edits.
|
|
116
|
+
*
|
|
117
|
+
* Unchanged text maps character by character. Replacement text maps to its original start unless an
|
|
118
|
+
* expression interval provides a more precise correspondence. All offsets use UTF-16 code units.
|
|
119
|
+
*
|
|
120
|
+
* @param source - Original source whose text is embedded in the map.
|
|
121
|
+
* @param compiled - Compiler output before the host inserts a prefix or removes intervals.
|
|
122
|
+
* @param id - Source identity used as the map's file and sole source name.
|
|
123
|
+
* @param mappings - Nonoverlapping compiler replacements in generated-start order, with valid
|
|
124
|
+
* original and generated ranges.
|
|
125
|
+
* @param removed - Nonoverlapping ranges removed from `compiled`, in ascending order.
|
|
126
|
+
* @param prefix - Exact text inserted before the retained compiler output. It advances generated
|
|
127
|
+
* positions without receiving original mappings.
|
|
128
|
+
* @returns An encoded version 3 map for the finalized output with original source content.
|
|
129
|
+
*/
|
|
130
|
+
function moduleSourceMap(source, compiled, id, mappings, removed, prefix) {
|
|
131
|
+
const map = new GenMapping({ file: id });
|
|
132
|
+
setSourceContent(map, id, source);
|
|
133
|
+
const lines = [0];
|
|
134
|
+
for (let index = 0; index < source.length; index++) if (source[index] === "\n") lines.push(index + 1);
|
|
135
|
+
let line = prefix.split("\n").length - 1;
|
|
136
|
+
let column = prefix.length - prefix.lastIndexOf("\n") - 1;
|
|
137
|
+
let editIndex = 0;
|
|
138
|
+
let removedIndex = 0;
|
|
139
|
+
let expressionIndex = 0;
|
|
140
|
+
let delta = 0;
|
|
141
|
+
let originalLine = 0;
|
|
142
|
+
for (let index = 0; index < compiled.length; index++) {
|
|
143
|
+
while (removedIndex < removed.length && removed[removedIndex].to <= index) removedIndex++;
|
|
144
|
+
if (removedIndex < removed.length && removed[removedIndex].from <= index) continue;
|
|
145
|
+
while (editIndex < mappings.length && mappings[editIndex].generatedEnd <= index) {
|
|
146
|
+
const edit = mappings[editIndex++];
|
|
147
|
+
delta = edit.originalEnd - edit.generatedEnd;
|
|
148
|
+
expressionIndex = 0;
|
|
149
|
+
}
|
|
150
|
+
const edit = mappings[editIndex];
|
|
151
|
+
const expressions = edit?.expressions ?? [];
|
|
152
|
+
while (expressionIndex < expressions.length && expressions[expressionIndex].generatedEnd <= index) expressionIndex++;
|
|
153
|
+
const expression = expressions[expressionIndex];
|
|
154
|
+
const original = expression && expression.generatedStart <= index ? expression.originalStart + (expression.exact ? index - expression.generatedStart : 0) : edit && edit.generatedStart <= index ? edit.originalStart : index + delta;
|
|
155
|
+
if (original < lines[originalLine] || originalLine + 1 < lines.length && lines[originalLine + 1] <= original) {
|
|
156
|
+
let low = 0;
|
|
157
|
+
let high = lines.length;
|
|
158
|
+
while (low < high) {
|
|
159
|
+
const middle = low + high >>> 1;
|
|
160
|
+
if (lines[middle] <= original) low = middle + 1;
|
|
161
|
+
else high = middle;
|
|
162
|
+
}
|
|
163
|
+
originalLine = low - 1;
|
|
164
|
+
}
|
|
165
|
+
addSegment(map, line, column, id, originalLine, original - lines[originalLine]);
|
|
166
|
+
if (compiled[index] === "\n") {
|
|
167
|
+
line++;
|
|
168
|
+
column = 0;
|
|
169
|
+
} else column++;
|
|
170
|
+
}
|
|
171
|
+
return toEncodedMap(map);
|
|
172
|
+
}
|
|
173
|
+
// src/css/css-source-map.ts
|
|
174
|
+
/**
|
|
175
|
+
* Composes one producer map into the matching immediate source of a CSS map.
|
|
176
|
+
*
|
|
177
|
+
* Relative producer sources are resolved against its resource path and optional source root. Other
|
|
178
|
+
* CSS sources keep their existing mappings.
|
|
179
|
+
*
|
|
180
|
+
* @param map - Encoded CSS map whose source names identify original producer inputs.
|
|
181
|
+
* @param upstream - Optional producer map and the exact CSS source name to replace.
|
|
182
|
+
* @returns The composed map, or the input map unchanged when upstream is absent or lacks a sources
|
|
183
|
+
* array or nonempty mappings.
|
|
184
|
+
* @throws If producer JSON, source URLs, or source-map composition are invalid.
|
|
185
|
+
*/
|
|
186
|
+
function composeUpstream(map, upstream) {
|
|
187
|
+
if (!upstream) return map;
|
|
188
|
+
const resource = pathToFileURL(resolve(upstream.id.split(/[?#]/, 1)[0])).href;
|
|
189
|
+
const original = JSON.parse(upstream.map);
|
|
190
|
+
if (!Array.isArray(original.sources) || !original.mappings) return map;
|
|
191
|
+
/**
|
|
192
|
+
* Resolves a map source while retaining its query and fragment.
|
|
193
|
+
* @param source - Absolute path or URL reference. Backslashes are normalized to slashes.
|
|
194
|
+
* @param base - Absolute URL used to resolve relative references.
|
|
195
|
+
* @returns A file URL for an absolute path, or the resolved URL for another reference.
|
|
196
|
+
* @throws If the reference or base cannot form a valid URL.
|
|
197
|
+
*/
|
|
198
|
+
const sourceUrl = (source, base) => {
|
|
199
|
+
const normalized = source.replaceAll("\\", "/");
|
|
200
|
+
const clean = normalized.split(/[?#]/, 1)[0];
|
|
201
|
+
return isAbsolute(clean) ? pathToFileURL(clean).href + normalized.slice(clean.length) : new URL(normalized, base).href;
|
|
202
|
+
};
|
|
203
|
+
const base = original.sourceRoot ? sourceUrl(original.sourceRoot.replace(/\/?$/, "/"), resource) : resource;
|
|
204
|
+
original.sources = original.sources.map((source) => sourceUrl(source, base));
|
|
205
|
+
delete original.sourceRoot;
|
|
206
|
+
return remapping(JSON.stringify(map), (source, context) => context.depth === 1 && source === upstream.sourceMapSource ? original : null);
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* Rewrites resource placeholders while retaining native UTF-8 source locations.
|
|
210
|
+
*
|
|
211
|
+
* @param output - CSS and native source locations before resource replacement. Source indexes and
|
|
212
|
+
* byte boundaries must be valid for the supplied CSS and authored text.
|
|
213
|
+
* @param replacements - Resource placeholders mapped to escaped URL text.
|
|
214
|
+
* @param upstream - Optional maps from producer input back to its original source, in composition order.
|
|
215
|
+
* @param includeSourcesContent - Whether the inline map retains source text. Defaults to true.
|
|
216
|
+
* @returns Resolved CSS with an inline version 3 map, or an empty string when the input CSS is empty.
|
|
217
|
+
* @throws If an upstream map cannot be decoded, its source URLs are invalid, or composition fails.
|
|
218
|
+
*/
|
|
219
|
+
function cssWithSourceMap(output, replacements, upstream, includeSourcesContent = true) {
|
|
220
|
+
if (!output.css) return "";
|
|
221
|
+
const { css, sourceMap } = output;
|
|
222
|
+
const positions = sourceMap.sources.map(({ content }) => {
|
|
223
|
+
const result = /* @__PURE__ */ new Map();
|
|
224
|
+
let byte = 0;
|
|
225
|
+
let line = 0;
|
|
226
|
+
let column = 0;
|
|
227
|
+
for (const char of content) {
|
|
228
|
+
result.set(byte, [line, column]);
|
|
229
|
+
byte += Buffer.byteLength(char);
|
|
230
|
+
if (char === "\n") {
|
|
231
|
+
line++;
|
|
232
|
+
column = 0;
|
|
233
|
+
} else column += char.length;
|
|
234
|
+
}
|
|
235
|
+
result.set(byte, [line, column]);
|
|
236
|
+
return result;
|
|
237
|
+
});
|
|
238
|
+
const names = sourceMap.sources.map(({ sourceMapSource }) => sourceMapSource);
|
|
239
|
+
const map = new GenMapping();
|
|
240
|
+
names.forEach((name, index) => setSourceContent(map, name, sourceMap.sources[index].content));
|
|
241
|
+
let result = cssBannerPrefix(output.banners ?? []);
|
|
242
|
+
let byte = 0;
|
|
243
|
+
let line = result.match(/\r\n|\r|\n/g)?.length ?? 0;
|
|
244
|
+
let column = result.split("\n").at(-1).length;
|
|
245
|
+
let entryIndex = 0;
|
|
246
|
+
const entries = [...sourceMap.entries].sort((a, b) => a.generatedStart - b.generatedStart);
|
|
247
|
+
const edits = [...replacements];
|
|
248
|
+
for (let offset = 0; offset < css.length;) {
|
|
249
|
+
while (entryIndex < entries.length && entries[entryIndex].generatedEnd <= byte) entryIndex++;
|
|
250
|
+
const entry = entries[entryIndex];
|
|
251
|
+
const active = entry && entry.generatedStart <= byte ? entry : void 0;
|
|
252
|
+
const replacement = edits.find(([placeholder]) => css.startsWith(placeholder, offset));
|
|
253
|
+
const originalText = replacement?.[0] ?? String.fromCodePoint(css.codePointAt(offset));
|
|
254
|
+
const emitted = replacement?.[1] ?? originalText;
|
|
255
|
+
const position = active && positions[active.source].get(active.originalStart + (active.exact ? byte - active.generatedStart : 0));
|
|
256
|
+
for (const char of emitted) {
|
|
257
|
+
if (active && position) addSegment(map, line, column, names[active.source], ...position);
|
|
258
|
+
else addSegment(map, line, column);
|
|
259
|
+
if (char === "\n") {
|
|
260
|
+
line++;
|
|
261
|
+
column = 0;
|
|
262
|
+
} else column += char.length;
|
|
263
|
+
}
|
|
264
|
+
result += emitted;
|
|
265
|
+
byte += Buffer.byteLength(originalText);
|
|
266
|
+
offset += originalText.length;
|
|
267
|
+
}
|
|
268
|
+
return result + "\n/*# sourceMappingURL=data:application/json;base64," + Buffer.from(JSON.stringify((Array.isArray(upstream) ? upstream : [upstream]).reduce((map, source) => composeUpstream(map, source), toEncodedMap(map)), (key, value) => key === "sourcesContent" && !includeSourcesContent ? void 0 : value)).toString("base64") + " */";
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* Decodes the trailing inline map emitted by `cssWithSourceMap` or a compatible CSS carrier.
|
|
272
|
+
*
|
|
273
|
+
* @param css - Stylesheet text. A recognized map must contain a base64-encoded version 3 JSON map
|
|
274
|
+
* in the trailing comment format emitted by `cssWithSourceMap`.
|
|
275
|
+
* @returns CSS and its decoded map. Without a recognized trailing map, the CSS is unchanged and
|
|
276
|
+
* the map is null. JSON is decoded without validating its source-map fields.
|
|
277
|
+
* @throws If a recognized inline map contains invalid JSON.
|
|
278
|
+
*/
|
|
279
|
+
function decodeCssSourceMap(css) {
|
|
280
|
+
const match = /\n\/\*# sourceMappingURL=data:application\/json;base64,([A-Za-z0-9+/=]+) \*\/$/.exec(css);
|
|
281
|
+
if (!match) return {
|
|
282
|
+
code: css,
|
|
283
|
+
map: null
|
|
284
|
+
};
|
|
285
|
+
return {
|
|
286
|
+
code: css.slice(0, match.index),
|
|
287
|
+
map: JSON.parse(Buffer.from(match[1], "base64").toString("utf8"))
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
// src/semantics/node/project.ts
|
|
291
|
+
/**
|
|
292
|
+
* Normalizes filesystem names used as keys in the virtual checker overlay.
|
|
293
|
+
*
|
|
294
|
+
* @param fileName - Absolute or relative filesystem path.
|
|
295
|
+
* @returns An absolute path with forward slashes, lowercased on Windows to match case-insensitive
|
|
296
|
+
* filesystem lookups.
|
|
297
|
+
*/
|
|
298
|
+
const normalize = (fileName) => {
|
|
299
|
+
const name = path.resolve(fileName).replaceAll("\\", "/");
|
|
300
|
+
return process.platform === "win32" ? name.toLowerCase() : name;
|
|
301
|
+
};
|
|
302
|
+
/**
|
|
303
|
+
* Selects the TypeScript environment before starting a checker.
|
|
304
|
+
*
|
|
305
|
+
* @param root - Filesystem project directory, resolved to an absolute path.
|
|
306
|
+
* @param tsconfig - Absolute or root-relative config path. Omission selects an existing root
|
|
307
|
+
* `tsconfig.json`. False selects isolated defaults even when that file exists.
|
|
308
|
+
* @returns Fixed settings without evaluating configuration or starting the checker.
|
|
309
|
+
* @throws If an explicitly selected path is empty or its configuration file does not exist.
|
|
310
|
+
*/
|
|
311
|
+
function resolveTypeFactsEnvironment(root, tsconfig) {
|
|
312
|
+
root = path.resolve(root);
|
|
313
|
+
if (typeof tsconfig === "string" && !tsconfig.trim()) throw new Error("TypeScript configuration path must not be empty");
|
|
314
|
+
const configPath = path.resolve(root, typeof tsconfig === "string" ? tsconfig : "tsconfig.json");
|
|
315
|
+
if (typeof tsconfig === "string" && !existsSync(configPath)) throw new Error(`TypeScript configuration does not exist: ${configPath}`);
|
|
316
|
+
return {
|
|
317
|
+
root,
|
|
318
|
+
project: tsconfig !== false && existsSync(configPath) ? {
|
|
319
|
+
kind: "configured",
|
|
320
|
+
configPath
|
|
321
|
+
} : { kind: "isolated" }
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
/**
|
|
325
|
+
* Builds checker sources and an in-memory project configuration for semantic queries.
|
|
326
|
+
*
|
|
327
|
+
* @param sources - Prepared sources with validated mappings, original probes, and dependency
|
|
328
|
+
* resolutions.
|
|
329
|
+
* @param assetsByModuleId - Native declaration records keyed by compiler module identity.
|
|
330
|
+
* @param shadowTsconfigPath - Absolute filename of the generated in-memory TypeScript project.
|
|
331
|
+
* @param project - Consumer configuration to inherit, or isolated compiler defaults.
|
|
332
|
+
* @param inputs - Captured file replacements and declarations required by this collection.
|
|
333
|
+
* @param configuredDeclarations - Declaration files selected by the consumer's tsconfig.
|
|
334
|
+
* @returns Virtual text and range mappings without writing any files to disk.
|
|
335
|
+
* @throws If checker edits or projection maps are invalid, or an original probe has no
|
|
336
|
+
* checker-buffer correspondence.
|
|
337
|
+
*/
|
|
338
|
+
function prepareProject(sources, assetsByModuleId, shadowTsconfigPath, project, inputs, configuredDeclarations) {
|
|
339
|
+
const virtualFiles = new Map([...inputs.overlayFiles ?? [], ...inputs.ambientDeclarations ?? []].map(([name, text]) => [normalize(name), text]));
|
|
340
|
+
const mappings = [];
|
|
341
|
+
const allIdentities = /* @__PURE__ */ new Map();
|
|
342
|
+
const globals = /* @__PURE__ */ new Set();
|
|
343
|
+
const ids = new Map(sources.map((source) => [source.resolverId, checkerId(source)]));
|
|
344
|
+
for (const source of sources) {
|
|
345
|
+
const declarations = source.kind === "projected" && source.projection.checkerGlobals;
|
|
346
|
+
if (declarations) {
|
|
347
|
+
const fingerprint = createHash("sha256").update(declarations).digest("hex").slice(0, 16);
|
|
348
|
+
const id = normalize(path.join(path.dirname(shadowTsconfigPath), `.stillwind-globals-${fingerprint}.d.ts`));
|
|
349
|
+
virtualFiles.set(id, declarations);
|
|
350
|
+
globals.add(id);
|
|
351
|
+
}
|
|
352
|
+
const syntax = source.kind === "direct" ? source.syntax : source.projection.syntax;
|
|
353
|
+
const buffers = source.checkerBuffers ?? [{
|
|
354
|
+
source: source.kind === "direct" ? source.document.code : source.projection.code,
|
|
355
|
+
language: syntax.language === "tsx" || syntax.language === "jsx" ? "tsx" : "ts"
|
|
356
|
+
}];
|
|
357
|
+
for (const [index, buffer] of buffers.entries()) {
|
|
358
|
+
const shadow = new CheckerSource(source, buffer, index, assetsByModuleId.get(source.moduleId) ?? [], ids);
|
|
359
|
+
virtualFiles.set(normalize(shadow.id), shadow.text);
|
|
360
|
+
if (shadow.helperModule) virtualFiles.set(normalize(shadow.helperModule.id), shadow.helperModule.text);
|
|
361
|
+
mappings.push(shadow);
|
|
362
|
+
for (const [key, identity] of shadow.identities) allIdentities.set(key, identity);
|
|
363
|
+
}
|
|
364
|
+
for (const probe of source.probes) if (!mappings.some((mapping) => mapping.source === source && [...mapping.probes.values()].some((candidate) => candidate.start === probe.start && candidate.end === probe.end))) throw new TypeFactsError(source.moduleId, probe.start, probe.end, "checker", "Cannot map this expression to a checker source");
|
|
365
|
+
}
|
|
366
|
+
virtualFiles.set(normalize(shadowTsconfigPath), JSON.stringify({
|
|
367
|
+
...project.kind === "configured" ? { extends: project.configPath } : {},
|
|
368
|
+
compilerOptions: {
|
|
369
|
+
allowJs: true,
|
|
370
|
+
checkJs: true,
|
|
371
|
+
...project.kind === "isolated" ? {
|
|
372
|
+
jsx: "preserve",
|
|
373
|
+
module: "esnext",
|
|
374
|
+
moduleResolution: "bundler",
|
|
375
|
+
strict: true,
|
|
376
|
+
target: "esnext",
|
|
377
|
+
types: []
|
|
378
|
+
} : {},
|
|
379
|
+
noEmit: true,
|
|
380
|
+
skipLibCheck: true,
|
|
381
|
+
allowImportingTsExtensions: true
|
|
382
|
+
},
|
|
383
|
+
files: [
|
|
384
|
+
...configuredDeclarations,
|
|
385
|
+
...[...inputs.ambientDeclarations?.keys() ?? []].map(normalize),
|
|
386
|
+
...globals,
|
|
387
|
+
...mappings.map((mapping) => mapping.id),
|
|
388
|
+
...new Set(sources.flatMap((source) => source.checkerTypes ?? []))
|
|
389
|
+
],
|
|
390
|
+
include: [],
|
|
391
|
+
exclude: []
|
|
392
|
+
}));
|
|
393
|
+
return {
|
|
394
|
+
virtualFiles,
|
|
395
|
+
mappings,
|
|
396
|
+
identities: allIdentities
|
|
397
|
+
};
|
|
398
|
+
}
|
|
399
|
+
// src/semantics/node/facts.ts
|
|
400
|
+
/**
|
|
401
|
+
* Traverses a checker AST in preorder.
|
|
402
|
+
*
|
|
403
|
+
* @param node - Root visited before its descendants.
|
|
404
|
+
* @param callback - Operation called once for the root and each child exposed by `forEachChild`.
|
|
405
|
+
* Thrown errors stop traversal.
|
|
406
|
+
*/
|
|
407
|
+
function visit(node, callback) {
|
|
408
|
+
callback(node);
|
|
409
|
+
node.forEachChild((child) => visit(child, callback));
|
|
410
|
+
}
|
|
411
|
+
/**
|
|
412
|
+
* Flattens a checker diagnostic and its nested message chain for matching and display.
|
|
413
|
+
*
|
|
414
|
+
* @param diagnostic - Checker diagnostic with optional nested messages.
|
|
415
|
+
* @returns Diagnostic text followed recursively by child messages, separated by newlines.
|
|
416
|
+
*/
|
|
417
|
+
function diagnosticText(diagnostic) {
|
|
418
|
+
return [diagnostic.text, ...(diagnostic.messageChain ?? []).map(diagnosticText)].join("\n");
|
|
419
|
+
}
|
|
420
|
+
/**
|
|
421
|
+
* Tests whether a TypeScript argument error belongs to a style producer call.
|
|
422
|
+
* Lowering reports unsupported macro arguments as lints, so these errors do not invalidate the
|
|
423
|
+
* facts of the call. The operands still require valid facts.
|
|
424
|
+
*
|
|
425
|
+
* @param diagnostic - Checker diagnostic for `sourceFile`.
|
|
426
|
+
* @param sourceFile - Checker source file that contains the diagnostic.
|
|
427
|
+
* @param mapping - Producer call ranges of the same source.
|
|
428
|
+
* @returns Whether the diagnostic is an argument error (TS2345 or TS2769) whose innermost
|
|
429
|
+
* enclosing call is a recorded producer call.
|
|
430
|
+
*/
|
|
431
|
+
function producerArgumentDiagnostic(diagnostic, sourceFile, mapping) {
|
|
432
|
+
if (diagnostic.code !== 2345 && diagnostic.code !== 2769) return false;
|
|
433
|
+
let owner;
|
|
434
|
+
visit(sourceFile, (node) => {
|
|
435
|
+
if (isCallExpression(node) && node.getStart(sourceFile) <= diagnostic.pos && node.end >= diagnostic.end && (!owner || node.end - node.getStart(sourceFile) < owner.end - owner.getStart(sourceFile))) owner = node;
|
|
436
|
+
});
|
|
437
|
+
return !!owner && mapping.producers.has(`${owner.getStart(sourceFile)}:${owner.end}`);
|
|
438
|
+
}
|
|
439
|
+
/**
|
|
440
|
+
* Decodes the types of checker expressions matched to original semantic probes.
|
|
441
|
+
*
|
|
442
|
+
* @param sourceFile - Final checker AST for the mapped buffer.
|
|
443
|
+
* @param mapping - Original probes indexed by exact checker AST start and end positions.
|
|
444
|
+
* @param decoder - Decoder with asset brands already registered from producer types.
|
|
445
|
+
* @param nodes - Expression nodes from sourceFile, in AST traversal order.
|
|
446
|
+
* @param typesAt - Returns one type per node, in the supplied order. Undefined means no type is available.
|
|
447
|
+
* @param unverified - Optional array to append unavailable original ranges to. Supplying it keeps
|
|
448
|
+
* other facts usable when a probe lacks an expression or a finite declaration type.
|
|
449
|
+
* @returns Facts in AST traversal order with original byte ranges. Known types that do not
|
|
450
|
+
* represent Stillwind assets produce null values. Unresolved recognition-only probes are skipped
|
|
451
|
+
* in both strict and partial queries.
|
|
452
|
+
* @throws If unverified is omitted and a probe has no matching expression or a required type cannot
|
|
453
|
+
* be resolved. Errors from typesAt also propagate.
|
|
454
|
+
*/
|
|
455
|
+
function factsForSource(sourceFile, mapping, decoder, nodes, typesAt, unverified) {
|
|
456
|
+
const expressions = [];
|
|
457
|
+
const matched = /* @__PURE__ */ new Set();
|
|
458
|
+
for (const node of nodes) {
|
|
459
|
+
const key = `${node.getStart(sourceFile)}:${node.end}`;
|
|
460
|
+
if (mapping.probes.has(key)) {
|
|
461
|
+
expressions.push(node);
|
|
462
|
+
matched.add(key);
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
for (const [key, probe] of mapping.probes) if (!matched.has(key)) {
|
|
466
|
+
const error = new TypeFactsError(mapping.source.moduleId, probe.start, probe.end, "checker", "Projected expression has no matching checker AST node");
|
|
467
|
+
if (!unverified) throw error;
|
|
468
|
+
unverified.push({
|
|
469
|
+
moduleId: error.moduleId,
|
|
470
|
+
start: error.start,
|
|
471
|
+
end: error.end,
|
|
472
|
+
reason: error.message
|
|
473
|
+
});
|
|
474
|
+
}
|
|
475
|
+
const types = typesAt(expressions);
|
|
476
|
+
const facts = [];
|
|
477
|
+
for (const [index, expression] of expressions.entries()) {
|
|
478
|
+
const probe = mapping.probes.get(`${expression.getStart(sourceFile)}:${expression.end}`);
|
|
479
|
+
const type = types[index];
|
|
480
|
+
const decoded = type ? decoder.decode(type, probe.recognitionOnly ?? false) : { kind: "unverified" };
|
|
481
|
+
if (decoded.kind !== "asset") {
|
|
482
|
+
if (decoded.kind === "unverified" || decoded.kind === "unbranded" && !probe.recognitionOnly) {
|
|
483
|
+
if (probe.recognitionOnly) continue;
|
|
484
|
+
const error = new TypeFactsError(mapping.source.moduleId, probe.start, probe.end, "identity", "Cannot determine a finite set of declaration identities. Preserve the value's inferred type, use an explicit union, or use a generic parameter.");
|
|
485
|
+
if (!unverified) throw error;
|
|
486
|
+
unverified.push({
|
|
487
|
+
moduleId: error.moduleId,
|
|
488
|
+
start: error.start,
|
|
489
|
+
end: error.end,
|
|
490
|
+
reason: error.message
|
|
491
|
+
});
|
|
492
|
+
} else facts.push({
|
|
493
|
+
...probe,
|
|
494
|
+
value: null
|
|
495
|
+
});
|
|
496
|
+
continue;
|
|
497
|
+
}
|
|
498
|
+
facts.push({
|
|
499
|
+
...probe,
|
|
500
|
+
value: decoded.value
|
|
501
|
+
});
|
|
502
|
+
}
|
|
503
|
+
return facts;
|
|
504
|
+
}
|
|
505
|
+
// src/semantics/node/checker.ts
|
|
506
|
+
/**
|
|
507
|
+
* Owns the Node checker process, snapshots, and answers cached within each snapshot.
|
|
508
|
+
* The analysis service serializes calls and closes the checker after pending work finishes.
|
|
509
|
+
*/
|
|
510
|
+
var NodeChecker = class {
|
|
511
|
+
/** Property answers for the current snapshot. Cleared before replacing that snapshot. */
|
|
512
|
+
properties = {
|
|
513
|
+
named: /* @__PURE__ */ new Map(),
|
|
514
|
+
all: /* @__PURE__ */ new Map()
|
|
515
|
+
};
|
|
516
|
+
/** Types keyed by filename and AST range within the current snapshot. */
|
|
517
|
+
#queryTypes = /* @__PURE__ */ new Map();
|
|
518
|
+
/** Expression nodes in AST traversal order, keyed by checker filename. */
|
|
519
|
+
#queryNodes = /* @__PURE__ */ new Map();
|
|
520
|
+
/** Syntactic and semantic diagnostics for each checker file in the current snapshot. */
|
|
521
|
+
diagnostics = /* @__PURE__ */ new Map();
|
|
522
|
+
/** Paths observed by disk reads and existence checks, including missing paths and overlay checks. */
|
|
523
|
+
dependencies = /* @__PURE__ */ new Set();
|
|
524
|
+
/**
|
|
525
|
+
* Live cumulative counters updated by this service. Consumers needing a stable report must copy
|
|
526
|
+
* their values.
|
|
527
|
+
*/
|
|
528
|
+
stats = {
|
|
529
|
+
starts: 0,
|
|
530
|
+
snapshots: 0,
|
|
531
|
+
incrementalSnapshots: 0,
|
|
532
|
+
restarts: 0,
|
|
533
|
+
overlayReads: 0,
|
|
534
|
+
diskReadRequests: 0
|
|
535
|
+
};
|
|
536
|
+
/** Copy of the selected TypeScript settings, fixed for this service's lifetime. */
|
|
537
|
+
#project;
|
|
538
|
+
/** Filesystem root supplied as the checker API working directory. */
|
|
539
|
+
#projectRoot;
|
|
540
|
+
/**
|
|
541
|
+
* Absolute filename of the in-memory `.stillwind-tsconfig.json`. The service does not write it to
|
|
542
|
+
* disk.
|
|
543
|
+
*/
|
|
544
|
+
#shadowTsconfigPath;
|
|
545
|
+
/** Active checker API instance, replaced after a recoverable collection failure. */
|
|
546
|
+
#api;
|
|
547
|
+
/**
|
|
548
|
+
* Latest retained checker snapshot, also retained after query failures until the next update,
|
|
549
|
+
* restart, or close.
|
|
550
|
+
*/
|
|
551
|
+
#snapshot;
|
|
552
|
+
/**
|
|
553
|
+
* Current normalized filename overlay read dynamically by the checker API filesystem callbacks.
|
|
554
|
+
*/
|
|
555
|
+
#virtualFiles = /* @__PURE__ */ new Map();
|
|
556
|
+
/**
|
|
557
|
+
* Starts a checker API for a project root without creating its first snapshot.
|
|
558
|
+
*
|
|
559
|
+
* @param environment - Absolute filesystem root and selected TypeScript settings. The checker
|
|
560
|
+
* copies these settings and uses them for its lifetime. Create a new checker to change them.
|
|
561
|
+
* @throws If the checker API cannot start.
|
|
562
|
+
*/
|
|
563
|
+
constructor(environment) {
|
|
564
|
+
this.#project = { ...environment.project };
|
|
565
|
+
this.#projectRoot = environment.root;
|
|
566
|
+
this.#shadowTsconfigPath = path.join(environment.root, ".stillwind-tsconfig.json");
|
|
567
|
+
this.#api = this.#startApi();
|
|
568
|
+
}
|
|
569
|
+
/**
|
|
570
|
+
* Builds virtual checker files using the project's TypeScript settings.
|
|
571
|
+
*
|
|
572
|
+
* @param sources - Prepared sources and probes for this request.
|
|
573
|
+
* @param assets - Declarations grouped by compiler module ID.
|
|
574
|
+
* @param inputs - Overlays and ambient declarations used for config reads and checker files.
|
|
575
|
+
* @returns Virtual files, checker mappings, and declaration identities for the supplied sources.
|
|
576
|
+
* @throws If configuration parsing, checker mapping, or declaration preparation fails.
|
|
577
|
+
*/
|
|
578
|
+
prepareProject(sources, assets, inputs) {
|
|
579
|
+
return prepareProject(sources, assets, this.#shadowTsconfigPath, this.#project, inputs, this.#configuredDeclarations(inputs));
|
|
580
|
+
}
|
|
581
|
+
/**
|
|
582
|
+
* Queries types once per expression in the current snapshot.
|
|
583
|
+
*
|
|
584
|
+
* @param checker - Checker that owns the current snapshot.
|
|
585
|
+
* @param nodes - Expression nodes from that snapshot, in the requested order.
|
|
586
|
+
* @returns Types in the same order. Undefined records a missing type. Answers are cached until the snapshot changes.
|
|
587
|
+
* @throws If the checker query fails.
|
|
588
|
+
*/
|
|
589
|
+
types(checker, nodes) {
|
|
590
|
+
const keys = nodes.map((node) => `${node.getSourceFile().fileName}:${node.pos}:${node.end}`);
|
|
591
|
+
const missing = /* @__PURE__ */ new Map();
|
|
592
|
+
for (const [index, key] of keys.entries()) if (!this.#queryTypes.has(key)) missing.set(key, nodes[index]);
|
|
593
|
+
if (missing.size) {
|
|
594
|
+
const values = checker.getTypeAtLocation([...missing.values()]);
|
|
595
|
+
[...missing.keys()].forEach((key, index) => this.#queryTypes.set(key, values[index]));
|
|
596
|
+
}
|
|
597
|
+
return keys.map((key) => this.#queryTypes.get(key));
|
|
598
|
+
}
|
|
599
|
+
/**
|
|
600
|
+
* Finds expression nodes once per file in the current snapshot.
|
|
601
|
+
*
|
|
602
|
+
* @param file - Source file from the current checker snapshot.
|
|
603
|
+
* @returns Cached expression nodes in AST traversal order. Do not mutate the array.
|
|
604
|
+
*/
|
|
605
|
+
expressions(file) {
|
|
606
|
+
let nodes = this.#queryNodes.get(file.fileName);
|
|
607
|
+
if (!nodes) {
|
|
608
|
+
const expressions = [];
|
|
609
|
+
visit(file, (node) => {
|
|
610
|
+
if (isExpression(node)) expressions.push(node);
|
|
611
|
+
});
|
|
612
|
+
nodes = expressions;
|
|
613
|
+
this.#queryNodes.set(file.fileName, nodes);
|
|
614
|
+
}
|
|
615
|
+
return nodes;
|
|
616
|
+
}
|
|
617
|
+
/**
|
|
618
|
+
* Reads the consumer's declaration roots using the captured configuration overlays. Ordinary
|
|
619
|
+
* source files selected by the consumer remain outside the generated project's root files.
|
|
620
|
+
*
|
|
621
|
+
* @param inputs - File replacements used while parsing the selected configuration.
|
|
622
|
+
* @returns Declaration filenames selected by TypeScript, or an empty list for isolated settings.
|
|
623
|
+
* Restores the overlay used by the retained snapshot before returning or throwing.
|
|
624
|
+
* @throws If TypeScript cannot parse the selected configuration or its inherited files.
|
|
625
|
+
*/
|
|
626
|
+
#configuredDeclarations(inputs) {
|
|
627
|
+
if (this.#project.kind === "isolated") return [];
|
|
628
|
+
const previous = this.#virtualFiles;
|
|
629
|
+
this.#virtualFiles = new Map([...inputs.overlayFiles ?? [], ...inputs.ambientDeclarations ?? []].map(([name, text]) => [normalize(name), text]));
|
|
630
|
+
try {
|
|
631
|
+
return this.#api.parseConfigFile(this.#project.configPath).fileNames.filter((file) => /\.d\.[cm]?ts$/i.test(file));
|
|
632
|
+
} finally {
|
|
633
|
+
this.#virtualFiles = previous;
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
/**
|
|
637
|
+
* Starts a checker API whose filesystem callbacks consult the current virtual overlay.
|
|
638
|
+
*
|
|
639
|
+
* @returns A new API using the project root, with timing collection enabled. Increments starts
|
|
640
|
+
* before construction. Read callbacks update the filesystem counters.
|
|
641
|
+
* @throws If API construction fails.
|
|
642
|
+
*/
|
|
643
|
+
#startApi() {
|
|
644
|
+
this.stats.starts += 1;
|
|
645
|
+
return new API({
|
|
646
|
+
cwd: this.#projectRoot,
|
|
647
|
+
collectTiming: true,
|
|
648
|
+
fs: {
|
|
649
|
+
directoryExists: (directoryName) => {
|
|
650
|
+
const prefix = normalize(directoryName).replace(/\/$/, "") + "/";
|
|
651
|
+
return [...this.#virtualFiles.keys()].some((name) => name.startsWith(prefix)) ? true : void 0;
|
|
652
|
+
},
|
|
653
|
+
fileExists: (fileName) => {
|
|
654
|
+
this.dependencies.add(fileName);
|
|
655
|
+
return this.#virtualFiles.has(normalize(fileName)) ? true : void 0;
|
|
656
|
+
},
|
|
657
|
+
readFile: (fileName) => {
|
|
658
|
+
const overlay = this.#virtualFiles.get(normalize(fileName));
|
|
659
|
+
if (overlay === void 0) {
|
|
660
|
+
this.dependencies.add(fileName);
|
|
661
|
+
this.stats.diskReadRequests += 1;
|
|
662
|
+
} else this.stats.overlayReads += 1;
|
|
663
|
+
return overlay;
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
});
|
|
667
|
+
}
|
|
668
|
+
/**
|
|
669
|
+
* Disposes the previous snapshot and API, then replaces the API without clearing virtual files or
|
|
670
|
+
* counters.
|
|
671
|
+
*
|
|
672
|
+
* @throws If cleanup or creation of the replacement API fails.
|
|
673
|
+
*/
|
|
674
|
+
restart() {
|
|
675
|
+
this.#disposeApi();
|
|
676
|
+
this.#api = this.#startApi();
|
|
677
|
+
}
|
|
678
|
+
/**
|
|
679
|
+
* Releases the API and all answers whose objects belong to its snapshot.
|
|
680
|
+
*/
|
|
681
|
+
#disposeApi() {
|
|
682
|
+
this.#snapshot?.dispose();
|
|
683
|
+
this.#snapshot = void 0;
|
|
684
|
+
this.#clearQueries();
|
|
685
|
+
this.#api.close();
|
|
686
|
+
}
|
|
687
|
+
/**
|
|
688
|
+
* Discards query results before replacing a checker snapshot.
|
|
689
|
+
*/
|
|
690
|
+
#clearQueries() {
|
|
691
|
+
this.properties.named.clear();
|
|
692
|
+
this.properties.all.clear();
|
|
693
|
+
this.#queryTypes.clear();
|
|
694
|
+
this.#queryNodes.clear();
|
|
695
|
+
this.diagnostics.clear();
|
|
696
|
+
}
|
|
697
|
+
/**
|
|
698
|
+
* Replaces virtual files and retains the new snapshot after releasing the previous one.
|
|
699
|
+
*
|
|
700
|
+
* @param prepared - Complete normalized virtual project, retained as the new filesystem overlay.
|
|
701
|
+
* @returns The checker project from the new snapshot. Snapshot counters are incremented after update.
|
|
702
|
+
* @throws If snapshot update or disposal fails, or the generated project cannot be opened.
|
|
703
|
+
*/
|
|
704
|
+
updateProject(prepared) {
|
|
705
|
+
const changed = [];
|
|
706
|
+
const created = [];
|
|
707
|
+
const deleted = [];
|
|
708
|
+
for (const [fileName, contents] of prepared.virtualFiles) if (!this.#virtualFiles.has(fileName)) (existsSync(fileName) ? changed : created).push(fileName);
|
|
709
|
+
else if (this.#virtualFiles.get(fileName) !== contents) changed.push(fileName);
|
|
710
|
+
for (const fileName of this.#virtualFiles.keys()) if (!prepared.virtualFiles.has(fileName)) (existsSync(fileName) ? changed : deleted).push(fileName);
|
|
711
|
+
this.#virtualFiles = prepared.virtualFiles;
|
|
712
|
+
if (this.#snapshot && changed.length === 0 && created.length === 0 && deleted.length === 0) {
|
|
713
|
+
const project = this.#snapshot.getProject(this.#shadowTsconfigPath);
|
|
714
|
+
if (project) return project;
|
|
715
|
+
}
|
|
716
|
+
this.#clearQueries();
|
|
717
|
+
const next = this.#snapshot ? this.#api.updateSnapshot({ fileChanges: {
|
|
718
|
+
changed,
|
|
719
|
+
created,
|
|
720
|
+
deleted
|
|
721
|
+
} }) : this.#api.updateSnapshot({ openProjects: [this.#shadowTsconfigPath] });
|
|
722
|
+
this.stats.snapshots += 1;
|
|
723
|
+
if (this.#snapshot) this.stats.incrementalSnapshots += 1;
|
|
724
|
+
this.#snapshot?.dispose();
|
|
725
|
+
this.#snapshot = next;
|
|
726
|
+
const project = next.getProject(this.#shadowTsconfigPath);
|
|
727
|
+
if (!project) throw new Error("TypeScript 7 could not open the Stillwind shadow project");
|
|
728
|
+
return project;
|
|
729
|
+
}
|
|
730
|
+
/**
|
|
731
|
+
* Releases the checker process and all objects owned by its snapshot.
|
|
732
|
+
*/
|
|
733
|
+
close() {
|
|
734
|
+
this.#disposeApi();
|
|
735
|
+
}
|
|
736
|
+
};
|
|
737
|
+
// src/semantics/node/decoder.ts
|
|
738
|
+
/** Types whose values cannot be Stillwind assets. */
|
|
739
|
+
const primitiveTypeFlags = TypeFlags.StringLike | TypeFlags.NumberLike | TypeFlags.BigIntLike | TypeFlags.BooleanLike | TypeFlags.EnumLike | TypeFlags.ESSymbolLike | TypeFlags.Null | TypeFlags.Undefined | TypeFlags.Void | TypeFlags.Never;
|
|
740
|
+
/**
|
|
741
|
+
* Decodes a string-literal identity type or union using the current declaration table.
|
|
742
|
+
*
|
|
743
|
+
* @param type - Checker type of an identity property, or undefined when the property is
|
|
744
|
+
* unavailable.
|
|
745
|
+
* @param identities - Serialized keys mapped to known native declaration identities.
|
|
746
|
+
* @param kind - Asset family that every candidate must belong to.
|
|
747
|
+
* @returns Candidates in type-member order. Returns `"unknown"` if the type is absent,
|
|
748
|
+
* nonliteral, or unknown to the table, and `"mismatch"` if a candidate belongs to a
|
|
749
|
+
* different asset family.
|
|
750
|
+
*/
|
|
751
|
+
function knownIdentities(type, identities, kind) {
|
|
752
|
+
if (!type) return "unknown";
|
|
753
|
+
const types = type.isUnionType() ? type.getTypes() : [type];
|
|
754
|
+
const result = [];
|
|
755
|
+
let unknown = false;
|
|
756
|
+
for (const candidate of types) {
|
|
757
|
+
const identity = candidate.isStringLiteralType() ? identities.get(candidate.value) : void 0;
|
|
758
|
+
if (!identity) {
|
|
759
|
+
unknown = true;
|
|
760
|
+
continue;
|
|
761
|
+
}
|
|
762
|
+
if (identity.kind !== kind) return "mismatch";
|
|
763
|
+
result.push(identity);
|
|
764
|
+
}
|
|
765
|
+
return unknown ? "unknown" : result;
|
|
766
|
+
}
|
|
767
|
+
/**
|
|
768
|
+
* Packages known declarations as a finite native symbolic value.
|
|
769
|
+
*
|
|
770
|
+
* @param kind - Asset family shared by the supplied identities.
|
|
771
|
+
* @param identities - Candidate identities retained in their supplied order.
|
|
772
|
+
* @returns A finite symbolic value containing a copied candidate array.
|
|
773
|
+
*/
|
|
774
|
+
function symbolic(kind, identities) {
|
|
775
|
+
return {
|
|
776
|
+
kind,
|
|
777
|
+
candidates: {
|
|
778
|
+
kind: "finite",
|
|
779
|
+
values: [...identities]
|
|
780
|
+
}
|
|
781
|
+
};
|
|
782
|
+
}
|
|
783
|
+
/**
|
|
784
|
+
* Decodes checker types into native declaration candidates using brand properties discovered from
|
|
785
|
+
* producer modules.
|
|
786
|
+
*/
|
|
787
|
+
var AssetTypeDecoder = class {
|
|
788
|
+
/**
|
|
789
|
+
* Checker for the current project snapshot, used to inspect exported types and their properties.
|
|
790
|
+
*/
|
|
791
|
+
#checker;
|
|
792
|
+
/** Shared property lookups. The owning service clears them before replacing the snapshot. */
|
|
793
|
+
#properties;
|
|
794
|
+
/**
|
|
795
|
+
* All declaration keys registered in the current virtual project, mapped to original native
|
|
796
|
+
* identities.
|
|
797
|
+
*/
|
|
798
|
+
#identities;
|
|
799
|
+
/** Checker symbol IDs of modules whose exported asset brands have already been inspected. */
|
|
800
|
+
#modules = /* @__PURE__ */ new Set();
|
|
801
|
+
/** Internal names of discovered unique-symbol brand properties mapped to their asset families. */
|
|
802
|
+
#brands = /* @__PURE__ */ new Map();
|
|
803
|
+
/** Registered producer call types, used to detect object types that may hold a widened asset. */
|
|
804
|
+
#producers = [];
|
|
805
|
+
/**
|
|
806
|
+
* Creates a decoder for one checker snapshot and declaration table.
|
|
807
|
+
*
|
|
808
|
+
* @param checker - Checker owning all types supplied to this decoder.
|
|
809
|
+
* @param identities - Serialized identity keys inserted into the project's producer calls.
|
|
810
|
+
* @param properties - Property cache for the same checker snapshot. May be shared with other decoders.
|
|
811
|
+
*/
|
|
812
|
+
constructor(checker, identities, properties) {
|
|
813
|
+
this.#checker = checker;
|
|
814
|
+
this.#identities = identities;
|
|
815
|
+
this.#properties = properties;
|
|
816
|
+
}
|
|
817
|
+
/**
|
|
818
|
+
* Looks up a named property once per snapshot, including missing properties.
|
|
819
|
+
*
|
|
820
|
+
* @param type - Type from this decoder's checker snapshot.
|
|
821
|
+
* @param name - Property name to look up.
|
|
822
|
+
* @returns The property symbol, or undefined when absent. Stores the answer in the shared cache.
|
|
823
|
+
*/
|
|
824
|
+
#property(type, name) {
|
|
825
|
+
const key = `${type.id}:${name}`;
|
|
826
|
+
if (!this.#properties.named.has(key)) this.#properties.named.set(key, this.#checker.getPropertyOfType(type, name));
|
|
827
|
+
return this.#properties.named.get(key);
|
|
828
|
+
}
|
|
829
|
+
/**
|
|
830
|
+
* Looks up all properties of a type once per snapshot.
|
|
831
|
+
*
|
|
832
|
+
* @param type - Type from this decoder's checker snapshot.
|
|
833
|
+
* @returns The cached property list. Do not mutate it.
|
|
834
|
+
*/
|
|
835
|
+
#allProperties(type) {
|
|
836
|
+
let properties = this.#properties.all.get(type.id);
|
|
837
|
+
if (!properties) {
|
|
838
|
+
properties = this.#checker.getPropertiesOfType(type);
|
|
839
|
+
this.#properties.all.set(type.id, properties);
|
|
840
|
+
}
|
|
841
|
+
return properties;
|
|
842
|
+
}
|
|
843
|
+
/**
|
|
844
|
+
* Discovers ref, keyframe, and view-transition brands in a producer type's declaring module.
|
|
845
|
+
*
|
|
846
|
+
* @param type - Producer call type from this decoder's checker snapshot. The type is retained for
|
|
847
|
+
* later decoding. Missing alias modules and already inspected modules are skipped. The discovered
|
|
848
|
+
* property names are retained for later decoding.
|
|
849
|
+
*/
|
|
850
|
+
register(type) {
|
|
851
|
+
this.#producers.push(type);
|
|
852
|
+
const module = type.getAliasSymbol()?.getParent();
|
|
853
|
+
if (!module || this.#modules.has(module.id)) return;
|
|
854
|
+
this.#modules.add(module.id);
|
|
855
|
+
for (const [name, kind, brand] of [
|
|
856
|
+
[
|
|
857
|
+
"StyleRef",
|
|
858
|
+
"ref",
|
|
859
|
+
"refIdentity"
|
|
860
|
+
],
|
|
861
|
+
[
|
|
862
|
+
"StyleKeyframes",
|
|
863
|
+
"keyframes",
|
|
864
|
+
"keyframesIdentity"
|
|
865
|
+
],
|
|
866
|
+
[
|
|
867
|
+
"StyleViewTransition",
|
|
868
|
+
"viewTransition",
|
|
869
|
+
"viewTransitionIdentity"
|
|
870
|
+
]
|
|
871
|
+
]) {
|
|
872
|
+
const symbol = this.#checker.getMemberInModuleExports(module, name);
|
|
873
|
+
if (!symbol) continue;
|
|
874
|
+
const declared = this.#checker.getDeclaredTypeOfSymbol(symbol);
|
|
875
|
+
const property = this.#checker.getPropertiesOfType(declared).find((property) => property.name.startsWith(`__@${brand}@`));
|
|
876
|
+
if (property) this.#brands.set(property.name, kind);
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
/**
|
|
880
|
+
* Tests whether a type alias is declared by a registered macro module. Such a type describes a
|
|
881
|
+
* macro use or declaration, not an author's widened asset.
|
|
882
|
+
*
|
|
883
|
+
* @param type - Type from this decoder's checker snapshot.
|
|
884
|
+
* @returns Whether the alias symbol's module was inspected by {@link register}.
|
|
885
|
+
*/
|
|
886
|
+
#declaredByMacro(type) {
|
|
887
|
+
const module = type.getAliasSymbol()?.getParent();
|
|
888
|
+
return !!module && this.#modules.has(module.id);
|
|
889
|
+
}
|
|
890
|
+
/**
|
|
891
|
+
* Resolves a checker type to finite candidates from a single asset family.
|
|
892
|
+
*
|
|
893
|
+
* @param type - Type of a probed expression from the current checker snapshot.
|
|
894
|
+
* @param recognitionOnly - True skips checks for widened asset types when only macro recognition is needed.
|
|
895
|
+
* @returns Finite candidates, a confirmed non-asset, an object type that may hold a widened
|
|
896
|
+
* asset, or an unverified value whose declarations cannot be determined.
|
|
897
|
+
*/
|
|
898
|
+
decode(type, recognitionOnly) {
|
|
899
|
+
if (type.flags & (TypeFlags.Any | TypeFlags.Unknown)) return { kind: "unverified" };
|
|
900
|
+
const constituents = type.isUnionType() ? type.getTypes() : [type];
|
|
901
|
+
const values = [];
|
|
902
|
+
let family;
|
|
903
|
+
let recognized = false;
|
|
904
|
+
let valid = true;
|
|
905
|
+
let finite = true;
|
|
906
|
+
for (const constituent of constituents) {
|
|
907
|
+
if (constituent.flags & primitiveTypeFlags) {
|
|
908
|
+
valid = false;
|
|
909
|
+
continue;
|
|
910
|
+
}
|
|
911
|
+
let kind;
|
|
912
|
+
let identityType;
|
|
913
|
+
const style = this.#property(constituent, "data-__stillwindStyleIdentity");
|
|
914
|
+
if (style) {
|
|
915
|
+
kind = "style";
|
|
916
|
+
identityType = this.#checker.getTypeOfSymbol(style);
|
|
917
|
+
} else for (const brand of this.#allProperties(constituent)) {
|
|
918
|
+
const candidateKind = this.#brands.get(brand.name);
|
|
919
|
+
if (!candidateKind) continue;
|
|
920
|
+
const callable = candidateKind === "viewTransition" ? this.#property(constituent, "for") : void 0;
|
|
921
|
+
const method = callable && this.#checker.getTypeOfSymbol(callable);
|
|
922
|
+
if (!(candidateKind === "viewTransition" ? method && this.#checker.getSignaturesOfType(method, SignatureKind.Call).length > 0 : this.#checker.getSignaturesOfType(constituent, SignatureKind.Call).length > 0)) continue;
|
|
923
|
+
kind = candidateKind;
|
|
924
|
+
identityType = this.#checker.getTypeOfSymbol(brand);
|
|
925
|
+
if (kind === "ref" && identityType) {
|
|
926
|
+
const ref = this.#property(identityType, "ref");
|
|
927
|
+
identityType = ref && this.#checker.getTypeOfSymbol(ref);
|
|
928
|
+
}
|
|
929
|
+
break;
|
|
930
|
+
}
|
|
931
|
+
const name = (constituent.getAliasSymbol() ?? constituent.getSymbol())?.name;
|
|
932
|
+
recognized ||= !!kind || !!name && /^Style(?:Result|Ref|Keyframes|ViewTransition)$/.test(name);
|
|
933
|
+
if (!kind) {
|
|
934
|
+
valid = false;
|
|
935
|
+
continue;
|
|
936
|
+
}
|
|
937
|
+
if (family && family !== kind) {
|
|
938
|
+
valid = false;
|
|
939
|
+
continue;
|
|
940
|
+
}
|
|
941
|
+
family = kind;
|
|
942
|
+
const candidates = knownIdentities(identityType, this.#identities, kind);
|
|
943
|
+
if (candidates === "mismatch") valid = false;
|
|
944
|
+
else if (candidates === "unknown") finite = false;
|
|
945
|
+
else values.push(...candidates);
|
|
946
|
+
}
|
|
947
|
+
if (valid && family === "style" && !finite) return {
|
|
948
|
+
kind: "asset",
|
|
949
|
+
value: {
|
|
950
|
+
kind: "styles",
|
|
951
|
+
value: {
|
|
952
|
+
kind: "style",
|
|
953
|
+
candidates: { kind: "universe" }
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
};
|
|
957
|
+
if (!valid || !family || values.length === 0) {
|
|
958
|
+
if (recognized) return { kind: "unverified" };
|
|
959
|
+
return { kind: !recognitionOnly && constituents.some((constituent) => !(constituent.flags & primitiveTypeFlags) && !this.#declaredByMacro(constituent) && (this.#producers.length === 0 || this.#producers.some((producer) => this.#checker.isTypeAssignableTo(producer, constituent)))) ? "unbranded" : "nonAsset" };
|
|
960
|
+
}
|
|
961
|
+
return {
|
|
962
|
+
kind: "asset",
|
|
963
|
+
value: {
|
|
964
|
+
kind: {
|
|
965
|
+
style: "styles",
|
|
966
|
+
ref: "refs",
|
|
967
|
+
keyframes: "keyframes",
|
|
968
|
+
viewTransition: "viewTransitions"
|
|
969
|
+
}[family],
|
|
970
|
+
value: symbolic(family, values)
|
|
971
|
+
}
|
|
972
|
+
};
|
|
973
|
+
}
|
|
974
|
+
};
|
|
975
|
+
// src/semantics/node/service.ts
|
|
976
|
+
/**
|
|
977
|
+
* Collects declaration facts with a reusable Node checker. Close the service after pending queries finish.
|
|
978
|
+
*/
|
|
979
|
+
var TypeScriptFactsService = class {
|
|
980
|
+
/** Project inputs retained until setProjectSources replaces them. Queries select a subset. */
|
|
981
|
+
#installed;
|
|
982
|
+
/** Checker buffers prepared from the installed project inputs. */
|
|
983
|
+
#prepared;
|
|
984
|
+
/**
|
|
985
|
+
* Whether close has been requested. Subsequent collections reject and repeated close calls do
|
|
986
|
+
* nothing.
|
|
987
|
+
*/
|
|
988
|
+
#closed = false;
|
|
989
|
+
/** Checker process and snapshot caches owned by this service. */
|
|
990
|
+
#checker;
|
|
991
|
+
/** Paths observed by disk reads and existence checks, including missing paths and overlay checks. */
|
|
992
|
+
dependencies;
|
|
993
|
+
/**
|
|
994
|
+
* Live cumulative counters updated by this service. Consumers needing a stable report must copy
|
|
995
|
+
* their values.
|
|
996
|
+
*/
|
|
997
|
+
stats;
|
|
998
|
+
/**
|
|
999
|
+
* Creates a service and starts its checker process without opening a snapshot.
|
|
1000
|
+
*
|
|
1001
|
+
* @param environment - Fixed project root and TypeScript settings.
|
|
1002
|
+
* @throws If the checker process cannot start.
|
|
1003
|
+
*/
|
|
1004
|
+
constructor(environment) {
|
|
1005
|
+
this.#checker = new NodeChecker(environment);
|
|
1006
|
+
this.dependencies = this.#checker.dependencies;
|
|
1007
|
+
this.stats = this.#checker.stats;
|
|
1008
|
+
}
|
|
1009
|
+
/**
|
|
1010
|
+
* Keeps project inputs for later queries and clears prepared checker buffers.
|
|
1011
|
+
*
|
|
1012
|
+
* @param sources - Prepared project sources, retained by reference until replaced.
|
|
1013
|
+
* @param assets - Declarations grouped by compiler module ID, retained with the sources.
|
|
1014
|
+
* @param inputs - File overlays and ambient declarations. Omission supplies no extra files.
|
|
1015
|
+
* Do not mutate these inputs while they are installed. Queries select their own probes and sources.
|
|
1016
|
+
*/
|
|
1017
|
+
setProjectSources(sources, assets, inputs = {}) {
|
|
1018
|
+
this.#installed = {
|
|
1019
|
+
sources,
|
|
1020
|
+
assets,
|
|
1021
|
+
inputs
|
|
1022
|
+
};
|
|
1023
|
+
this.#prepared = void 0;
|
|
1024
|
+
}
|
|
1025
|
+
/**
|
|
1026
|
+
* Collects finite declaration candidates for original-coordinate probes.
|
|
1027
|
+
*
|
|
1028
|
+
* Queries reuse the current snapshot when files have not changed. Mapping, assignment, and
|
|
1029
|
+
* identity errors throw TypeFactsError. Other checker failures restart the API and retry once.
|
|
1030
|
+
* Only diagnostics about Stillwind declaration contracts affect the result.
|
|
1031
|
+
*
|
|
1032
|
+
* @param sources - Prepared sources and original-byte probes, with validated projection
|
|
1033
|
+
* correspondences where needed.
|
|
1034
|
+
* @param assetsByModuleId - Declaration records keyed by compiler module identity.
|
|
1035
|
+
* @param inputs - Overlays and ambient declarations for an independent query. Omission supplies none.
|
|
1036
|
+
* When project sources are installed, preparation uses their installed inputs instead.
|
|
1037
|
+
* @returns Facts keyed by compiler module identity. Facts for the same original range are
|
|
1038
|
+
* deduplicated across buffers. Conflicting values throw. Known non-asset types produce null facts.
|
|
1039
|
+
* Unresolved recognition-only probes produce no fact.
|
|
1040
|
+
* @throws If the service is closed, preparation or checker contracts fail, or the API fails. A
|
|
1041
|
+
* failed query retry throws an AggregateError containing both query failures.
|
|
1042
|
+
*/
|
|
1043
|
+
collect(sources, assetsByModuleId, inputs = {}) {
|
|
1044
|
+
return this.#collect(sources, assetsByModuleId, inputs, false).facts;
|
|
1045
|
+
}
|
|
1046
|
+
/**
|
|
1047
|
+
* Collects verified facts, reusing the snapshot when files have not changed.
|
|
1048
|
+
*
|
|
1049
|
+
* @param sources - Prepared sources and original UTF-8 probes with validated checker correspondences.
|
|
1050
|
+
* @param assetsByModuleId - Declaration records grouped by compiler module identity.
|
|
1051
|
+
* @param inputs - Overlays and ambient declarations for an independent query. Omission supplies none.
|
|
1052
|
+
* When project sources are installed, preparation uses their installed inputs instead.
|
|
1053
|
+
* @returns Verified facts and unavailable original ranges. Unavailable queries do not discard
|
|
1054
|
+
* facts collected for other expressions.
|
|
1055
|
+
* @throws If the service is closed, project preparation fails, facts conflict, or checker restart and retry fail.
|
|
1056
|
+
*/
|
|
1057
|
+
collectAvailable(sources, assetsByModuleId, inputs = {}) {
|
|
1058
|
+
return this.#collect(sources, assetsByModuleId, inputs, true);
|
|
1059
|
+
}
|
|
1060
|
+
/**
|
|
1061
|
+
* Resolves authored imports and exports using module symbols in the selected TypeScript settings.
|
|
1062
|
+
*
|
|
1063
|
+
* @param sources - Prepared sources whose checker buffers contain the authored module requests.
|
|
1064
|
+
* Independent resolution ignores probes. An installed project also prepares its probes for later queries.
|
|
1065
|
+
* @param assetsByModuleId - Declaration records used to expose generated helper types.
|
|
1066
|
+
* @param inputs - Overlays and ambient declarations for independent resolution. Omission supplies none.
|
|
1067
|
+
* An installed project uses the inputs supplied by setProjectSources.
|
|
1068
|
+
* @returns Request-to-identity maps grouped by source resolver identity. Prepared checker paths
|
|
1069
|
+
* map back to resolver identities. Other resolutions retain checker filenames, including declarations.
|
|
1070
|
+
* Requests without a matching module symbol are omitted.
|
|
1071
|
+
* @throws If the service is closed, project preparation fails, or checker resolution fails.
|
|
1072
|
+
*/
|
|
1073
|
+
resolveModules(sources, assetsByModuleId, inputs = {}) {
|
|
1074
|
+
if (this.#closed) throw new Error("TypeScript facts service is closed");
|
|
1075
|
+
const inventory = this.#installed?.sources ?? sources;
|
|
1076
|
+
const prepared = this.#prepare(sources, assetsByModuleId, inputs, true);
|
|
1077
|
+
const project = this.#checker.updateProject(prepared);
|
|
1078
|
+
const result = /* @__PURE__ */ new Map();
|
|
1079
|
+
for (const mapping of prepared.mappings) {
|
|
1080
|
+
const file = project.program.getSourceFile(mapping.id);
|
|
1081
|
+
if (!file) continue;
|
|
1082
|
+
const resolutions = result.get(mapping.source.resolverId) ?? /* @__PURE__ */ new Map();
|
|
1083
|
+
result.set(mapping.source.resolverId, resolutions);
|
|
1084
|
+
visit(file, (node) => {
|
|
1085
|
+
if (!(isImportDeclaration(node) || isExportDeclaration(node)) || !node.moduleSpecifier || !isStringLiteral(node.moduleSpecifier)) return;
|
|
1086
|
+
const declaration = project.checker.getSymbolAtLocation(node.moduleSpecifier)?.declarations.find((declaration) => {
|
|
1087
|
+
const node = declaration.resolve(project);
|
|
1088
|
+
return node !== void 0 && (isSourceFile(node) || node.getSourceFile().isDeclarationFile);
|
|
1089
|
+
});
|
|
1090
|
+
if (declaration) {
|
|
1091
|
+
const fileName = declaration.resolve(project).getSourceFile().fileName;
|
|
1092
|
+
const original = inventory.find((source) => normalize(checkerId(source)) === normalize(fileName));
|
|
1093
|
+
const key = `${node.moduleSpecifier.getStart(file)}:${node.moduleSpecifier.end}`;
|
|
1094
|
+
resolutions.set(mapping.moduleSpecifiers.get(key) ?? node.moduleSpecifier.text, original?.resolverId ?? fileName);
|
|
1095
|
+
}
|
|
1096
|
+
});
|
|
1097
|
+
}
|
|
1098
|
+
return result;
|
|
1099
|
+
}
|
|
1100
|
+
/**
|
|
1101
|
+
* Prepares one request and retries an unexpected checker failure once with a clean API.
|
|
1102
|
+
*
|
|
1103
|
+
* @param sources - Prepared sources and original UTF-8 probes.
|
|
1104
|
+
* @param assetsByModuleId - Declaration records grouped by compiler identity.
|
|
1105
|
+
* @param inputs - Complete overlays and ambient declarations for the request.
|
|
1106
|
+
* @param available - Whether unavailable facts are recorded instead of rejecting the request.
|
|
1107
|
+
* @returns Collected facts and unavailable ranges from the successful attempt.
|
|
1108
|
+
* @throws If preparation fails, a TypeFactsError occurs, restart fails, or both query attempts fail.
|
|
1109
|
+
*/
|
|
1110
|
+
#collect(sources, assetsByModuleId, inputs, available) {
|
|
1111
|
+
if (this.#closed) throw new Error("TypeScript facts service is closed");
|
|
1112
|
+
if (this.#installed) {
|
|
1113
|
+
const updated = withRequestedProbes(this.#installed.sources, sources);
|
|
1114
|
+
if (updated !== this.#installed.sources) {
|
|
1115
|
+
this.#installed = {
|
|
1116
|
+
...this.#installed,
|
|
1117
|
+
sources: updated
|
|
1118
|
+
};
|
|
1119
|
+
this.#prepared = void 0;
|
|
1120
|
+
}
|
|
1121
|
+
}
|
|
1122
|
+
const full = this.#prepare(sources, assetsByModuleId, inputs);
|
|
1123
|
+
const selected = new Set(sources.map((source) => source.resolverId));
|
|
1124
|
+
const mappings = full.mappings.filter((mapping) => selected.has(mapping.source.resolverId));
|
|
1125
|
+
const prepared = {
|
|
1126
|
+
...full,
|
|
1127
|
+
mappings,
|
|
1128
|
+
identities: new Map(mappings.flatMap((mapping) => [...mapping.identities]))
|
|
1129
|
+
};
|
|
1130
|
+
try {
|
|
1131
|
+
return this.#collectPrepared(prepared, available);
|
|
1132
|
+
} catch (firstError) {
|
|
1133
|
+
if (firstError instanceof TypeFactsError) throw firstError;
|
|
1134
|
+
this.stats.restarts += 1;
|
|
1135
|
+
this.#restartApi();
|
|
1136
|
+
try {
|
|
1137
|
+
return this.#collectPrepared(prepared, available);
|
|
1138
|
+
} catch (retryError) {
|
|
1139
|
+
throw new AggregateError([firstError, retryError], `TypeScript 7 checker failed before and after a clean restart: ${String(retryError)}`);
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
/**
|
|
1144
|
+
* Reuses prepared project inputs or prepares only the requested sources if project preparation fails.
|
|
1145
|
+
*
|
|
1146
|
+
* @param sources - Requested sources to use when no project is installed or preparation fails.
|
|
1147
|
+
* @param assets - Declarations grouped by module ID for those sources.
|
|
1148
|
+
* @param inputs - Overlays and ambient declarations for the requested sources.
|
|
1149
|
+
* @param resolutionOnly - True omits probes when preparing only the requested sources for import resolution.
|
|
1150
|
+
* @returns Prepared checker files and mappings. Successful project preparation is cached.
|
|
1151
|
+
* @throws If the requested sources or their TypeScript configuration cannot be prepared.
|
|
1152
|
+
*/
|
|
1153
|
+
#prepare(sources, assets, inputs, resolutionOnly = false) {
|
|
1154
|
+
if (this.#installed && this.#prepared) return this.#prepared;
|
|
1155
|
+
if (this.#installed) try {
|
|
1156
|
+
this.#prepared = this.#checker.prepareProject(this.#installed.sources, this.#installed.assets, this.#installed.inputs);
|
|
1157
|
+
return this.#prepared;
|
|
1158
|
+
} catch {}
|
|
1159
|
+
return this.#checker.prepareProject(resolutionOnly ? sources.map((source) => ({
|
|
1160
|
+
...source,
|
|
1161
|
+
probes: []
|
|
1162
|
+
})) : sources, assets, inputs);
|
|
1163
|
+
}
|
|
1164
|
+
/**
|
|
1165
|
+
* Marks the service closed, disposes its retained snapshot, and closes the checker API. Repeated
|
|
1166
|
+
* calls return without further work.
|
|
1167
|
+
*
|
|
1168
|
+
* @throws If snapshot disposal or API cleanup fails.
|
|
1169
|
+
*/
|
|
1170
|
+
close() {
|
|
1171
|
+
if (this.#closed) return;
|
|
1172
|
+
this.#closed = true;
|
|
1173
|
+
this.#prepared = void 0;
|
|
1174
|
+
this.#checker.close();
|
|
1175
|
+
}
|
|
1176
|
+
/**
|
|
1177
|
+
* Discards cached disk contents and the retained snapshot while keeping the selected environment.
|
|
1178
|
+
* The next collection opens a new project. Calls after close have no effect.
|
|
1179
|
+
*
|
|
1180
|
+
* @throws If checker cleanup or restart fails.
|
|
1181
|
+
*/
|
|
1182
|
+
invalidate() {
|
|
1183
|
+
if (!this.#closed) this.#restartApi();
|
|
1184
|
+
}
|
|
1185
|
+
/**
|
|
1186
|
+
* Updates the snapshot and collects facts from the prepared checker buffers.
|
|
1187
|
+
*
|
|
1188
|
+
* @param prepared - Virtual files, original-coordinate mappings, and serialized declaration identities.
|
|
1189
|
+
* @param available - Whether contract failures become unverified ranges where recovery is possible.
|
|
1190
|
+
* @returns Deduplicated facts by compiler identity and unverified original UTF-8 ranges.
|
|
1191
|
+
* @throws If snapshot update fails, a checker file is missing, facts conflict, or strict collection fails.
|
|
1192
|
+
*/
|
|
1193
|
+
#collectPrepared(prepared, available) {
|
|
1194
|
+
const project = this.#checker.updateProject(prepared);
|
|
1195
|
+
const unverified = [];
|
|
1196
|
+
const result = /* @__PURE__ */ new Map();
|
|
1197
|
+
const decoder = new AssetTypeDecoder(project.checker, prepared.identities, this.#checker.properties);
|
|
1198
|
+
const producers = [];
|
|
1199
|
+
for (const mapping of prepared.mappings) {
|
|
1200
|
+
const file = project.program.getSourceFile(mapping.id);
|
|
1201
|
+
if (!file) continue;
|
|
1202
|
+
producers.push(...this.#checker.expressions(file).filter((node) => isCallExpression(node) && mapping.producers.has(`${node.getStart(file)}:${node.end}`)));
|
|
1203
|
+
}
|
|
1204
|
+
for (const type of this.#checker.types(project.checker, producers)) if (type) decoder.register(type);
|
|
1205
|
+
for (const mapping of prepared.mappings) {
|
|
1206
|
+
const sourceFile = project.program.getSourceFile(mapping.id);
|
|
1207
|
+
if (!sourceFile) throw new Error(`TypeScript 7 omitted ${mapping.id}`);
|
|
1208
|
+
let diagnostics = this.#checker.diagnostics.get(mapping.id);
|
|
1209
|
+
if (!diagnostics) {
|
|
1210
|
+
diagnostics = [...project.program.getSyntacticDiagnostics(mapping.id), ...project.program.getSemanticDiagnostics(mapping.id)];
|
|
1211
|
+
this.#checker.diagnostics.set(mapping.id, diagnostics);
|
|
1212
|
+
}
|
|
1213
|
+
const diagnostic = diagnostics.find((d) => !producerArgumentDiagnostic(d, sourceFile, mapping) && /stillwind\/v1:|StyleResult|StyleRef|StyleKeyframes|StyleViewTransition|__stillwindDeclarationIdentity|data-__stillwindStyleIdentity/.test(diagnosticText(d)));
|
|
1214
|
+
if (diagnostic) {
|
|
1215
|
+
const start = mapping.originalOffset(diagnostic.pos) ?? void 0;
|
|
1216
|
+
const end = mapping.originalOffset(diagnostic.end, true) ?? void 0;
|
|
1217
|
+
const message = diagnosticText(diagnostic).replace(/stillwind\/v1:[A-Za-z0-9_-]+/g, "declaration identity");
|
|
1218
|
+
const error = new TypeFactsError(mapping.source.moduleId, start, end, "assignment", `TS${diagnostic.code}: ${message} Preserve declaration candidates with an explicit union or a generic parameter.`);
|
|
1219
|
+
if (!available) throw error;
|
|
1220
|
+
unverified.push({
|
|
1221
|
+
moduleId: error.moduleId,
|
|
1222
|
+
start,
|
|
1223
|
+
end,
|
|
1224
|
+
reason: error.message
|
|
1225
|
+
});
|
|
1226
|
+
}
|
|
1227
|
+
const facts = factsForSource(sourceFile, mapping, decoder, this.#checker.expressions(sourceFile), (nodes) => this.#checker.types(project.checker, nodes), available ? unverified : void 0);
|
|
1228
|
+
const previous = result.get(mapping.source.moduleId) ?? [];
|
|
1229
|
+
for (const fact of facts) {
|
|
1230
|
+
const existing = previous.find((value) => value.start === fact.start && value.end === fact.end);
|
|
1231
|
+
if (existing && JSON.stringify(existing.value) !== JSON.stringify(fact.value)) throw new TypeFactsError(mapping.source.moduleId, fact.start, fact.end, "checker", "Ambiguous checker results for this original expression");
|
|
1232
|
+
if (!existing) previous.push(fact);
|
|
1233
|
+
}
|
|
1234
|
+
result.set(mapping.source.moduleId, previous);
|
|
1235
|
+
}
|
|
1236
|
+
return {
|
|
1237
|
+
facts: result,
|
|
1238
|
+
unverified
|
|
1239
|
+
};
|
|
1240
|
+
}
|
|
1241
|
+
/**
|
|
1242
|
+
* Clears prepared inputs and replaces the checker process after invalidation or query failure.
|
|
1243
|
+
*/
|
|
1244
|
+
#restartApi() {
|
|
1245
|
+
this.#prepared = void 0;
|
|
1246
|
+
this.#checker.restart();
|
|
1247
|
+
}
|
|
1248
|
+
};
|
|
1249
|
+
// src/project/diagnostic-map.ts
|
|
1250
|
+
/**
|
|
1251
|
+
* Maps reports through upstream loader maps to their original source documents.
|
|
1252
|
+
*
|
|
1253
|
+
* @param reports - Reports with byte offsets and UTF-16 locations in prepared source documents.
|
|
1254
|
+
* @param sources - Prepared sources whose document metadata supplies upstream maps.
|
|
1255
|
+
* @param read - Reads original file text when the map has no embedded content, or when a label
|
|
1256
|
+
* needs a document-level fallback. Identities passed here are absolute file paths.
|
|
1257
|
+
* @returns Reports with original positions and content fingerprints. Unmappable labels become
|
|
1258
|
+
* document-scoped. An action is retained only when every edit maps to an unchanged text range.
|
|
1259
|
+
* @throws If required source reads or upstream map decoding fail.
|
|
1260
|
+
*/
|
|
1261
|
+
async function mapAnalysisReports(reports, sources, read) {
|
|
1262
|
+
const documents = new Map(sources.map((source) => [source.document.uri, source]));
|
|
1263
|
+
/**
|
|
1264
|
+
* Maps a location when both endpoints identify exact segments in the same original file.
|
|
1265
|
+
* @param location - Prepared document range with zero-based lines and UTF-16 columns.
|
|
1266
|
+
* @param exact - Whether the mapped and prepared ranges must contain identical text.
|
|
1267
|
+
* @returns The original location when no upstream map exists, a mapped location, or undefined
|
|
1268
|
+
* when endpoints, source identity, bounds, or required text equality cannot be established.
|
|
1269
|
+
* @throws If map decoding or a required original file read fails.
|
|
1270
|
+
*/
|
|
1271
|
+
const mapLocation = async (location, exact) => {
|
|
1272
|
+
const source = documents.get(location.uri);
|
|
1273
|
+
if (!source?.document.upstreamMap) return location;
|
|
1274
|
+
const trace = new TraceMap(source.document.upstreamMap, path.isAbsolute(cleanModuleId(source.resolverId)) ? pathToFileURL(cleanModuleId(source.resolverId)).href : void 0);
|
|
1275
|
+
const start = originalPositionFor(trace, {
|
|
1276
|
+
line: location.startLine + 1,
|
|
1277
|
+
column: location.startColumn
|
|
1278
|
+
});
|
|
1279
|
+
const end = originalPositionFor(trace, {
|
|
1280
|
+
line: location.endLine + 1,
|
|
1281
|
+
column: location.endColumn
|
|
1282
|
+
});
|
|
1283
|
+
const mappings = decodedMappings(trace);
|
|
1284
|
+
/**
|
|
1285
|
+
* Checks whether a generated position has a segment containing an original source position.
|
|
1286
|
+
* @param line - Zero-based generated line.
|
|
1287
|
+
* @param column - Zero-based UTF-16 column that must equal a segment start.
|
|
1288
|
+
* @returns Whether a matching segment exists, or undefined when the line has no mappings.
|
|
1289
|
+
*/
|
|
1290
|
+
const endpoint = (line, column) => mappings[line]?.some((segment) => segment.length > 1 && segment[0] === column);
|
|
1291
|
+
if (!endpoint(location.startLine, location.startColumn) || !endpoint(location.endLine, location.endColumn)) return;
|
|
1292
|
+
if (!start.source || start.source !== end.source || start.line === null || end.line === null || start.column === null || end.column === null) return;
|
|
1293
|
+
const uri = start.source.startsWith("file:") ? start.source : path.isAbsolute(start.source) ? pathToFileURL(start.source).href : void 0;
|
|
1294
|
+
if (!uri) return;
|
|
1295
|
+
const code = sourceContentFor(trace, start.source) ?? await read(fileURLToPath(uri));
|
|
1296
|
+
/**
|
|
1297
|
+
* Converts an original map position to an offset in the captured text.
|
|
1298
|
+
* @param line - One-based original line.
|
|
1299
|
+
* @param column - Nonnegative UTF-16 column that excludes a trailing carriage return.
|
|
1300
|
+
* @returns A UTF-16 offset, or undefined when the line or column exceeds the text bounds.
|
|
1301
|
+
*/
|
|
1302
|
+
const offset = (line, column) => {
|
|
1303
|
+
const lines = code.split("\n");
|
|
1304
|
+
if (line < 1 || line > lines.length || column > lines[line - 1].replace(/\r$/, "").length) return;
|
|
1305
|
+
return lines.slice(0, line - 1).reduce((sum, text) => sum + text.length + 1, 0) + column;
|
|
1306
|
+
};
|
|
1307
|
+
const startUtf16 = offset(start.line, start.column);
|
|
1308
|
+
const endUtf16 = offset(end.line, end.column);
|
|
1309
|
+
if (startUtf16 === void 0 || endUtf16 === void 0 || endUtf16 < startUtf16 || exact && code.slice(startUtf16, endUtf16) !== source.document.code.slice(location.startUtf16, location.endUtf16)) return;
|
|
1310
|
+
return {
|
|
1311
|
+
uri,
|
|
1312
|
+
revision: fingerprint(code),
|
|
1313
|
+
start: Buffer.byteLength(code.slice(0, startUtf16)),
|
|
1314
|
+
end: Buffer.byteLength(code.slice(0, endUtf16)),
|
|
1315
|
+
startUtf16,
|
|
1316
|
+
endUtf16,
|
|
1317
|
+
startLine: start.line - 1,
|
|
1318
|
+
startColumn: start.column,
|
|
1319
|
+
endLine: end.line - 1,
|
|
1320
|
+
endColumn: end.column
|
|
1321
|
+
};
|
|
1322
|
+
};
|
|
1323
|
+
/**
|
|
1324
|
+
* Maps a label or limits it to document scope when its range cannot be mapped.
|
|
1325
|
+
* @param value - Label in a prepared document. The input object is not mutated.
|
|
1326
|
+
* @returns A copied label. A readable file fallback receives a current fingerprint and zero range.
|
|
1327
|
+
* @throws If map decoding or a required file read fails.
|
|
1328
|
+
*/
|
|
1329
|
+
const label = async (value) => {
|
|
1330
|
+
const mapped = await mapLocation(value.location, false);
|
|
1331
|
+
if (mapped) return {
|
|
1332
|
+
...value,
|
|
1333
|
+
location: mapped
|
|
1334
|
+
};
|
|
1335
|
+
const source = documents.get(value.location.uri);
|
|
1336
|
+
const file = source && cleanModuleId(source.resolverId);
|
|
1337
|
+
if (file && path.isAbsolute(file)) {
|
|
1338
|
+
const code = await read(file);
|
|
1339
|
+
return {
|
|
1340
|
+
...value,
|
|
1341
|
+
scope: "document",
|
|
1342
|
+
location: {
|
|
1343
|
+
...value.location,
|
|
1344
|
+
uri: pathToFileURL(file).href,
|
|
1345
|
+
revision: fingerprint(code),
|
|
1346
|
+
start: 0,
|
|
1347
|
+
end: 0,
|
|
1348
|
+
startUtf16: 0,
|
|
1349
|
+
endUtf16: 0,
|
|
1350
|
+
startLine: 0,
|
|
1351
|
+
endLine: 0,
|
|
1352
|
+
startColumn: 0,
|
|
1353
|
+
endColumn: 0
|
|
1354
|
+
}
|
|
1355
|
+
};
|
|
1356
|
+
}
|
|
1357
|
+
return {
|
|
1358
|
+
...value,
|
|
1359
|
+
scope: "document"
|
|
1360
|
+
};
|
|
1361
|
+
};
|
|
1362
|
+
return Promise.all(reports.map(async (report) => {
|
|
1363
|
+
const actions = [];
|
|
1364
|
+
for (const action of report.actions) {
|
|
1365
|
+
const edits = await Promise.all(action.edits.map(async (edit) => {
|
|
1366
|
+
const location = await mapLocation(edit.location, true);
|
|
1367
|
+
return location && {
|
|
1368
|
+
...edit,
|
|
1369
|
+
location
|
|
1370
|
+
};
|
|
1371
|
+
}));
|
|
1372
|
+
if (edits.every((edit) => edit !== void 0)) actions.push({
|
|
1373
|
+
...action,
|
|
1374
|
+
edits
|
|
1375
|
+
});
|
|
1376
|
+
}
|
|
1377
|
+
return {
|
|
1378
|
+
...report,
|
|
1379
|
+
primary: await label(report.primary),
|
|
1380
|
+
related: await Promise.all(report.related.map(label)),
|
|
1381
|
+
actions
|
|
1382
|
+
};
|
|
1383
|
+
}));
|
|
1384
|
+
}
|
|
1385
|
+
// src/project/analysis/host.ts
|
|
1386
|
+
/**
|
|
1387
|
+
* Loads CSS and tracks the host dependencies that require a fresh design system.
|
|
1388
|
+
*/
|
|
1389
|
+
var AnalysisCss = class {
|
|
1390
|
+
/** Files read by CSS or plugins. Open-buffer changes to these files reload CSS. */
|
|
1391
|
+
#dependencies = /* @__PURE__ */ new Set();
|
|
1392
|
+
/** Delegates CSS operations to the host and records watched dependencies. */
|
|
1393
|
+
#css;
|
|
1394
|
+
/** CSS loader retained until a CSS update or explicit invalidation. */
|
|
1395
|
+
#loader;
|
|
1396
|
+
/** Session that uses the retained loader. Replaced when CSS changes. */
|
|
1397
|
+
#session;
|
|
1398
|
+
/** Query-only CSS graph, rebuilt after CSS changes and kept separate from strict analysis. */
|
|
1399
|
+
#editorCss;
|
|
1400
|
+
/** Identities that the retained loader marked for stylesheet lint, in load order. */
|
|
1401
|
+
#lintSources = [];
|
|
1402
|
+
/**
|
|
1403
|
+
* Plugin runtime of the retained loader. A CSS update keeps it as the previous runtime of the
|
|
1404
|
+
* next load, so definitions of unchanged plugins survive.
|
|
1405
|
+
*/
|
|
1406
|
+
#plugins;
|
|
1407
|
+
/** Host operations are called only inside the project's serialized transactions. */
|
|
1408
|
+
#host;
|
|
1409
|
+
/**
|
|
1410
|
+
* Wraps CSS watching without loading files.
|
|
1411
|
+
* @param host - Host owned by the analysis project. Calls retain the host as their receiver.
|
|
1412
|
+
*/
|
|
1413
|
+
constructor(host) {
|
|
1414
|
+
this.#host = host;
|
|
1415
|
+
this.#css = {
|
|
1416
|
+
resolve: (specifier, importer) => host.css.resolve(specifier, importer),
|
|
1417
|
+
read: (id) => host.css.read(id),
|
|
1418
|
+
documentUri: (id) => host.css.documentUri(id),
|
|
1419
|
+
sourceMapSource: (id) => host.css.sourceMapSource(id),
|
|
1420
|
+
plugins: host.css.plugins,
|
|
1421
|
+
lint: host.css.lint?.bind(host.css),
|
|
1422
|
+
watch: (id) => {
|
|
1423
|
+
this.#dependencies.add(id);
|
|
1424
|
+
host.css.watch(id);
|
|
1425
|
+
}
|
|
1426
|
+
};
|
|
1427
|
+
}
|
|
1428
|
+
/** Current strict loader, or undefined before loading or after invalidation. */
|
|
1429
|
+
get loader() {
|
|
1430
|
+
return this.#loader;
|
|
1431
|
+
}
|
|
1432
|
+
/** Session that uses the strict loader, or undefined until load succeeds. */
|
|
1433
|
+
get session() {
|
|
1434
|
+
return this.#session;
|
|
1435
|
+
}
|
|
1436
|
+
/** Plugin runtime of the latest successful load. Kept across CSS changes for reuse. */
|
|
1437
|
+
get plugins() {
|
|
1438
|
+
return this.#plugins;
|
|
1439
|
+
}
|
|
1440
|
+
/** Stylesheets marked for lint by the last strict load, in load order. */
|
|
1441
|
+
get lintSources() {
|
|
1442
|
+
return this.#lintSources;
|
|
1443
|
+
}
|
|
1444
|
+
/**
|
|
1445
|
+
* Checks whether an open-buffer edit requires reloading CSS.
|
|
1446
|
+
*
|
|
1447
|
+
* @param id - Absolute path of the changed document.
|
|
1448
|
+
* @returns Whether it is a stylesheet or a dependency watched by CSS or a plugin.
|
|
1449
|
+
*/
|
|
1450
|
+
affects(id) {
|
|
1451
|
+
return isStylesheet(id) || [...this.#dependencies].some((file) => sameFile(file, id));
|
|
1452
|
+
}
|
|
1453
|
+
/**
|
|
1454
|
+
* Discards loaders and the native session while keeping plugins available for the next load.
|
|
1455
|
+
*/
|
|
1456
|
+
invalidate() {
|
|
1457
|
+
this.#loader = void 0;
|
|
1458
|
+
this.#session = void 0;
|
|
1459
|
+
this.#editorCss = void 0;
|
|
1460
|
+
}
|
|
1461
|
+
/**
|
|
1462
|
+
* Discards a failed plugin runtime and the loaders that depend on it before individual analysis retries.
|
|
1463
|
+
*/
|
|
1464
|
+
discardPlugins() {
|
|
1465
|
+
this.invalidate();
|
|
1466
|
+
this.#plugins = void 0;
|
|
1467
|
+
}
|
|
1468
|
+
/**
|
|
1469
|
+
* Loads the configured CSS graph once until CSS invalidation clears it.
|
|
1470
|
+
*
|
|
1471
|
+
* @returns The retained loader with compiler options applied.
|
|
1472
|
+
* @throws If resolving, reading, or loading the CSS graph fails.
|
|
1473
|
+
*/
|
|
1474
|
+
async load() {
|
|
1475
|
+
if (!this.#loader) {
|
|
1476
|
+
const css = path.resolve(this.#host.root, cssEntrypoint(this.#host.config));
|
|
1477
|
+
const loaded = await loadCssGraph(css, compilerOptions(this.#host.config), this.#css, void 0, void 0, this.#pluginInputs());
|
|
1478
|
+
this.#loader = loaded.loader;
|
|
1479
|
+
this.#lintSources = loaded.lintSources;
|
|
1480
|
+
this.#plugins = loaded.plugins;
|
|
1481
|
+
this.#session = new NativeProjectSession(this.#loader, false, "development", this.#host.config.naming);
|
|
1482
|
+
attachPlugins(this.#session, this.#plugins, this.#plugins?.generation);
|
|
1483
|
+
}
|
|
1484
|
+
return this.#loader;
|
|
1485
|
+
}
|
|
1486
|
+
/**
|
|
1487
|
+
* Selects the plugins of the project's CSS graph.
|
|
1488
|
+
*
|
|
1489
|
+
* @returns Configured plugins, the project root, and the runtime of the last load.
|
|
1490
|
+
*/
|
|
1491
|
+
#pluginInputs() {
|
|
1492
|
+
return {
|
|
1493
|
+
plugins: this.#host.config.plugins,
|
|
1494
|
+
tailwind: this.#host.config.tailwind,
|
|
1495
|
+
important: this.#host.config.important,
|
|
1496
|
+
root: this.#host.root,
|
|
1497
|
+
previous: this.#plugins
|
|
1498
|
+
};
|
|
1499
|
+
}
|
|
1500
|
+
/**
|
|
1501
|
+
* Loads a query graph from original CSS or recovered definitions, without publishing its reports.
|
|
1502
|
+
*
|
|
1503
|
+
* @returns The cached editor graph, reusing the strict loader when available. Otherwise, a failed
|
|
1504
|
+
* original load is retried with recovered definitions. CSS invalidation clears this cache.
|
|
1505
|
+
* @throws If neither the original nor the recovered CSS graph can be resolved, read, and loaded.
|
|
1506
|
+
*/
|
|
1507
|
+
async editor() {
|
|
1508
|
+
if (!this.#editorCss) {
|
|
1509
|
+
if (this.#loader) this.#editorCss = {
|
|
1510
|
+
loader: this.#loader,
|
|
1511
|
+
resources: [],
|
|
1512
|
+
lintSources: this.#lintSources,
|
|
1513
|
+
recovered: false,
|
|
1514
|
+
plugins: this.#plugins
|
|
1515
|
+
};
|
|
1516
|
+
else this.#editorCss = await loadEditorCssGraph(path.resolve(this.#host.root, cssEntrypoint(this.#host.config)), compilerOptions(this.#host.config), this.#css, this.#pluginInputs());
|
|
1517
|
+
}
|
|
1518
|
+
return this.#editorCss;
|
|
1519
|
+
}
|
|
1520
|
+
/**
|
|
1521
|
+
* Creates a strict stylesheet editor and its lint reports.
|
|
1522
|
+
*
|
|
1523
|
+
* @param entry - Absolute stylesheet path in this host.
|
|
1524
|
+
* @returns Reports for that document and an editor using the same CSS definitions.
|
|
1525
|
+
* @throws If CSS loading, source reading, or plugin catalog loading fails.
|
|
1526
|
+
*/
|
|
1527
|
+
async stylesheet(entry) {
|
|
1528
|
+
const loader = await this.load();
|
|
1529
|
+
const reports = loader.stylesheetReports().filter((report) => {
|
|
1530
|
+
const uri = report.primary.location.uri;
|
|
1531
|
+
return uri.startsWith("file:") ? sameFile(fileURLToPath(uri), entry) : uri === this.#host.css.documentUri(entry);
|
|
1532
|
+
});
|
|
1533
|
+
return {
|
|
1534
|
+
reports,
|
|
1535
|
+
snapshot: new StylesheetEditor(entry, await this.#host.css.read(entry), reports, loader.editorQuery(), this.#host.config, await this.#plugins?.catalog() ?? [], this.#plugins)
|
|
1536
|
+
};
|
|
1537
|
+
}
|
|
1538
|
+
/**
|
|
1539
|
+
* Creates an editor from original CSS, or from recovered definitions when strict loading fails.
|
|
1540
|
+
*
|
|
1541
|
+
* @param entry - Absolute stylesheet path. Files outside the linted CSS graph are skipped.
|
|
1542
|
+
* @returns The editor and whether recovery was needed, or undefined outside the graph.
|
|
1543
|
+
* @throws If CSS recovery, source reading, or plugin catalog loading fails.
|
|
1544
|
+
*/
|
|
1545
|
+
async editorSnapshot(entry) {
|
|
1546
|
+
const graph = await this.editor();
|
|
1547
|
+
if (!graph.lintSources.some((source) => sameFile(source, entry))) return;
|
|
1548
|
+
const reports = graph.recovered ? [] : graph.loader.stylesheetReports().filter((report) => report.primary.location.uri === this.#host.css.documentUri(entry));
|
|
1549
|
+
return {
|
|
1550
|
+
recovered: graph.recovered,
|
|
1551
|
+
snapshot: new StylesheetEditor(entry, await this.#host.css.read(entry), reports, graph.loader.editorQuery(), this.#host.config, await graph.plugins?.catalog() ?? [], graph.plugins)
|
|
1552
|
+
};
|
|
1553
|
+
}
|
|
1554
|
+
};
|
|
1555
|
+
/**
|
|
1556
|
+
* Compares file paths as the host filesystem does.
|
|
1557
|
+
*
|
|
1558
|
+
* @param a - File path resolved against the process working directory when relative.
|
|
1559
|
+
* @param b - File path resolved in the same way.
|
|
1560
|
+
* @returns Whether both paths name the same file, ignoring case on Windows.
|
|
1561
|
+
*/
|
|
1562
|
+
function sameFile(a, b) {
|
|
1563
|
+
/**
|
|
1564
|
+
* Normalizes a path for comparison.
|
|
1565
|
+
*
|
|
1566
|
+
* @param file - File path.
|
|
1567
|
+
* @returns The absolute path, lowercased on Windows.
|
|
1568
|
+
*/
|
|
1569
|
+
const key = (file) => process.platform === "win32" ? path.resolve(file).toLowerCase() : path.resolve(file);
|
|
1570
|
+
return key(a) === key(b);
|
|
1571
|
+
}
|
|
1572
|
+
// src/project/analysis/project.ts
|
|
1573
|
+
/**
|
|
1574
|
+
* Owns open buffers, checker queries, and serialized analysis for one host.
|
|
1575
|
+
*/
|
|
1576
|
+
var AnalysisProject = class {
|
|
1577
|
+
/** Prepared sources shared by analyses of different entries. */
|
|
1578
|
+
#compilation = new CompilationProject();
|
|
1579
|
+
/** CSS state and dependencies owned by this project. */
|
|
1580
|
+
#css;
|
|
1581
|
+
/** Owned host. The project serializes its operations and closes it during cleanup. */
|
|
1582
|
+
host;
|
|
1583
|
+
/** Optional factory used once when semantic analysis first needs a backend. */
|
|
1584
|
+
#backend;
|
|
1585
|
+
/** Unsaved original buffers keyed by absolute path and captured before each queued operation. */
|
|
1586
|
+
#documents = /* @__PURE__ */ new Map();
|
|
1587
|
+
/** Editor snapshots retained by entry identity until their project revision changes. */
|
|
1588
|
+
#editors = /* @__PURE__ */ new Map();
|
|
1589
|
+
/** Lazily selected custom or Node semantic backend owned by this project. */
|
|
1590
|
+
#semantics;
|
|
1591
|
+
/** Change counter used to discard pending analyses and editor answers. */
|
|
1592
|
+
#revision = 0;
|
|
1593
|
+
/** Serializes transactions and absorbs failures before subsequent work. */
|
|
1594
|
+
#queue = Promise.resolve();
|
|
1595
|
+
/** Node backend retained separately to expose checker statistics. */
|
|
1596
|
+
#facts;
|
|
1597
|
+
/** Requests backend invalidation before the next transaction. */
|
|
1598
|
+
#dirty = true;
|
|
1599
|
+
/** Requests replacement of the cached CSS loader. */
|
|
1600
|
+
#cssDirty = true;
|
|
1601
|
+
/** Requests semantic disk-cache invalidation after an external change. */
|
|
1602
|
+
#diskDirty = true;
|
|
1603
|
+
/** Prevents transactions from producing new results during cleanup. */
|
|
1604
|
+
#closed = false;
|
|
1605
|
+
/**
|
|
1606
|
+
* Takes ownership of a backend without loading CSS or starting a checker.
|
|
1607
|
+
*
|
|
1608
|
+
* @param host - Initialized backend whose TypeScript environment uses the same root. Release
|
|
1609
|
+
* this project with `close` when its analysis services are no longer needed.
|
|
1610
|
+
* @param backend - Optional lazy semantic backend factory. Omission selects the Node checker.
|
|
1611
|
+
*/
|
|
1612
|
+
constructor(host, backend) {
|
|
1613
|
+
this.host = host;
|
|
1614
|
+
this.#css = new AnalysisCss(host);
|
|
1615
|
+
this.#backend = backend;
|
|
1616
|
+
}
|
|
1617
|
+
/**
|
|
1618
|
+
* Reads counters from the owned Node checker without exposing its mutable statistics object.
|
|
1619
|
+
* @returns A copy of the counters, or undefined before checker creation or with a custom backend.
|
|
1620
|
+
*/
|
|
1621
|
+
get checkerStats() {
|
|
1622
|
+
return this.#facts && { ...this.#facts.stats };
|
|
1623
|
+
}
|
|
1624
|
+
/**
|
|
1625
|
+
* Stores an unsaved buffer. Changed text advances the revision and makes pending results stale.
|
|
1626
|
+
*
|
|
1627
|
+
* @param id - File path resolved from the process working directory when relative.
|
|
1628
|
+
* @param source - Complete original document text.
|
|
1629
|
+
* @param version - Safe integer greater than the open buffer's version. An identical buffer and
|
|
1630
|
+
* version have no effect. Identical text with a newer version updates only the version.
|
|
1631
|
+
* A document can restart its version sequence after closeDocument.
|
|
1632
|
+
* @throws If the version is invalid or does not increase for a changed open buffer.
|
|
1633
|
+
*/
|
|
1634
|
+
update(id, source, version) {
|
|
1635
|
+
id = path.resolve(id);
|
|
1636
|
+
const previous = this.#documents.get(id);
|
|
1637
|
+
if (previous?.version === version && previous.source === source) return;
|
|
1638
|
+
if (!Number.isSafeInteger(version) || previous && previous.version >= version) throw new Error("Analysis document versions must increase");
|
|
1639
|
+
this.#documents.set(id, {
|
|
1640
|
+
source,
|
|
1641
|
+
version
|
|
1642
|
+
});
|
|
1643
|
+
if (previous?.source === source) return;
|
|
1644
|
+
if (this.#compilation.source(id)?.document.code !== source) this.#compilation.invalidate(id);
|
|
1645
|
+
this.#revision++;
|
|
1646
|
+
this.#dirty = true;
|
|
1647
|
+
this.#cssDirty ||= this.#css.affects(id);
|
|
1648
|
+
}
|
|
1649
|
+
/**
|
|
1650
|
+
* Removes an unsaved buffer and advances the revision when one existed.
|
|
1651
|
+
*
|
|
1652
|
+
* @param id - File path, resolved in the same way as update. Later reads use the host's source
|
|
1653
|
+
* provider. Unknown paths have no effect.
|
|
1654
|
+
*/
|
|
1655
|
+
closeDocument(id) {
|
|
1656
|
+
id = path.resolve(id);
|
|
1657
|
+
if (this.#documents.delete(id)) {
|
|
1658
|
+
this.#compilation.invalidate(id);
|
|
1659
|
+
this.#revision++;
|
|
1660
|
+
this.#dirty = true;
|
|
1661
|
+
this.#cssDirty ||= this.#css.affects(id);
|
|
1662
|
+
}
|
|
1663
|
+
}
|
|
1664
|
+
/** Makes pending results stale. The next transaction rebuilds CSS and backend caches. */
|
|
1665
|
+
invalidate() {
|
|
1666
|
+
this.#compilation.invalidate();
|
|
1667
|
+
this.#revision++;
|
|
1668
|
+
this.#dirty = true;
|
|
1669
|
+
this.#cssDirty = true;
|
|
1670
|
+
this.#diskDirty = true;
|
|
1671
|
+
}
|
|
1672
|
+
/**
|
|
1673
|
+
* Lists the stylesheets that this project lints, using the document contents captured when this
|
|
1674
|
+
* method is called.
|
|
1675
|
+
*
|
|
1676
|
+
* @param editor - When false (the default), loads the original CSS and rejects invalid input.
|
|
1677
|
+
* When true, retries a failed load with recovered definitions so incomplete CSS can still
|
|
1678
|
+
* determine membership for completion, hover, and colors.
|
|
1679
|
+
* @returns Identities of the CSS entry and the imported files that the CSS host marks for lint,
|
|
1680
|
+
* in load order. Package CSS is excluded unless the host marks it. Returns an empty list
|
|
1681
|
+
* if the captured buffers become outdated before loading starts.
|
|
1682
|
+
* @throws If the project is closed, installing buffers or invalidating caches fails, or the
|
|
1683
|
+
* selected CSS loading mode fails.
|
|
1684
|
+
*/
|
|
1685
|
+
stylesheets(editor = false) {
|
|
1686
|
+
const revision = this.#revision;
|
|
1687
|
+
const documents = new Map([...this.#documents].map(([id, document]) => [id, document.source]));
|
|
1688
|
+
const task = this.#queue.then(async () => {
|
|
1689
|
+
if (this.#closed) throw new Error("Analysis project is closed");
|
|
1690
|
+
if (!await this.#installDocuments(documents, revision)) return [];
|
|
1691
|
+
if (editor) return [...(await this.#css.editor()).lintSources];
|
|
1692
|
+
await this.#css.load();
|
|
1693
|
+
return [...this.#css.lintSources];
|
|
1694
|
+
});
|
|
1695
|
+
this.#queue = task.catch(() => {});
|
|
1696
|
+
return task;
|
|
1697
|
+
}
|
|
1698
|
+
/**
|
|
1699
|
+
* Queues analysis using the document contents and revision captured when this method is called.
|
|
1700
|
+
*
|
|
1701
|
+
* @param entry - Full resolver identity of a supported target, or of a stylesheet that
|
|
1702
|
+
* {@link stylesheets} lists. A stylesheet's reports are its stylesheet lint findings, and its
|
|
1703
|
+
* result has no graph. Membership filtering is performed by AnalysisWorkspace, not by this
|
|
1704
|
+
* project.
|
|
1705
|
+
* @param signal - Optional cancellation checked before and after queued work. Cancellation
|
|
1706
|
+
* discards results without interrupting a checker query that has already started.
|
|
1707
|
+
* @returns Reports for the entry and demanded semantic dependencies. Host failures appear as
|
|
1708
|
+
* incomplete results with error text. Unavailable semantic information appears in the graph's
|
|
1709
|
+
* unverified ranges. Stale and cancelled results omit reports and graphs.
|
|
1710
|
+
*/
|
|
1711
|
+
analyze(entry, signal) {
|
|
1712
|
+
const revision = this.#revision;
|
|
1713
|
+
const documents = new Map([...this.#documents].map(([id, document]) => [id, document.source]));
|
|
1714
|
+
const task = this.#queue.then(async () => {
|
|
1715
|
+
const before = this.#discardReason(revision, signal);
|
|
1716
|
+
if (before) return discardedResult(entry, revision, before);
|
|
1717
|
+
const result = await this.#analyzeSnapshot(entry, revision, documents);
|
|
1718
|
+
const after = this.#discardReason(revision, signal);
|
|
1719
|
+
return after ? discardedResult(entry, revision, after) : result;
|
|
1720
|
+
});
|
|
1721
|
+
this.#queue = task.catch(() => {});
|
|
1722
|
+
return task;
|
|
1723
|
+
}
|
|
1724
|
+
/**
|
|
1725
|
+
* Loads targets together and prepares plugin candidates using the current buffers.
|
|
1726
|
+
*
|
|
1727
|
+
* @param entries - Full resolver IDs. The workspace must apply project membership rules first.
|
|
1728
|
+
* @returns Completion of preparation. Closed or outdated requests stop without publishing results.
|
|
1729
|
+
* Loading and plugin failures are left for each target's analysis to report. A failed plugin
|
|
1730
|
+
* runtime is discarded before retrying.
|
|
1731
|
+
*/
|
|
1732
|
+
prepare(entries) {
|
|
1733
|
+
const revision = this.#revision;
|
|
1734
|
+
const documents = new Map([...this.#documents].map(([id, document]) => [id, document.source]));
|
|
1735
|
+
const task = this.#queue.then(async () => {
|
|
1736
|
+
if (this.#closed || this.#discardReason(revision)) return;
|
|
1737
|
+
try {
|
|
1738
|
+
if (!await this.#installDocuments(documents, revision)) return;
|
|
1739
|
+
const loader = await this.#css.load();
|
|
1740
|
+
if (this.#discardReason(revision)) return;
|
|
1741
|
+
await this.#compilation.prepare(entries, this.host, this.#css.session);
|
|
1742
|
+
await prepareSourcePlugins(this.#css.session, loader, this.#compilation.texts());
|
|
1743
|
+
} catch {
|
|
1744
|
+
this.#css.discardPlugins();
|
|
1745
|
+
}
|
|
1746
|
+
});
|
|
1747
|
+
this.#queue = task.catch(() => {});
|
|
1748
|
+
return task;
|
|
1749
|
+
}
|
|
1750
|
+
/**
|
|
1751
|
+
* Queries the captured analysis for an entry. Buffer changes or cancellation discard its answer.
|
|
1752
|
+
* CSS completion, hover, resolution, and colors can load recovered definitions for incomplete
|
|
1753
|
+
* input. CSS sorting and lint fixes require the original graph to load successfully.
|
|
1754
|
+
* Plugin path completion and links read captured CSS inside the project root without loading
|
|
1755
|
+
* its graph or executing plugins.
|
|
1756
|
+
*
|
|
1757
|
+
* @param entry - Full resolver identity. The workspace applies target membership filtering.
|
|
1758
|
+
* @param request - Operation with offsets in the original UTF-16 document.
|
|
1759
|
+
* @param signal - Optional cancellation checked before and after queued work.
|
|
1760
|
+
* @returns The current editor answer, or undefined after closure, cancellation, a revision change,
|
|
1761
|
+
* failed entry analysis, or a semantic CSS query outside the graph's stylesheets marked for lint.
|
|
1762
|
+
* @throws If preparing a CSS query fails or the editor query rejects a candidate or preview.
|
|
1763
|
+
*/
|
|
1764
|
+
query(entry, request, signal) {
|
|
1765
|
+
const revision = this.#revision;
|
|
1766
|
+
const documents = new Map([...this.#documents].map(([id, document]) => [id, document.source]));
|
|
1767
|
+
const task = this.#queue.then(async () => {
|
|
1768
|
+
if (this.#closed || this.#discardReason(revision, signal)) return;
|
|
1769
|
+
if (isStylesheet(entry) && [
|
|
1770
|
+
"completion",
|
|
1771
|
+
"resolve",
|
|
1772
|
+
"links"
|
|
1773
|
+
].includes(request.kind)) {
|
|
1774
|
+
if (!await this.#installDocuments(documents, revision, signal)) return;
|
|
1775
|
+
const text = await this.host.css.read(entry).catch(() => void 0);
|
|
1776
|
+
if (text === void 0) return;
|
|
1777
|
+
const navigation = await queryPluginPaths(entry, text, request, {
|
|
1778
|
+
root: this.host.root,
|
|
1779
|
+
names: this.host.config.plugins?.map((plugin) => plugin.name) ?? [],
|
|
1780
|
+
host: this.host.css.plugins,
|
|
1781
|
+
documentUri: (id) => this.host.css.documentUri(id)
|
|
1782
|
+
});
|
|
1783
|
+
if (navigation) return this.#discardReason(revision, signal) ? void 0 : navigation;
|
|
1784
|
+
}
|
|
1785
|
+
if ((request.kind === "sort" || request.kind === "fixes") && this.#editors.get(entry)?.recovered) this.#editors.delete(entry);
|
|
1786
|
+
if (this.#editors.get(entry)?.revision !== revision) {
|
|
1787
|
+
if (isStylesheet(entry) && [
|
|
1788
|
+
"completion",
|
|
1789
|
+
"hover",
|
|
1790
|
+
"resolve",
|
|
1791
|
+
"colors",
|
|
1792
|
+
"colorPresentation"
|
|
1793
|
+
].includes(request.kind)) {
|
|
1794
|
+
if (!await this.#installDocuments(documents, revision, signal)) return;
|
|
1795
|
+
const editor = await this.#css.editorSnapshot(entry);
|
|
1796
|
+
if (!editor) return;
|
|
1797
|
+
this.#editors.set(entry, {
|
|
1798
|
+
revision,
|
|
1799
|
+
...editor
|
|
1800
|
+
});
|
|
1801
|
+
} else await this.#analyzeSnapshot(entry, revision, documents);
|
|
1802
|
+
}
|
|
1803
|
+
const snapshot = this.#editors.get(entry)?.snapshot;
|
|
1804
|
+
await snapshot?.prepare(entry, request);
|
|
1805
|
+
const result = snapshot?.query(entry, request);
|
|
1806
|
+
return this.#discardReason(revision, signal) ? void 0 : result;
|
|
1807
|
+
});
|
|
1808
|
+
this.#queue = task.catch(() => {});
|
|
1809
|
+
return task;
|
|
1810
|
+
}
|
|
1811
|
+
/**
|
|
1812
|
+
* Marks the project closed, discards pending results, and waits for queued work before cleanup.
|
|
1813
|
+
* Repeated calls return without requesting further cleanup.
|
|
1814
|
+
*
|
|
1815
|
+
* @throws If checker or backend cleanup fails.
|
|
1816
|
+
* @returns A promise that resolves after queued analysis and cleanup. Repeated calls made after
|
|
1817
|
+
* closure starts return immediately. They do not wait for the first call's cleanup.
|
|
1818
|
+
*/
|
|
1819
|
+
async close() {
|
|
1820
|
+
if (this.#closed) return;
|
|
1821
|
+
this.#closed = true;
|
|
1822
|
+
this.#editors.clear();
|
|
1823
|
+
this.#revision++;
|
|
1824
|
+
await this.#queue;
|
|
1825
|
+
const errors = (await Promise.allSettled([Promise.resolve().then(() => this.#semantics?.close()), Promise.resolve().then(() => this.host.close())])).flatMap((result) => result.status === "rejected" ? [result.reason] : []);
|
|
1826
|
+
if (errors.length) throw new AggregateError(errors, "Failed to close Stillwind analysis services");
|
|
1827
|
+
}
|
|
1828
|
+
/**
|
|
1829
|
+
* Determines whether a captured operation can still publish its result.
|
|
1830
|
+
*
|
|
1831
|
+
* @param revision - Change counter captured when the operation was queued.
|
|
1832
|
+
* @param signal - Optional request cancellation, which takes precedence over staleness.
|
|
1833
|
+
* @returns The discard status, or undefined while the capture remains current.
|
|
1834
|
+
*/
|
|
1835
|
+
#discardReason(revision, signal) {
|
|
1836
|
+
if (signal?.aborted) return "cancelled";
|
|
1837
|
+
if (revision !== this.#revision) return "stale";
|
|
1838
|
+
}
|
|
1839
|
+
/**
|
|
1840
|
+
* Installs captured buffers, refreshes caches, and retains an editor snapshot after compilation.
|
|
1841
|
+
*
|
|
1842
|
+
* @param entry - Supported full resolver identity to analyze.
|
|
1843
|
+
* @param revision - Change counter associated with the captured documents.
|
|
1844
|
+
* @param documents - Independent map of open absolute paths to original text.
|
|
1845
|
+
* @returns Findings mapped to original documents. Host failures become incomplete results with error text.
|
|
1846
|
+
*/
|
|
1847
|
+
async #analyzeSnapshot(entry, revision, documents) {
|
|
1848
|
+
const result = {
|
|
1849
|
+
entry,
|
|
1850
|
+
revision,
|
|
1851
|
+
status: "incomplete",
|
|
1852
|
+
reports: []
|
|
1853
|
+
};
|
|
1854
|
+
try {
|
|
1855
|
+
if (this.#closed) throw new Error("Analysis project is closed");
|
|
1856
|
+
if (!await this.#installDocuments(documents, revision)) return result;
|
|
1857
|
+
if (isStylesheet(entry)) {
|
|
1858
|
+
const stylesheet = await this.#css.stylesheet(entry);
|
|
1859
|
+
result.reports = stylesheet.reports;
|
|
1860
|
+
result.status = "complete";
|
|
1861
|
+
this.#editors.set(entry, {
|
|
1862
|
+
revision,
|
|
1863
|
+
snapshot: stylesheet.snapshot
|
|
1864
|
+
});
|
|
1865
|
+
return result;
|
|
1866
|
+
}
|
|
1867
|
+
if (!this.host.supports?.(entry)) throw new Error(`The ${this.host.constructor.name} host cannot analyze ${entry}`);
|
|
1868
|
+
await this.#css.load();
|
|
1869
|
+
const loader = this.#css.loader;
|
|
1870
|
+
const session = this.#css.session;
|
|
1871
|
+
const graph = await analyzeModule(session, () => this.#semanticBackend(), entry, this.host, { overlayFiles: documents }, revision === this.#revision ? this.#compilation : void 0);
|
|
1872
|
+
result.graph = structuredClone(graph);
|
|
1873
|
+
result.reports = await mapAnalysisReports(graph.batches.flatMap((batch) => batch.reports), graph.sources, (id) => this.host.read(id));
|
|
1874
|
+
const editor = new EditorSnapshot(graph, session, loader, this.host.config, await this.#css.plugins?.catalog() ?? [], this.#css.plugins);
|
|
1875
|
+
result.reports.push(...editor.reports());
|
|
1876
|
+
this.#editors.set(entry, {
|
|
1877
|
+
revision,
|
|
1878
|
+
snapshot: editor
|
|
1879
|
+
});
|
|
1880
|
+
result.status = analysisComplete(graph) ? "complete" : "incomplete";
|
|
1881
|
+
} catch (error) {
|
|
1882
|
+
result.error = error instanceof Error ? error.message : String(error);
|
|
1883
|
+
if (error instanceof Error && "reports" in error && Array.isArray(error.reports)) result.reports = error.reports;
|
|
1884
|
+
}
|
|
1885
|
+
return result;
|
|
1886
|
+
}
|
|
1887
|
+
/**
|
|
1888
|
+
* Installs captured buffers and refreshes caches before work continues.
|
|
1889
|
+
*
|
|
1890
|
+
* @param documents - Original buffers captured with the supplied revision.
|
|
1891
|
+
* @param revision - Revision that owns this queued operation.
|
|
1892
|
+
* @param signal - Optional cancellation checked between host operations.
|
|
1893
|
+
* @returns Whether the operation can continue with these buffers after cache refresh.
|
|
1894
|
+
* @throws If installing buffers or refreshing host or checker caches fails.
|
|
1895
|
+
*/
|
|
1896
|
+
async #installDocuments(documents, revision, signal) {
|
|
1897
|
+
await this.host.setDocuments(documents);
|
|
1898
|
+
if (this.#discardReason(revision, signal)) return false;
|
|
1899
|
+
await this.#resetCaches();
|
|
1900
|
+
return !this.#discardReason(revision, signal);
|
|
1901
|
+
}
|
|
1902
|
+
/**
|
|
1903
|
+
* Consumes dirty flags and invalidates semantic, CSS, and host caches as requested.
|
|
1904
|
+
*
|
|
1905
|
+
* @returns Completion of required invalidation, or no work when the project is clean.
|
|
1906
|
+
* @throws If semantic or host invalidation fails.
|
|
1907
|
+
*/
|
|
1908
|
+
async #resetCaches() {
|
|
1909
|
+
if (!this.#dirty) return;
|
|
1910
|
+
this.#dirty = false;
|
|
1911
|
+
if (this.#diskDirty) {
|
|
1912
|
+
this.#diskDirty = false;
|
|
1913
|
+
await this.#semantics?.invalidate();
|
|
1914
|
+
}
|
|
1915
|
+
if (this.#cssDirty) {
|
|
1916
|
+
this.#cssDirty = false;
|
|
1917
|
+
this.#css.invalidate();
|
|
1918
|
+
}
|
|
1919
|
+
await this.host.invalidate();
|
|
1920
|
+
}
|
|
1921
|
+
/**
|
|
1922
|
+
* Lazily selects the custom backend or creates the Node checker with fixed project settings.
|
|
1923
|
+
*
|
|
1924
|
+
* @returns The owned backend, or undefined when type facts are disabled.
|
|
1925
|
+
* @throws If backend creation fails.
|
|
1926
|
+
*/
|
|
1927
|
+
#semanticBackend() {
|
|
1928
|
+
if (this.host.typeFacts === false) return;
|
|
1929
|
+
if (!this.#semantics) {
|
|
1930
|
+
const backend = this.#backend?.();
|
|
1931
|
+
if (backend) this.#semantics = backend;
|
|
1932
|
+
else {
|
|
1933
|
+
this.#facts = new TypeScriptFactsService(this.host.typeFactsEnvironment);
|
|
1934
|
+
this.#semantics = this.#facts;
|
|
1935
|
+
}
|
|
1936
|
+
}
|
|
1937
|
+
return this.#semantics;
|
|
1938
|
+
}
|
|
1939
|
+
};
|
|
1940
|
+
/**
|
|
1941
|
+
* Creates a result that carries no reports or graph after a capture becomes unusable.
|
|
1942
|
+
*
|
|
1943
|
+
* @param entry - Requested resolver identity.
|
|
1944
|
+
* @param revision - Change counter captured when the request was queued.
|
|
1945
|
+
* @param status - Reason the capture was discarded.
|
|
1946
|
+
* @returns An empty analysis result preserving request identity and revision.
|
|
1947
|
+
*/
|
|
1948
|
+
function discardedResult(entry, revision, status) {
|
|
1949
|
+
return {
|
|
1950
|
+
entry,
|
|
1951
|
+
revision,
|
|
1952
|
+
status,
|
|
1953
|
+
reports: []
|
|
1954
|
+
};
|
|
1955
|
+
}
|
|
1956
|
+
/**
|
|
1957
|
+
* Checks whether all demanded semantic inputs were available, independently of compiler error reports.
|
|
1958
|
+
*
|
|
1959
|
+
* @param graph - Observed graph returned by compilation.
|
|
1960
|
+
* @returns Whether no ranges are unverified and no dependency is unresolved or unsupported.
|
|
1961
|
+
*/
|
|
1962
|
+
function analysisComplete(graph) {
|
|
1963
|
+
return graph.unverified.length === 0 && !graph.dependencies.some((dependency) => dependency.status === "unresolved" || dependency.status === "unsupported");
|
|
1964
|
+
}
|
|
1965
|
+
// src/project/editor.ts
|
|
1966
|
+
/** Versioned, unpublished previews. Each request owns its compiler session. */
|
|
1967
|
+
var EditorProject = class {
|
|
1968
|
+
/**
|
|
1969
|
+
* Open unsaved buffers keyed by cleaned resolver identity. Analysis captures a map of these
|
|
1970
|
+
* buffers before asynchronous work.
|
|
1971
|
+
*/
|
|
1972
|
+
#documents = /* @__PURE__ */ new Map();
|
|
1973
|
+
/**
|
|
1974
|
+
* Most recent successful output for each cleaned document identity, retained across later
|
|
1975
|
+
* unsuccessful attempts.
|
|
1976
|
+
*/
|
|
1977
|
+
#successes = /* @__PURE__ */ new Map();
|
|
1978
|
+
/**
|
|
1979
|
+
* Project change counter used to reject results whose source or dependencies changed during
|
|
1980
|
+
* analysis.
|
|
1981
|
+
*/
|
|
1982
|
+
#revision = 0;
|
|
1983
|
+
/** Filesystem root used to initialize the type-facts service when an analysis needs it. */
|
|
1984
|
+
root;
|
|
1985
|
+
/**
|
|
1986
|
+
* Dependency resolver and source metadata operations. Open buffers override its reader during
|
|
1987
|
+
* analysis.
|
|
1988
|
+
*/
|
|
1989
|
+
host;
|
|
1990
|
+
/**
|
|
1991
|
+
* Factory that must return a completed design-system loader suitable for a new compiler session
|
|
1992
|
+
* on every analysis, or a loaded CSS graph whose plugins define dynamic candidates.
|
|
1993
|
+
*/
|
|
1994
|
+
designSystem;
|
|
1995
|
+
/** Fixed checker settings reused by independent analyses and retained without rereading tsconfig. */
|
|
1996
|
+
#typeFactsEnvironment;
|
|
1997
|
+
/**
|
|
1998
|
+
* Creates an editor project without opening documents or creating a checker.
|
|
1999
|
+
*
|
|
2000
|
+
* @param root - Filesystem project root used for checker resolution.
|
|
2001
|
+
* @param host - Source descriptors, dependency resolver, and reader used by analysis.
|
|
2002
|
+
* @param designSystem - Factory returning a loaded design system, or a loaded CSS graph with its
|
|
2003
|
+
* plugins, for each independent analysis.
|
|
2004
|
+
* @param typeFactsEnvironment - Fixed checker settings whose root matches this project. Omission
|
|
2005
|
+
* selects an existing root tsconfig or isolated defaults.
|
|
2006
|
+
*/
|
|
2007
|
+
constructor(root, host, designSystem, typeFactsEnvironment = resolveTypeFactsEnvironment(root)) {
|
|
2008
|
+
this.root = root;
|
|
2009
|
+
this.host = host;
|
|
2010
|
+
this.designSystem = designSystem;
|
|
2011
|
+
this.#typeFactsEnvironment = typeFactsEnvironment;
|
|
2012
|
+
}
|
|
2013
|
+
/**
|
|
2014
|
+
* Stores an unsaved buffer and advances the project revision.
|
|
2015
|
+
*
|
|
2016
|
+
* @param document - Buffer with a safe integer version greater than the current version for its
|
|
2017
|
+
* cleaned identity. A copy is stored.
|
|
2018
|
+
* @throws If the version is not a safe integer or does not increase for an open document.
|
|
2019
|
+
*/
|
|
2020
|
+
update(document) {
|
|
2021
|
+
const id = cleanModuleId(document.id);
|
|
2022
|
+
const previous = this.#documents.get(id);
|
|
2023
|
+
if (!Number.isSafeInteger(document.version) || previous && document.version <= previous.version) throw new Error("Editor document versions must increase monotonically");
|
|
2024
|
+
this.#documents.set(id, {
|
|
2025
|
+
...document,
|
|
2026
|
+
id
|
|
2027
|
+
});
|
|
2028
|
+
this.#revision += 1;
|
|
2029
|
+
}
|
|
2030
|
+
/**
|
|
2031
|
+
* Removes an open buffer and its retained successful preview.
|
|
2032
|
+
*
|
|
2033
|
+
* @param id - Document identity, cleaned in the same way as `update`. Removing an open buffer
|
|
2034
|
+
* advances the revision. An unknown identity has no effect.
|
|
2035
|
+
*/
|
|
2036
|
+
close(id) {
|
|
2037
|
+
id = cleanModuleId(id);
|
|
2038
|
+
if (this.#documents.delete(id)) this.#revision += 1;
|
|
2039
|
+
this.#successes.delete(id);
|
|
2040
|
+
}
|
|
2041
|
+
/**
|
|
2042
|
+
* Advances the revision after disk dependencies or the design system change, making in-progress
|
|
2043
|
+
* analysis stale.
|
|
2044
|
+
*/
|
|
2045
|
+
invalidate() {
|
|
2046
|
+
this.#revision += 1;
|
|
2047
|
+
}
|
|
2048
|
+
/**
|
|
2049
|
+
* Compiles an open document with the unsaved buffers captured at analysis start.
|
|
2050
|
+
*
|
|
2051
|
+
* The analysis owns a new compiler session and closes any checker it creates. Dependency reads
|
|
2052
|
+
* prefer captured open buffers. Compiler diagnostics are collected. Other failures become the
|
|
2053
|
+
* returned error text. Stale or cancelled work retains neither current output nor a new
|
|
2054
|
+
* successful preview.
|
|
2055
|
+
*
|
|
2056
|
+
* @param id - Identity of an open document. Ordinary query and fragment suffixes are removed.
|
|
2057
|
+
* @param signal - Optional cancellation signal checked around asynchronous dependency operations
|
|
2058
|
+
* and before returning.
|
|
2059
|
+
* @returns A promise for the versioned result, observed dependencies, optional checker counters,
|
|
2060
|
+
* and the success retained when analysis started.
|
|
2061
|
+
* @throws If the document is not open. Cleanup failures can also reject the promise.
|
|
2062
|
+
*/
|
|
2063
|
+
async analyze(id, signal) {
|
|
2064
|
+
id = cleanModuleId(id);
|
|
2065
|
+
const document = this.#documents.get(id);
|
|
2066
|
+
if (!document) throw new Error(`Editor document is not open: ${id}`);
|
|
2067
|
+
const revision = this.#revision;
|
|
2068
|
+
const overlays = new Map(this.#documents);
|
|
2069
|
+
const dependencies = /* @__PURE__ */ new Set();
|
|
2070
|
+
const result = {
|
|
2071
|
+
document: { ...document },
|
|
2072
|
+
revision,
|
|
2073
|
+
coverage: "observed",
|
|
2074
|
+
status: "partial",
|
|
2075
|
+
dependencies: [],
|
|
2076
|
+
previousSuccess: this.#successes.get(id)
|
|
2077
|
+
};
|
|
2078
|
+
/**
|
|
2079
|
+
* Requires this analysis to retain the captured project revision and an active signal.
|
|
2080
|
+
* @throws If cancellation or a newer project revision makes this analysis obsolete.
|
|
2081
|
+
*/
|
|
2082
|
+
const assertActive = () => {
|
|
2083
|
+
if (signal?.aborted) throw new Error("Editor analysis cancelled");
|
|
2084
|
+
if (revision !== this.#revision) throw new Error("Editor analysis superseded");
|
|
2085
|
+
};
|
|
2086
|
+
let facts;
|
|
2087
|
+
try {
|
|
2088
|
+
assertActive();
|
|
2089
|
+
const design = this.designSystem();
|
|
2090
|
+
const graph = "loader" in design ? design : {
|
|
2091
|
+
loader: design,
|
|
2092
|
+
plugins: void 0
|
|
2093
|
+
};
|
|
2094
|
+
const session = new NativeProjectSession(graph.loader, false);
|
|
2095
|
+
attachPlugins(session, graph.plugins);
|
|
2096
|
+
const output = await compileModule(session, () => {
|
|
2097
|
+
facts ??= new TypeScriptFactsService(this.#typeFactsEnvironment);
|
|
2098
|
+
return facts;
|
|
2099
|
+
}, document.source, id, {
|
|
2100
|
+
describe: (dependency) => this.host.describe(dependency),
|
|
2101
|
+
resolve: async (...args) => {
|
|
2102
|
+
assertActive();
|
|
2103
|
+
const resolved = await this.host.resolve(...args);
|
|
2104
|
+
assertActive();
|
|
2105
|
+
return resolved;
|
|
2106
|
+
},
|
|
2107
|
+
read: async (dependency) => {
|
|
2108
|
+
assertActive();
|
|
2109
|
+
const source = overlays.get(cleanModuleId(dependency))?.source ?? await this.host.read(dependency);
|
|
2110
|
+
assertActive();
|
|
2111
|
+
return source;
|
|
2112
|
+
},
|
|
2113
|
+
watch: (dependency) => dependencies.add(dependency),
|
|
2114
|
+
warn: () => {}
|
|
2115
|
+
}, {
|
|
2116
|
+
diagnostics: "collect",
|
|
2117
|
+
typeFactsInputs: { overlayFiles: new Map([...overlays].map(([id, value]) => [id, value.source])) }
|
|
2118
|
+
});
|
|
2119
|
+
assertActive();
|
|
2120
|
+
result.output = output;
|
|
2121
|
+
const denied = output?.lintFindings.some((finding) => output.lintSettings[finding.rule] === "deny");
|
|
2122
|
+
if (output?.code != null && output.diagnostics.length === 0 && !denied) {
|
|
2123
|
+
result.status = "success";
|
|
2124
|
+
this.#successes.set(id, {
|
|
2125
|
+
version: document.version,
|
|
2126
|
+
revision,
|
|
2127
|
+
output
|
|
2128
|
+
});
|
|
2129
|
+
}
|
|
2130
|
+
} catch (error) {
|
|
2131
|
+
result.error = error instanceof Error ? error.message : String(error);
|
|
2132
|
+
} finally {
|
|
2133
|
+
if (facts) result.checkerStats = { ...facts.stats };
|
|
2134
|
+
facts?.close();
|
|
2135
|
+
result.dependencies = [...dependencies];
|
|
2136
|
+
}
|
|
2137
|
+
if (signal?.aborted || revision !== this.#revision) {
|
|
2138
|
+
result.status = signal?.aborted ? "cancelled" : "stale";
|
|
2139
|
+
delete result.output;
|
|
2140
|
+
}
|
|
2141
|
+
return result;
|
|
2142
|
+
}
|
|
2143
|
+
};
|
|
2144
|
+
// src/project/plugins.ts
|
|
2145
|
+
/**
|
|
2146
|
+
* Lists disk children for plugin completion and plugin directory reads, following
|
|
2147
|
+
* directory symlinks.
|
|
2148
|
+
* @param id - Absolute directory to enumerate without loading its scripts.
|
|
2149
|
+
* @returns Immediate entries in filesystem order. Broken symlinks are treated as files.
|
|
2150
|
+
* @throws If the directory cannot be read.
|
|
2151
|
+
*/
|
|
2152
|
+
async function readPluginDirectory(id) {
|
|
2153
|
+
return Promise.all((await readdir(id, { withFileTypes: true })).map(async (entry) => ({
|
|
2154
|
+
name: entry.name,
|
|
2155
|
+
directory: entry.isDirectory() || entry.isSymbolicLink() && await stat(path.join(id, entry.name)).then((value) => value.isDirectory()).catch(() => false)
|
|
2156
|
+
})));
|
|
2157
|
+
}
|
|
2158
|
+
/**
|
|
2159
|
+
* Plugin files evaluated from a relative or absolute `@plugin` path, keyed by entry path. Each entry
|
|
2160
|
+
* records the text of its bundled local files, so a load reuses the plugin only while every text is
|
|
2161
|
+
* unchanged.
|
|
2162
|
+
*/
|
|
2163
|
+
const files = /* @__PURE__ */ new Map();
|
|
2164
|
+
/**
|
|
2165
|
+
* Loads plugin packages and plugin files with Node module resolution from the stylesheet that
|
|
2166
|
+
* contains the `@plugin` statement, and reads files from the filesystem.
|
|
2167
|
+
*
|
|
2168
|
+
* A package specifier is imported with Node's module cache, so a changed package takes effect only
|
|
2169
|
+
* in a new process. A relative or absolute path is bundled with its local imports and evaluated
|
|
2170
|
+
* again after any of those files changes.
|
|
2171
|
+
*/
|
|
2172
|
+
const nodePluginHost = {
|
|
2173
|
+
complete: (prefix, importer, root) => completePluginPaths(prefix, importer, root, {
|
|
2174
|
+
read: (id) => readFile(id, "utf8"),
|
|
2175
|
+
directory: readPluginDirectory
|
|
2176
|
+
}),
|
|
2177
|
+
async load(specifier, importer, watch) {
|
|
2178
|
+
const resolved = createRequire(importer).resolve(specifier);
|
|
2179
|
+
if (!specifier.startsWith(".") && !path.isAbsolute(specifier)) return defaultPluginExport(await import(pathToFileURL(resolved).href), specifier);
|
|
2180
|
+
let cached = files.get(resolved);
|
|
2181
|
+
if (!cached || !await Promise.all([...cached.sources].map(async ([file, text]) => readFile(file, "utf8").then((current) => current === text, () => false))).then((results) => results.every(Boolean))) {
|
|
2182
|
+
const { exported, dependencies, sources } = await evaluateModule(resolved);
|
|
2183
|
+
cached = {
|
|
2184
|
+
sources,
|
|
2185
|
+
dependencies,
|
|
2186
|
+
plugin: defaultPluginExport({ default: exported }, specifier)
|
|
2187
|
+
};
|
|
2188
|
+
files.set(resolved, cached);
|
|
2189
|
+
}
|
|
2190
|
+
for (const dependency of cached.dependencies) watch(dependency);
|
|
2191
|
+
return cached.plugin;
|
|
2192
|
+
},
|
|
2193
|
+
async resolve(specifier, importer) {
|
|
2194
|
+
try {
|
|
2195
|
+
return createRequire(importer).resolve(specifier);
|
|
2196
|
+
} catch {
|
|
2197
|
+
return;
|
|
2198
|
+
}
|
|
2199
|
+
},
|
|
2200
|
+
async read(path) {
|
|
2201
|
+
return await readFile(path, "utf8");
|
|
2202
|
+
},
|
|
2203
|
+
list: readPluginDirectory
|
|
2204
|
+
};
|
|
2205
|
+
// src/project/stylesheets.ts
|
|
2206
|
+
/**
|
|
2207
|
+
* Creates a resolver for stylesheet imports. It selects `.css` files, the `style` export
|
|
2208
|
+
* condition, and the `style` package field, as CSS tooling resolves packages such as
|
|
2209
|
+
* `tw-animate-css`.
|
|
2210
|
+
*
|
|
2211
|
+
* @returns A new resolver with its own cache.
|
|
2212
|
+
*/
|
|
2213
|
+
function stylesheetResolver() {
|
|
2214
|
+
return new ResolverFactory({
|
|
2215
|
+
extensions: [".css"],
|
|
2216
|
+
conditionNames: [
|
|
2217
|
+
"style",
|
|
2218
|
+
"import",
|
|
2219
|
+
"default"
|
|
2220
|
+
],
|
|
2221
|
+
mainFields: ["style", "main"]
|
|
2222
|
+
});
|
|
2223
|
+
}
|
|
2224
|
+
/**
|
|
2225
|
+
* Creates a stylesheet package resolver for hosts whose own resolver selects JavaScript entries.
|
|
2226
|
+
*
|
|
2227
|
+
* @returns A function that resolves a specifier from an importing file to a path, or to
|
|
2228
|
+
* undefined when the specifier does not resolve.
|
|
2229
|
+
*/
|
|
2230
|
+
function createStylesheetResolver() {
|
|
2231
|
+
const resolver = stylesheetResolver();
|
|
2232
|
+
return async (specifier, importer) => (await resolver.async(path.dirname(importer), specifier)).path;
|
|
2233
|
+
}
|
|
2234
|
+
// src/project/filesystem.ts
|
|
2235
|
+
/**
|
|
2236
|
+
* Creates a Node analysis host with captured buffers, source providers, and CSS resolution.
|
|
2237
|
+
* Custom source resolution takes precedence over identities supplied by the semantic backend.
|
|
2238
|
+
*
|
|
2239
|
+
* @param config - One evaluated project. Custom source and projection callbacks receive the
|
|
2240
|
+
* buffers installed by setDocuments. Prepared inputs bypass custom projection preparation.
|
|
2241
|
+
* @param directory - Configuration directory used to resolve a relative project root.
|
|
2242
|
+
* @returns An owned host with fixed TypeScript settings. CSS and checker creation remain lazy.
|
|
2243
|
+
* @throws If TypeScript settings cannot be selected or the CSS resolver cannot be initialized.
|
|
2244
|
+
*/
|
|
2245
|
+
function createFileSystemAnalysisHost(config, directory) {
|
|
2246
|
+
config = captureProjectConfig(config);
|
|
2247
|
+
const resolvedConfig = resolveProjectConfig(config, directory);
|
|
2248
|
+
const root = resolvedConfig.root;
|
|
2249
|
+
const typeFactsEnvironment = resolveTypeFactsEnvironment(root, resolvedConfig.tsconfig);
|
|
2250
|
+
const cssResolver = stylesheetResolver();
|
|
2251
|
+
const frameworkResolver = new ResolverFactory({
|
|
2252
|
+
extensions: [
|
|
2253
|
+
".astro",
|
|
2254
|
+
".svelte",
|
|
2255
|
+
".vue"
|
|
2256
|
+
],
|
|
2257
|
+
conditionNames: ["import", "default"],
|
|
2258
|
+
tsconfig: typeFactsEnvironment.project.kind === "configured" ? {
|
|
2259
|
+
configFile: typeFactsEnvironment.project.configPath,
|
|
2260
|
+
references: "auto"
|
|
2261
|
+
} : void 0
|
|
2262
|
+
});
|
|
2263
|
+
let documents = /* @__PURE__ */ new Map();
|
|
2264
|
+
let buffers = /* @__PURE__ */ new Map();
|
|
2265
|
+
/**
|
|
2266
|
+
* Normalizes paths for lookup in the captured buffer map.
|
|
2267
|
+
*
|
|
2268
|
+
* @param id - File path resolved against the process working directory when relative.
|
|
2269
|
+
* @returns An absolute path, lowercased on Windows to share keys across case variations.
|
|
2270
|
+
*/
|
|
2271
|
+
const documentKey = (id) => process.platform === "win32" ? path.resolve(id).toLowerCase() : path.resolve(id);
|
|
2272
|
+
/**
|
|
2273
|
+
* Reads a captured buffer before falling back to the physical file.
|
|
2274
|
+
*
|
|
2275
|
+
* @param id - File path accepted by the Node filesystem.
|
|
2276
|
+
* @returns Captured text when present, otherwise UTF-8 file text.
|
|
2277
|
+
* @throws If the required physical file cannot be read.
|
|
2278
|
+
*/
|
|
2279
|
+
const read = (id) => Promise.resolve(buffers.get(documentKey(id)) ?? readFile(id, "utf8"));
|
|
2280
|
+
/**
|
|
2281
|
+
* Lists a directory with the open buffers inside it, so that an unsaved file appears as an entry.
|
|
2282
|
+
*
|
|
2283
|
+
* @param id - Absolute directory path.
|
|
2284
|
+
* @returns Disk and buffered entries, each listed once.
|
|
2285
|
+
* @throws If neither the disk nor the buffers contain the directory.
|
|
2286
|
+
*/
|
|
2287
|
+
const list = async (id) => {
|
|
2288
|
+
const buffered = pluginDirectory(documents, id, process.platform !== "win32");
|
|
2289
|
+
const entries = [...await readPluginDirectory(id).catch((error) => {
|
|
2290
|
+
if (!buffered.length) throw error;
|
|
2291
|
+
return [];
|
|
2292
|
+
}), ...buffered];
|
|
2293
|
+
return [...new Map(entries.map((entry) => [process.platform === "win32" ? entry.name.toLowerCase() : entry.name, entry])).values()];
|
|
2294
|
+
};
|
|
2295
|
+
/**
|
|
2296
|
+
* Selects script and framework sources eligible for default analysis.
|
|
2297
|
+
*
|
|
2298
|
+
* @param id - File path tested case-insensitively by extension.
|
|
2299
|
+
* @returns Whether the path has a supported extension and is not a TypeScript declaration file.
|
|
2300
|
+
*/
|
|
2301
|
+
const supports = (id) => /\.(?:[cm]?[jt]sx?|vue|svelte|astro)$/i.test(id) && !/\.d\.[cm]?ts$/i.test(id);
|
|
2302
|
+
return {
|
|
2303
|
+
root,
|
|
2304
|
+
config: resolvedConfig,
|
|
2305
|
+
typeFactsResolution: true,
|
|
2306
|
+
typeFacts: config.typeFacts,
|
|
2307
|
+
typeFactsEnvironment,
|
|
2308
|
+
supports: (id) => config.sources?.kind === "custom" ? config.sources.supports(id) : supports(id),
|
|
2309
|
+
describe: (id) => fileModuleDescriptor(root, id),
|
|
2310
|
+
read,
|
|
2311
|
+
load: async (id) => {
|
|
2312
|
+
const context = {
|
|
2313
|
+
root,
|
|
2314
|
+
documents
|
|
2315
|
+
};
|
|
2316
|
+
const input = config.sources?.kind === "custom" ? await config.sources.load(id, context) : {
|
|
2317
|
+
resolverId: id,
|
|
2318
|
+
...fileModuleDescriptor(root, id),
|
|
2319
|
+
document: {
|
|
2320
|
+
...fileModuleDescriptor(root, id).document,
|
|
2321
|
+
code: await read(id)
|
|
2322
|
+
}
|
|
2323
|
+
};
|
|
2324
|
+
return !("kind" in input) && config.projection?.kind === "custom" ? config.projection.prepare(input) : input;
|
|
2325
|
+
},
|
|
2326
|
+
resolve: async (specifier, importer) => {
|
|
2327
|
+
if (config.sources?.kind === "custom") {
|
|
2328
|
+
const id = await config.sources.resolve?.(specifier, importer, {
|
|
2329
|
+
root,
|
|
2330
|
+
documents
|
|
2331
|
+
});
|
|
2332
|
+
return id ? { id } : null;
|
|
2333
|
+
}
|
|
2334
|
+
if (/\.(?:vue|svelte|astro)$/i.test(specifier)) {
|
|
2335
|
+
if (specifier.startsWith(".") || path.isAbsolute(specifier)) {
|
|
2336
|
+
const id = path.resolve(path.dirname(importer), specifier);
|
|
2337
|
+
if (buffers.has(documentKey(id))) return { id };
|
|
2338
|
+
}
|
|
2339
|
+
const id = (await frameworkResolver.async(path.dirname(importer), specifier)).path;
|
|
2340
|
+
return id ? { id } : null;
|
|
2341
|
+
}
|
|
2342
|
+
return null;
|
|
2343
|
+
},
|
|
2344
|
+
watch: () => {},
|
|
2345
|
+
warn: () => {},
|
|
2346
|
+
css: {
|
|
2347
|
+
resolve: async (specifier, importer) => {
|
|
2348
|
+
const result = await cssResolver.async(path.dirname(importer), specifier);
|
|
2349
|
+
if (!result.path) throw new Error(`Cannot resolve CSS ${specifier} from ${importer}: ${result.error}`);
|
|
2350
|
+
return result.path;
|
|
2351
|
+
},
|
|
2352
|
+
read,
|
|
2353
|
+
documentUri: (id) => pathToFileURL(id).href,
|
|
2354
|
+
sourceMapSource: (id) => pathToFileURL(id).href,
|
|
2355
|
+
watch: () => {},
|
|
2356
|
+
plugins: {
|
|
2357
|
+
...nodePluginHost,
|
|
2358
|
+
read,
|
|
2359
|
+
/**
|
|
2360
|
+
* Resolves a plugin file request, preferring open buffers for a relative or absolute
|
|
2361
|
+
* path so that an unsaved plugin file resolves.
|
|
2362
|
+
*
|
|
2363
|
+
* @param specifier - Package specifier or path.
|
|
2364
|
+
* @param importer - Stylesheet that contains the statement.
|
|
2365
|
+
* @returns A buffered or existing file, or undefined when the request does not resolve
|
|
2366
|
+
* to a file.
|
|
2367
|
+
*/
|
|
2368
|
+
async resolve(specifier, importer) {
|
|
2369
|
+
if (specifier.startsWith(".") || path.isAbsolute(specifier)) {
|
|
2370
|
+
const base = path.resolve(path.dirname(importer), specifier);
|
|
2371
|
+
for (const suffix of [
|
|
2372
|
+
"",
|
|
2373
|
+
".js",
|
|
2374
|
+
".json",
|
|
2375
|
+
"/index.js"
|
|
2376
|
+
]) {
|
|
2377
|
+
const candidate = base + suffix;
|
|
2378
|
+
if (buffers.has(documentKey(candidate))) return candidate;
|
|
2379
|
+
}
|
|
2380
|
+
}
|
|
2381
|
+
const resolved = await nodePluginHost.resolve(specifier, importer);
|
|
2382
|
+
return resolved && await stat(resolved).then((value) => value.isFile()).catch(() => false) ? resolved : void 0;
|
|
2383
|
+
},
|
|
2384
|
+
list,
|
|
2385
|
+
complete: (prefix, importer, projectRoot) => completePluginPaths(prefix, importer, projectRoot, {
|
|
2386
|
+
read,
|
|
2387
|
+
directory: (id) => list(id).catch(() => [])
|
|
2388
|
+
})
|
|
2389
|
+
}
|
|
2390
|
+
},
|
|
2391
|
+
setDocuments: async (next) => {
|
|
2392
|
+
documents = next;
|
|
2393
|
+
buffers = new Map([...next].map(([id, text]) => [documentKey(id), text]));
|
|
2394
|
+
},
|
|
2395
|
+
invalidate: async () => {
|
|
2396
|
+
cssResolver.clearCache();
|
|
2397
|
+
frameworkResolver.clearCache();
|
|
2398
|
+
},
|
|
2399
|
+
close: async () => {}
|
|
2400
|
+
};
|
|
2401
|
+
}
|
|
2402
|
+
// src/project/workspace.ts
|
|
2403
|
+
/** Owns every project in one evaluated configuration and keeps overlapping scopes independent. */
|
|
2404
|
+
var AnalysisWorkspace = class AnalysisWorkspace {
|
|
2405
|
+
/** Absolute paths with open buffers, including paths outside the configured target globs. */
|
|
2406
|
+
#openDocuments = /* @__PURE__ */ new Set();
|
|
2407
|
+
/** Configuration files and imports whose changes require reopening this workspace. */
|
|
2408
|
+
#configurationDependencies;
|
|
2409
|
+
/** Absolute path evaluated when this workspace opened. Reopen the workspace to apply configuration changes. */
|
|
2410
|
+
configFile;
|
|
2411
|
+
/** Fixed project records in configuration order. Each analysis service owns mutable state. */
|
|
2412
|
+
projects;
|
|
2413
|
+
/**
|
|
2414
|
+
* Retains the evaluated configuration and takes ownership of its initialized projects.
|
|
2415
|
+
*
|
|
2416
|
+
* @param configFile - Absolute configuration path.
|
|
2417
|
+
* @param projects - Successfully opened hosts in configuration order.
|
|
2418
|
+
* @param dependencies - Absolute configuration and import paths recorded during evaluation.
|
|
2419
|
+
*/
|
|
2420
|
+
constructor(configFile, projects, dependencies) {
|
|
2421
|
+
this.configFile = configFile;
|
|
2422
|
+
this.projects = projects;
|
|
2423
|
+
this.#configurationDependencies = dependencies;
|
|
2424
|
+
}
|
|
2425
|
+
/**
|
|
2426
|
+
* Evaluates configuration and opens every project, closing earlier hosts if initialization fails.
|
|
2427
|
+
*
|
|
2428
|
+
* @param configFile - Trusted configuration path. Relative paths use the process working directory.
|
|
2429
|
+
* @returns A workspace that owns its project hosts. Close it when replacing the configuration.
|
|
2430
|
+
* @throws If configuration evaluation or project initialization fails.
|
|
2431
|
+
*/
|
|
2432
|
+
static async open(configFile) {
|
|
2433
|
+
configFile = path.resolve(configFile);
|
|
2434
|
+
const { config, dependencies } = await loadConfiguration(configFile);
|
|
2435
|
+
const projects = [];
|
|
2436
|
+
try {
|
|
2437
|
+
for (const supplied of config.projects) {
|
|
2438
|
+
const project = captureProjectConfig(supplied);
|
|
2439
|
+
const host = createFileSystemAnalysisHost(project, path.dirname(configFile));
|
|
2440
|
+
projects.push({
|
|
2441
|
+
config: project,
|
|
2442
|
+
configFile,
|
|
2443
|
+
analysis: new AnalysisProject(host)
|
|
2444
|
+
});
|
|
2445
|
+
}
|
|
2446
|
+
return new AnalysisWorkspace(configFile, projects, dependencies);
|
|
2447
|
+
} catch (error) {
|
|
2448
|
+
await Promise.allSettled(projects.map((project) => project.analysis.close()));
|
|
2449
|
+
throw error;
|
|
2450
|
+
}
|
|
2451
|
+
}
|
|
2452
|
+
/**
|
|
2453
|
+
* Matches target scope independently of whether the source exists on disk.
|
|
2454
|
+
*
|
|
2455
|
+
* @param project - Project whose root, include globs, and exclusions define membership.
|
|
2456
|
+
* @param file - Absolute file path to test.
|
|
2457
|
+
* @returns Whether the path matches files without matching excludes, node_modules, or .git.
|
|
2458
|
+
* Dependency traversal does not use this filter.
|
|
2459
|
+
*/
|
|
2460
|
+
includes(project, file) {
|
|
2461
|
+
const name = path.relative(project.analysis.host.root, file).replaceAll("\\", "/");
|
|
2462
|
+
/**
|
|
2463
|
+
* Matches this project-relative path, including dotfiles.
|
|
2464
|
+
* @param pattern - Include or exclude glob interpreted by minimatch.
|
|
2465
|
+
* @returns Whether the normalized path matches the pattern.
|
|
2466
|
+
*/
|
|
2467
|
+
const matches = (pattern) => minimatch(name, pattern, { dot: true });
|
|
2468
|
+
return project.config.files.some(matches) && ![
|
|
2469
|
+
"**/node_modules/**",
|
|
2470
|
+
"**/.git/**",
|
|
2471
|
+
...project.config.exclude ?? []
|
|
2472
|
+
].some(matches);
|
|
2473
|
+
}
|
|
2474
|
+
/**
|
|
2475
|
+
* Checks whether the project lints a stylesheet. Loading the project's CSS graph decides it.
|
|
2476
|
+
*
|
|
2477
|
+
* @param project - Project whose CSS graph lists its linted stylesheets.
|
|
2478
|
+
* @param file - Absolute file path to test.
|
|
2479
|
+
* @param editor - When false (the default), requires the original CSS graph to load successfully.
|
|
2480
|
+
* When true, retries a failed load with recovered definitions so completion, hover, and colors
|
|
2481
|
+
* can still identify stylesheet membership while the CSS is incomplete.
|
|
2482
|
+
* @returns Whether the file is the CSS entry or an imported file that the CSS host marks for
|
|
2483
|
+
* lint. Returns false for other extensions or when the selected loading mode fails. Ordinary
|
|
2484
|
+
* script analysis reports CSS loading failures.
|
|
2485
|
+
*/
|
|
2486
|
+
async lintsStylesheet(project, file, editor = false) {
|
|
2487
|
+
if (!isStylesheet(file)) return false;
|
|
2488
|
+
return (await project.analysis.stylesheets(editor).catch(() => [])).some((source) => sameFile(source, file));
|
|
2489
|
+
}
|
|
2490
|
+
/**
|
|
2491
|
+
* Enumerates existing target files independently of dependency traversal.
|
|
2492
|
+
*
|
|
2493
|
+
* @param project - Project whose files and excludes globs are relative to its host root.
|
|
2494
|
+
* @param patterns - Optional additional include globs relative to the same root. An empty list
|
|
2495
|
+
* adds no filtering. These patterns cannot expand the configured scope.
|
|
2496
|
+
* @param options - Target kinds to add to the configured script targets.
|
|
2497
|
+
* @returns Sorted absolute target paths. Unsaved files absent from disk are not enumerated.
|
|
2498
|
+
* @throws If filesystem enumeration fails.
|
|
2499
|
+
*/
|
|
2500
|
+
async targets(project, patterns, options = {}) {
|
|
2501
|
+
const filters = patterns?.map((pattern) => {
|
|
2502
|
+
if (path.isAbsolute(pattern)) return { file: path.normalize(pattern) };
|
|
2503
|
+
return { pattern: pattern.replace(/^(\.\/)+/, "") };
|
|
2504
|
+
});
|
|
2505
|
+
const files = await glob(project.config.files, {
|
|
2506
|
+
cwd: project.analysis.host.root,
|
|
2507
|
+
absolute: true,
|
|
2508
|
+
onlyFiles: true,
|
|
2509
|
+
dot: true,
|
|
2510
|
+
ignore: [
|
|
2511
|
+
"**/node_modules/**",
|
|
2512
|
+
"**/.git/**",
|
|
2513
|
+
...project.config.exclude ?? []
|
|
2514
|
+
]
|
|
2515
|
+
});
|
|
2516
|
+
if (options.stylesheets) files.push(...await project.analysis.stylesheets().catch(() => []));
|
|
2517
|
+
return files.filter((file, index) => files.findIndex((other) => sameFile(other, file)) === index && (!filters?.length || filters.some((filter) => filter.file !== void 0 ? path.normalize(file) === filter.file : minimatch(path.relative(project.analysis.host.root, file).replaceAll("\\", "/"), filter.pattern, { dot: true })))).sort();
|
|
2518
|
+
}
|
|
2519
|
+
/**
|
|
2520
|
+
* Keeps editor answers separate when several projects include the same target.
|
|
2521
|
+
*
|
|
2522
|
+
* @param file - Absolute target path used for independent scope checks.
|
|
2523
|
+
* @param request - Operation in the original document's UTF-16 coordinates.
|
|
2524
|
+
* @param signal - Optional cancellation forwarded to each project's queued query.
|
|
2525
|
+
* @returns Available answers in configuration order, including overlapping project memberships.
|
|
2526
|
+
* CSS membership checks allow recovered definitions when the original graph cannot load.
|
|
2527
|
+
* Plugin path completion and links also accept CSS files inside a project's root.
|
|
2528
|
+
* @throws If a project's editor query fails.
|
|
2529
|
+
*/
|
|
2530
|
+
async query(file, request, signal) {
|
|
2531
|
+
const results = [];
|
|
2532
|
+
for (const [index, project] of this.projects.entries()) {
|
|
2533
|
+
const relative = path.relative(project.analysis.host.root, file);
|
|
2534
|
+
const navigation = isStylesheet(file) && [
|
|
2535
|
+
"completion",
|
|
2536
|
+
"resolve",
|
|
2537
|
+
"links"
|
|
2538
|
+
].includes(request.kind) && relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
|
|
2539
|
+
if (!this.includes(project, file) && !navigation && !await this.lintsStylesheet(project, file, true)) continue;
|
|
2540
|
+
const result = await project.analysis.query(file, request, signal);
|
|
2541
|
+
if (result) results.push({
|
|
2542
|
+
project: index,
|
|
2543
|
+
config: project.configFile,
|
|
2544
|
+
result
|
|
2545
|
+
});
|
|
2546
|
+
}
|
|
2547
|
+
return results;
|
|
2548
|
+
}
|
|
2549
|
+
/**
|
|
2550
|
+
* Updates all hosts because an open file can be a dependency outside their target scope.
|
|
2551
|
+
*
|
|
2552
|
+
* @param file - File path resolved by each project from the process working directory if relative.
|
|
2553
|
+
* @param source - Complete unsaved document text.
|
|
2554
|
+
* @param version - Increasing safe integer for the open buffer. Identical repeated updates have no effect.
|
|
2555
|
+
* @throws If a project rejects the version. Updates already applied to earlier projects are retained.
|
|
2556
|
+
*/
|
|
2557
|
+
update(file, source, version) {
|
|
2558
|
+
for (const project of this.projects) project.analysis.update(file, source, version);
|
|
2559
|
+
this.#openDocuments.add(path.resolve(file));
|
|
2560
|
+
}
|
|
2561
|
+
/**
|
|
2562
|
+
* Removes a buffer from every project so later reads use its source provider.
|
|
2563
|
+
*
|
|
2564
|
+
* @param file - File path resolved in the same way as update. Unknown buffers have no effect.
|
|
2565
|
+
*/
|
|
2566
|
+
closeDocument(file) {
|
|
2567
|
+
this.#openDocuments.delete(path.resolve(file));
|
|
2568
|
+
for (const project of this.projects) project.analysis.closeDocument(file);
|
|
2569
|
+
}
|
|
2570
|
+
/**
|
|
2571
|
+
* Checks whether save or watch notifications need a new workspace.
|
|
2572
|
+
*
|
|
2573
|
+
* @param files - File paths reported by the notification. Relative paths use the working directory.
|
|
2574
|
+
* @returns True when every file has an open buffer and none is a configuration dependency,
|
|
2575
|
+
* a tsconfig, or package.json. This method does not read disk or reopen projects.
|
|
2576
|
+
*/
|
|
2577
|
+
refresh(files) {
|
|
2578
|
+
return files.every((file) => [...this.#openDocuments].some((open) => sameFile(open, file)) && !this.#configurationDependencies.some((dependency) => sameFile(dependency, file)) && !/(?:^|[/\\])(?:tsconfig(?:\.[^/\\]+)?\.json|package\.json)$/.test(file));
|
|
2579
|
+
}
|
|
2580
|
+
/**
|
|
2581
|
+
* Advances every project revision and requests CSS and resolver cache refresh before its next analysis.
|
|
2582
|
+
*/
|
|
2583
|
+
invalidate() {
|
|
2584
|
+
for (const project of this.projects) project.analysis.invalidate();
|
|
2585
|
+
}
|
|
2586
|
+
/**
|
|
2587
|
+
* Analyzes a target separately in every matching project and filters reports to each scope.
|
|
2588
|
+
* A project matches a script target in its configured scope and a stylesheet that it lints.
|
|
2589
|
+
*
|
|
2590
|
+
* @param file - Absolute target path. The file need not exist on disk when an open buffer supplies it.
|
|
2591
|
+
* @param signal - Optional cancellation checked by each project's queued analysis.
|
|
2592
|
+
* @returns Results in project order, or an empty list when no project includes the target.
|
|
2593
|
+
* Dependency information remains available even when its reports lie outside the target scope.
|
|
2594
|
+
*/
|
|
2595
|
+
async analyze(file, signal) {
|
|
2596
|
+
const results = [];
|
|
2597
|
+
for (const [index, project] of this.projects.entries()) if (this.includes(project, file) || await this.lintsStylesheet(project, file)) results.push({
|
|
2598
|
+
project: index,
|
|
2599
|
+
config: project.configFile,
|
|
2600
|
+
result: this.scopedResult(project, await project.analysis.analyze(file, signal))
|
|
2601
|
+
});
|
|
2602
|
+
return results;
|
|
2603
|
+
}
|
|
2604
|
+
/**
|
|
2605
|
+
* Analyzes every selected target, including files unreachable from an application entry, and
|
|
2606
|
+
* every stylesheet that a project lints.
|
|
2607
|
+
*
|
|
2608
|
+
* @param patterns - Optional additional globs relative to each project's root. Empty or omitted
|
|
2609
|
+
* filters check every configured target.
|
|
2610
|
+
* @returns Scoped results in project order, then sorted target order. Overlapping memberships remain separate.
|
|
2611
|
+
* @throws If target enumeration fails. Analysis failures are represented in individual results.
|
|
2612
|
+
*/
|
|
2613
|
+
async lint(patterns) {
|
|
2614
|
+
const results = [];
|
|
2615
|
+
for (const [index, project] of this.projects.entries()) {
|
|
2616
|
+
const files = await this.targets(project, patterns, { stylesheets: true });
|
|
2617
|
+
await project.analysis.prepare(files);
|
|
2618
|
+
for (const file of files) results.push({
|
|
2619
|
+
project: index,
|
|
2620
|
+
config: project.configFile,
|
|
2621
|
+
result: this.scopedResult(project, await project.analysis.analyze(file))
|
|
2622
|
+
});
|
|
2623
|
+
}
|
|
2624
|
+
return results;
|
|
2625
|
+
}
|
|
2626
|
+
/**
|
|
2627
|
+
* Prepares targets together in each project that includes them.
|
|
2628
|
+
*
|
|
2629
|
+
* @param files - Absolute target paths. Files outside a project's target globs are skipped.
|
|
2630
|
+
* @returns Completion of preparation. Each target's analysis reports its own source failures.
|
|
2631
|
+
*/
|
|
2632
|
+
async prepare(files) {
|
|
2633
|
+
for (const project of this.projects) await project.analysis.prepare(files.filter((file) => this.includes(project, file)));
|
|
2634
|
+
}
|
|
2635
|
+
/**
|
|
2636
|
+
* Keeps dependency context while filtering findings from known sources to the project's target scope.
|
|
2637
|
+
*
|
|
2638
|
+
* @param project - Project whose host and globs identify owned source documents.
|
|
2639
|
+
* @param result - Captured analysis with original document URIs.
|
|
2640
|
+
* @returns A copy with filtered reports. Reports for unknown source documents remain available.
|
|
2641
|
+
* @throws If a file URI in a report cannot be converted to a path.
|
|
2642
|
+
*/
|
|
2643
|
+
scopedResult(project, result) {
|
|
2644
|
+
return {
|
|
2645
|
+
...result,
|
|
2646
|
+
reports: result.reports.filter((report) => {
|
|
2647
|
+
const uri = report.primary.location.uri;
|
|
2648
|
+
if (uri.startsWith("file:")) {
|
|
2649
|
+
const file = fileURLToPath(uri);
|
|
2650
|
+
if (project.analysis.host.supports(file)) return this.includes(project, file);
|
|
2651
|
+
}
|
|
2652
|
+
const source = result.graph?.sources.find((source) => source.document.uri === uri);
|
|
2653
|
+
if (!source) return true;
|
|
2654
|
+
const file = uri.startsWith("file:") ? fileURLToPath(uri) : source.resolverId;
|
|
2655
|
+
return this.includes(project, file);
|
|
2656
|
+
})
|
|
2657
|
+
};
|
|
2658
|
+
}
|
|
2659
|
+
/**
|
|
2660
|
+
* Closes every project and waits for all cleanup attempts before reporting failures.
|
|
2661
|
+
*
|
|
2662
|
+
* @returns A promise that resolves after project cleanup.
|
|
2663
|
+
* @throws An AggregateError containing all project cleanup failures.
|
|
2664
|
+
*/
|
|
2665
|
+
async close() {
|
|
2666
|
+
const errors = (await Promise.allSettled(this.projects.map((project) => project.analysis.close()))).flatMap((result) => result.status === "rejected" ? [result.reason] : []);
|
|
2667
|
+
if (errors.length) throw new AggregateError(errors, "Failed to close Stillwind analysis hosts");
|
|
2668
|
+
}
|
|
2669
|
+
};
|
|
2670
|
+
export { AnalysisProject, AnalysisWorkspace, CompilationFailure, EditorProject, EditorSnapshot, PluginRuntime, TypeFactsError, TypeScriptFactsService, analyzeModule, attachPlugins, cleanModuleId, compileModule, compileWithPlugins, compilerModuleId, compilerOptions, composeCarrierSourceMap, composeFrameworkSourceMap, composeModuleSourceMap, createFileSystemAnalysisHost, createStylesheetResolver, cssEntrypoint, cssWithSourceMap, decodeCssSourceMap, defaultPluginExport, fileModuleDescriptor, fileSourceKind, finalizeCss, finalizeModuleWithMap, isStylesheet, lintsStylesheet, loadCssGraph, loadEditorCssGraph, moduleSourceMap, nodePluginHost, pluginLoader, resolveTypeFactsEnvironment, warnRejectedNames };
|
|
2671
|
+
|
|
2672
|
+
//# sourceMappingURL=index.js.map
|