@stillwind/host 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { A as compileWithPlugins, C as compileModule, D as fileSourceKind, E as cleanModuleId, M as prepareSourcePlugins, O as TypeFactsError, S as analyzeModule, T as CompilationFailure, _ as loadEditorCssGraph, a as pluginDirectory, b as cssBannerPrefix, c as CheckerSource, d as CompilationProject, f as sourceKey, g as loadCssGraph, h as lintsStylesheet, i as completePluginPaths, j as pluginLoader, k as attachPlugins, l as checkerId, m as isStylesheet, n as cssEntrypoint, o as queryPluginPaths, p as queryDesignSystem, r as StylesheetEditor, s as EditorSnapshot, t as compilerOptions, u as withRequestedProbes, v as PluginRuntime, w as warnRejectedNames, x as finalizeCss, y as defaultPluginExport } from "./options-PMjJ1c8W.js";
1
+ import { A as fileSourceKind, C as CompilationFailure, D as ResolutionMismatchError, E as CompilationProject, F as prepareSourcePlugins, M as attachPlugins, N as compileWithPlugins, O as sourceKey, P as pluginLoader, S as warnRejectedNames, T as tracePhase, _ as defaultPluginExport, a as pluginDirectory, b as analyzeModule, c as CheckerSource, d as queryDesignSystem, f as isStylesheet, g as PluginRuntime, h as loadEditorCssGraph, i as completePluginPaths, j as TypeFactsError, k as cleanModuleId, l as checkerId, m as loadCssGraph, n as cssEntrypoint, o as queryPluginPaths, p as lintsStylesheet, r as StylesheetEditor, s as EditorSnapshot, t as compilerOptions, u as withRequestedProbes, v as cssBannerPrefix, w as startPhase, x as compileModule, y as finalizeCss } from "./options-CHkqG1Gc.js";
2
2
  import { createRequire, syncBuiltinESMExports } from "node:module";
3
3
  import { NativeProjectSession, fingerprint } from "@stillwind/native";
4
4
  import path, { isAbsolute, relative, resolve } from "node:path";
@@ -9,8 +9,9 @@ import { TraceMap, decodedMappings, originalPositionFor, sourceContentFor } from
9
9
  import { createHash } from "node:crypto";
10
10
  import { existsSync } from "node:fs";
11
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";
12
+ import { isCallExpression, isExportDeclaration, isExpression, isImportDeclaration, isSourceFile, isStringLiteral } from "tsrs/ast/is";
13
+ import { serverFS } from "tsrs/fs";
14
+ import { API, SignatureKind, SymbolFlags, TypeFlags } from "tsrs/sync";
14
15
  import childProcess from "node:child_process";
15
16
  import { captureProjectConfig } from "@stillwind/config";
16
17
  import { readFile, readdir, stat } from "node:fs/promises";
@@ -278,16 +279,30 @@ function cssWithSourceMap(output, replacements, upstream, includeSourcesContent
278
279
  * @throws If a recognized inline map contains invalid JSON.
279
280
  */
280
281
  function decodeCssSourceMap(css) {
281
- const match = /\n\/\*# sourceMappingURL=data:application\/json;base64,([A-Za-z0-9+/=]+) \*\/$/.exec(css);
282
- if (!match) return {
282
+ const prefix = "\n/*# sourceMappingURL=data:application/json;base64,";
283
+ const suffix = " */";
284
+ const start = css.lastIndexOf(prefix);
285
+ const payload = start >= 0 && css.endsWith(suffix) ? css.slice(start + 51, css.length - 3) : "";
286
+ if (!payload || !isBase64(payload)) return {
283
287
  code: css,
284
288
  map: null
285
289
  };
286
290
  return {
287
- code: css.slice(0, match.index),
288
- map: JSON.parse(Buffer.from(match[1], "base64").toString("utf8"))
291
+ code: css.slice(0, start),
292
+ map: JSON.parse(Buffer.from(payload, "base64").toString("utf8"))
289
293
  };
290
294
  }
295
+ /**
296
+ * Tests whether text contains only base64 alphabet and padding characters.
297
+ *
298
+ * @param text - Text to test.
299
+ * @returns True when every character is `A`-`Z`, `a`-`z`, `0`-`9`, `+`, `/`, or `=`. Empty text
300
+ * also passes.
301
+ */
302
+ function isBase64(text) {
303
+ for (const character of text) if (!(character >= "A" && character <= "Z") && !(character >= "a" && character <= "z") && !(character >= "0" && character <= "9") && character !== "+" && character !== "/" && character !== "=") return false;
304
+ return true;
305
+ }
291
306
  // src/semantics/node/project.ts
292
307
  /**
293
308
  * Normalizes filesystem names used as keys in the virtual checker overlay.
@@ -300,6 +315,8 @@ const normalize = (fileName) => {
300
315
  const name = path.resolve(fileName).replaceAll("\\", "/");
301
316
  return process.platform === "win32" ? name.toLowerCase() : name;
302
317
  };
318
+ /** Shared empty declaration list, so that cached buffers of sources without assets stay valid. */
319
+ const noAssets = [];
303
320
  /**
304
321
  * Selects the TypeScript environment before starting a checker.
305
322
  *
@@ -332,11 +349,14 @@ function resolveTypeFactsEnvironment(root, tsconfig) {
332
349
  * @param project - Consumer configuration to inherit, or isolated compiler defaults.
333
350
  * @param inputs - Captured file replacements and declarations required by this collection.
334
351
  * @param configuredDeclarations - Declaration files selected by the consumer's tsconfig.
352
+ * @param cache - Optional buffers to reuse. A source object reuses its buffers when its assets array
353
+ * and import targets are the same. The source object must not change in other ways while it is
354
+ * cached. New buffers are stored in the cache.
335
355
  * @returns Virtual text and range mappings without writing any files to disk.
336
356
  * @throws If checker edits or projection maps are invalid, or an original probe has no
337
357
  * checker-buffer correspondence.
338
358
  */
339
- function prepareProject(sources, assetsByModuleId, shadowTsconfigPath, project, inputs, configuredDeclarations) {
359
+ function prepareProject(sources, assetsByModuleId, shadowTsconfigPath, project, inputs, configuredDeclarations, cache) {
340
360
  const virtualFiles = new Map([...inputs.overlayFiles ?? [], ...inputs.ambientDeclarations ?? []].map(([name, text]) => [normalize(name), text]));
341
361
  const mappings = [];
342
362
  const allIdentities = /* @__PURE__ */ new Map();
@@ -350,13 +370,22 @@ function prepareProject(sources, assetsByModuleId, shadowTsconfigPath, project,
350
370
  virtualFiles.set(id, declarations);
351
371
  globals.add(id);
352
372
  }
353
- const syntax = source.kind === "direct" ? source.syntax : source.projection.syntax;
354
- const buffers = source.checkerBuffers ?? [{
355
- source: source.kind === "direct" ? source.document.code : source.projection.code,
356
- language: syntax.language === "tsx" || syntax.language === "jsx" ? "tsx" : "ts"
357
- }];
358
- for (const [index, buffer] of buffers.entries()) {
359
- const shadow = new CheckerSource(source, buffer, index, assetsByModuleId.get(source.moduleId) ?? [], ids);
373
+ const assets = assetsByModuleId.get(source.moduleId) ?? noAssets;
374
+ const targets = (source.resolutions ?? []).map((item) => `${item.start}:${item.end}:${ids.get(item.id) ?? item.id}`).join("\n");
375
+ let cached = cache?.get(source);
376
+ if (cached?.assets !== assets || cached.targets !== targets) {
377
+ const syntax = source.kind === "direct" ? source.syntax : source.projection.syntax;
378
+ cached = {
379
+ assets,
380
+ targets,
381
+ mappings: (source.checkerBuffers ?? [{
382
+ source: source.kind === "direct" ? source.document.code : source.projection.code,
383
+ language: syntax.language === "tsx" || syntax.language === "jsx" ? "tsx" : "ts"
384
+ }]).map((buffer, index) => new CheckerSource(source, buffer, index, assets, ids))
385
+ };
386
+ cache?.set(source, cached);
387
+ }
388
+ for (const shadow of cached.mappings) {
360
389
  virtualFiles.set(normalize(shadow.id), shadow.text);
361
390
  if (shadow.helperModule) virtualFiles.set(normalize(shadow.helperModule.id), shadow.helperModule.text);
362
391
  mappings.push(shadow);
@@ -509,7 +538,7 @@ function factsForSource(sourceFile, mapping, decoder, nodes, typesAt, unverified
509
538
  *
510
539
  * The TypeScript API starts its checker with `spawn` and has no option for `windowsHide`. Under
511
540
  * Electron, `Code.exe` is a Windows GUI program that has no console, so Windows opens a visible
512
- * console for `tsc.exe` unless the spawn call hides it.
541
+ * console for `tsrs.exe` unless the spawn call hides it.
513
542
  *
514
543
  * @param action - Synchronous function that starts processes. Asynchronous work after it returns
515
544
  * uses the original `spawn`.
@@ -600,11 +629,12 @@ var NodeChecker = class {
600
629
  * @param sources - Prepared sources and probes for this request.
601
630
  * @param assets - Declarations grouped by compiler module ID.
602
631
  * @param inputs - Overlays and ambient declarations used for config reads and checker files.
632
+ * @param cache - Checker buffers to reuse and update, as {@link prepareProject} describes.
603
633
  * @returns Virtual files, checker mappings, and declaration identities for the supplied sources.
604
634
  * @throws If configuration parsing, checker mapping, or declaration preparation fails.
605
635
  */
606
- prepareProject(sources, assets, inputs) {
607
- return prepareProject(sources, assets, this.#shadowTsconfigPath, this.#project, inputs, this.#configuredDeclarations(inputs));
636
+ prepareProject(sources, assets, inputs, cache) {
637
+ return prepareProject(sources, assets, this.#shadowTsconfigPath, this.#project, inputs, this.#configuredDeclarations(inputs), cache);
608
638
  }
609
639
  /**
610
640
  * Queries types once per expression in the current snapshot.
@@ -676,20 +706,27 @@ var NodeChecker = class {
676
706
  fs: {
677
707
  directoryExists: (directoryName) => {
678
708
  const prefix = normalize(directoryName).replace(/\/$/, "") + "/";
679
- return [...this.#virtualFiles.keys()].some((name) => name.startsWith(prefix)) ? true : void 0;
709
+ return [...this.#virtualFiles.keys()].some((name) => name.startsWith(prefix)) ? true : serverFS.useOS;
680
710
  },
681
711
  fileExists: (fileName) => {
682
712
  this.dependencies.add(fileName);
683
- return this.#virtualFiles.has(normalize(fileName)) ? true : void 0;
713
+ return this.#virtualFiles.has(normalize(fileName)) ? true : serverFS.useOS;
684
714
  },
715
+ getAccessibleEntries: serverFS.useOS,
685
716
  readFile: (fileName) => {
686
717
  const overlay = this.#virtualFiles.get(normalize(fileName));
687
718
  if (overlay === void 0) {
688
719
  this.dependencies.add(fileName);
689
720
  this.stats.diskReadRequests += 1;
690
- } else this.stats.overlayReads += 1;
721
+ return serverFS.useOS;
722
+ }
723
+ this.stats.overlayReads += 1;
691
724
  return overlay;
692
- }
725
+ },
726
+ realpath: (fileName) => this.#virtualFiles.has(normalize(fileName)) ? serverFS.identity : serverFS.useOS,
727
+ stat: (fileName) => this.#virtualFiles.has(normalize(fileName)) ? serverFS.fakeStat : serverFS.useOS,
728
+ writeFile: serverFS.noop,
729
+ removeFile: serverFS.noop
693
730
  }
694
731
  }));
695
732
  }
@@ -738,21 +775,24 @@ var NodeChecker = class {
738
775
  for (const fileName of this.#virtualFiles.keys()) if (!prepared.virtualFiles.has(fileName)) (existsSync(fileName) ? changed : deleted).push(fileName);
739
776
  this.#virtualFiles = prepared.virtualFiles;
740
777
  if (this.#snapshot && changed.length === 0 && created.length === 0 && deleted.length === 0) {
741
- const project = this.#snapshot.getProject(this.#shadowTsconfigPath);
778
+ const project = this.#snapshot.getConfiguredProject(this.#shadowTsconfigPath);
742
779
  if (project) return project;
743
780
  }
744
781
  this.#clearQueries();
745
- const next = this.#snapshot ? this.#api.updateSnapshot({ fileChanges: {
746
- changed,
747
- created,
748
- deleted
749
- } }) : this.#api.updateSnapshot({ openProjects: [this.#shadowTsconfigPath] });
782
+ const next = this.#snapshot ? this.#snapshot.update({
783
+ fileNotifications: {
784
+ changed,
785
+ created,
786
+ deleted
787
+ },
788
+ ensurePrograms: true
789
+ }) : this.#api.createSnapshot({ openProjects: [this.#shadowTsconfigPath] });
750
790
  this.stats.snapshots += 1;
751
791
  if (this.#snapshot) this.stats.incrementalSnapshots += 1;
752
792
  this.#snapshot?.dispose();
753
793
  this.#snapshot = next;
754
- const project = next.getProject(this.#shadowTsconfigPath);
755
- if (!project) throw new Error("TypeScript 7 could not open the Stillwind shadow project");
794
+ const project = next.getConfiguredProject(this.#shadowTsconfigPath);
795
+ if (!project) throw new Error("tsrs could not open the Stillwind shadow project");
756
796
  return project;
757
797
  }
758
798
  /**
@@ -1006,6 +1046,80 @@ var AssetTypeDecoder = class {
1006
1046
  };
1007
1047
  }
1008
1048
  };
1049
+ // src/semantics/node/export-interface.ts
1050
+ /** Types that the walk describes by their printed form. */
1051
+ const printedTypeFlags = TypeFlags.Any | TypeFlags.Unknown | TypeFlags.StringLike | TypeFlags.NumberLike | TypeFlags.BigIntLike | TypeFlags.BooleanLike | TypeFlags.EnumLike | TypeFlags.ESSymbolLike | TypeFlags.Null | TypeFlags.Undefined | TypeFlags.Void | TypeFlags.Never | TypeFlags.NonPrimitive | TypeFlags.TypeParameter;
1052
+ /** Nesting depth after which the walk gives up and reports no interface. */
1053
+ const maxDepth = 12;
1054
+ /** Number of visited types after which the walk gives up and reports no interface. */
1055
+ const maxTypes = 2e3;
1056
+ /** Signals that a type is too large or too deep to describe. */
1057
+ var InterfaceLimit = class extends Error {};
1058
+ /**
1059
+ * Describes the exports of a checker file as consumers observe them through type facts.
1060
+ *
1061
+ * The description names each export with the decoded candidates of asset types and the structure
1062
+ * of other types. It omits the parts of an asset type that facts do not read, such as the utility
1063
+ * strings in the output type of a style, so an edit of those strings keeps the description. A type
1064
+ * declared in a package or library file is described by its name and type arguments, because its
1065
+ * declaration does not change while the project is edited.
1066
+ *
1067
+ * @param checker - Checker of the snapshot that contains `file`.
1068
+ * @param file - Checker file whose exports are described.
1069
+ * @param decoder - Decoder with the producer types of `file` and the files it imports registered.
1070
+ * @returns A string that is equal for two snapshots when consumers read the same facts from the
1071
+ * exports, or undefined when the exports are too large or too deep to describe. Undefined must be
1072
+ * treated as a changed interface.
1073
+ */
1074
+ function exportInterface(checker, file, decoder) {
1075
+ const module = checker.getSymbolAtLocation(file);
1076
+ if (!module) return "";
1077
+ const visited = /* @__PURE__ */ new Map();
1078
+ const walk = (type, depth) => {
1079
+ if (!type) return "?";
1080
+ if (type.flags & printedTypeFlags) return checker.typeToString(type);
1081
+ const seen = visited.get(type.id);
1082
+ if (seen !== void 0) return `@${seen}`;
1083
+ if (depth > maxDepth || visited.size >= maxTypes) throw new InterfaceLimit();
1084
+ visited.set(type.id, visited.size);
1085
+ const decoded = decoder.decode(type, true);
1086
+ if (decoded.kind === "asset") return `asset${JSON.stringify(decoded.value)}`;
1087
+ if (type.isUnionType() || type.isIntersectionType()) return `(${type.getTypes().map((member) => walk(member, depth + 1)).sort().join(type.isUnionType() ? "|" : "&")})`;
1088
+ const symbol = type.getAliasSymbol() ?? type.getSymbol();
1089
+ if (symbol && declaredOutsideProject(symbol)) {
1090
+ const args = type.getAliasSymbol() ? type.getAliasTypeArguments() : type.isTypeReference() ? checker.getTypeArguments(type) : [];
1091
+ return `${symbol.name}<${args.map((arg) => walk(arg, depth + 1)).join(",")}>`;
1092
+ }
1093
+ if (!type.isObjectType()) return checker.typeToString(type);
1094
+ const parts = checker.getPropertiesOfType(type).map((property) => `${property.name}${property.flags & SymbolFlags.Optional ? "?" : ""}:${walk(checker.getTypeOfSymbol(property), depth + 1)}`);
1095
+ for (const [kind, label] of [[SignatureKind.Call, "call"], [SignatureKind.Construct, "new"]]) for (const signature of checker.getSignaturesOfType(type, kind)) {
1096
+ const parameters = signature.parameters.map((_, index) => walk(checker.getParameterType(signature, index), depth + 1));
1097
+ parts.push(`${label}(${parameters.join(",")})=>${walk(checker.getReturnTypeOfSignature(signature), depth + 1)}`);
1098
+ }
1099
+ for (const info of checker.getIndexInfosOfType(type)) parts.push(`[${walk(info.keyType, depth + 1)}]:${walk(info.valueType, depth + 1)}`);
1100
+ return `{${parts.join(";")}}`;
1101
+ };
1102
+ try {
1103
+ return checker.getExportsOfModule(module).map((exported) => {
1104
+ const target = exported.flags & SymbolFlags.Alias ? checker.getAliasedSymbol(exported) : exported;
1105
+ const value = target.flags & SymbolFlags.Value ? walk(checker.getTypeOfSymbol(target), 0) : "";
1106
+ const declared = target.flags & SymbolFlags.Type ? walk(checker.getDeclaredTypeOfSymbol(target), 0) : "";
1107
+ return `${exported.name}=${value}/${declared}`;
1108
+ }).join("\n");
1109
+ } catch (error) {
1110
+ if (error instanceof InterfaceLimit) return;
1111
+ throw error;
1112
+ }
1113
+ }
1114
+ /**
1115
+ * Tests whether every declaration of a symbol is in a package or a TypeScript library file.
1116
+ *
1117
+ * @param symbol - Symbol of a type or type alias.
1118
+ * @returns False when the symbol has no declarations or one of them is in a project file.
1119
+ */
1120
+ function declaredOutsideProject(symbol) {
1121
+ return symbol.declarations.length > 0 && symbol.declarations.every((declaration) => declaration.path.includes("/node_modules/") || /\/lib\.[^/]*\.d\.ts$/.test(declaration.path));
1122
+ }
1009
1123
  // src/semantics/node/service.ts
1010
1124
  /**
1011
1125
  * Collects declaration facts with a reusable Node checker. Close the service after pending queries finish.
@@ -1016,6 +1130,13 @@ var TypeScriptFactsService = class {
1016
1130
  /** Checker buffers prepared from the installed project inputs. */
1017
1131
  #prepared;
1018
1132
  /**
1133
+ * Producer types registered for one prepared project in one checker snapshot. Queries against
1134
+ * the same installed project reuse it until the snapshot or the preparation changes.
1135
+ */
1136
+ #decoder;
1137
+ /** Checker buffers of earlier preparations, reused while their inputs stay the same. */
1138
+ #checkerSources = /* @__PURE__ */ new WeakMap();
1139
+ /**
1019
1140
  * Whether close has been requested. Subsequent collections reject and repeated close calls do
1020
1141
  * nothing.
1021
1142
  */
@@ -1132,6 +1253,35 @@ var TypeScriptFactsService = class {
1132
1253
  return result;
1133
1254
  }
1134
1255
  /**
1256
+ * Describes the exports of an installed source as consumers read them through facts.
1257
+ *
1258
+ * @param resolverId - Resolver identity of a source passed to {@link setProjectSources}.
1259
+ * @returns A description that is equal in two installations when consumers read the same facts
1260
+ * from the exports. Returns undefined when the service is closed, no project is installed, the
1261
+ * source is not installed, the exports are too large to describe, or the checker fails.
1262
+ */
1263
+ exportInterface(resolverId) {
1264
+ if (this.#closed || !this.#installed) return;
1265
+ try {
1266
+ const { sources, assets, inputs } = this.#installed;
1267
+ const prepared = this.#prepare(sources, assets, inputs);
1268
+ const mappings = prepared.mappings.filter((mapping) => mapping.source.resolverId === resolverId);
1269
+ if (mappings.length === 0) return;
1270
+ const project = tracePhase("checker-update", prepared.mappings.length, () => this.#checker.updateProject(prepared));
1271
+ const decoder = this.#producers(project, prepared, mappings);
1272
+ const parts = [];
1273
+ for (const mapping of mappings) {
1274
+ const file = project.program.getSourceFile(mapping.id);
1275
+ const description = file && exportInterface(project.checker, file, decoder);
1276
+ if (description === void 0) return;
1277
+ parts.push(description);
1278
+ }
1279
+ return parts.join("\n\n");
1280
+ } catch {
1281
+ return;
1282
+ }
1283
+ }
1284
+ /**
1135
1285
  * Prepares one request and retries an unexpected checker failure once with a clean API.
1136
1286
  *
1137
1287
  * @param sources - Prepared sources and original UTF-8 probes.
@@ -1143,34 +1293,33 @@ var TypeScriptFactsService = class {
1143
1293
  */
1144
1294
  #collect(sources, assetsByModuleId, inputs, available) {
1145
1295
  if (this.#closed) throw new Error("TypeScript facts service is closed");
1146
- if (this.#installed) {
1147
- const updated = withRequestedProbes(this.#installed.sources, sources);
1148
- if (updated !== this.#installed.sources) {
1149
- this.#installed = {
1150
- ...this.#installed,
1151
- sources: updated
1152
- };
1153
- this.#prepared = void 0;
1296
+ let full;
1297
+ if (this.#installed && !installedText(this.#installed.sources, sources)) full = tracePhase("checker-prepare", sources.length, () => this.#checker.prepareProject(sources, assetsByModuleId, inputs, this.#checkerSources));
1298
+ else {
1299
+ if (this.#installed) {
1300
+ const updated = withRequestedProbes(this.#installed.sources, sources);
1301
+ if (updated !== this.#installed.sources) {
1302
+ this.#installed = {
1303
+ ...this.#installed,
1304
+ sources: updated
1305
+ };
1306
+ this.#prepared = void 0;
1307
+ }
1154
1308
  }
1309
+ full = this.#prepare(sources, assetsByModuleId, inputs);
1155
1310
  }
1156
- const full = this.#prepare(sources, assetsByModuleId, inputs);
1157
1311
  const selected = new Set(sources.map((source) => source.resolverId));
1158
1312
  const mappings = full.mappings.filter((mapping) => selected.has(mapping.source.resolverId));
1159
- const prepared = {
1160
- ...full,
1161
- mappings,
1162
- identities: new Map(mappings.flatMap((mapping) => [...mapping.identities]))
1163
- };
1164
1313
  try {
1165
- return this.#collectPrepared(prepared, available);
1314
+ return this.#collectPrepared(full, mappings, available);
1166
1315
  } catch (firstError) {
1167
1316
  if (firstError instanceof TypeFactsError) throw firstError;
1168
1317
  this.stats.restarts += 1;
1169
1318
  this.#restartApi();
1170
1319
  try {
1171
- return this.#collectPrepared(prepared, available);
1320
+ return this.#collectPrepared(full, mappings, available);
1172
1321
  } catch (retryError) {
1173
- throw new AggregateError([firstError, retryError], `TypeScript 7 checker failed before and after a clean restart: ${String(retryError)}`);
1322
+ throw new AggregateError([firstError, retryError], `tsrs checker failed before and after a clean restart: ${String(retryError)}`);
1174
1323
  }
1175
1324
  }
1176
1325
  }
@@ -1187,13 +1336,63 @@ var TypeScriptFactsService = class {
1187
1336
  #prepare(sources, assets, inputs, resolutionOnly = false) {
1188
1337
  if (this.#installed && this.#prepared) return this.#prepared;
1189
1338
  if (this.#installed) try {
1190
- this.#prepared = this.#checker.prepareProject(this.#installed.sources, this.#installed.assets, this.#installed.inputs);
1339
+ const installed = this.#installed;
1340
+ this.#prepared = tracePhase("checker-prepare", installed.sources.length, () => this.#checker.prepareProject(installed.sources, installed.assets, installed.inputs, this.#checkerSources));
1191
1341
  return this.#prepared;
1192
1342
  } catch {}
1193
- return this.#checker.prepareProject(resolutionOnly ? sources.map((source) => ({
1343
+ return tracePhase("checker-prepare", sources.length, () => this.#checker.prepareProject(resolutionOnly ? sources.map((source) => ({
1194
1344
  ...source,
1195
1345
  probes: []
1196
- })) : sources, assets, inputs);
1346
+ })) : sources, assets, inputs, this.#checkerSources));
1347
+ }
1348
+ /**
1349
+ * Registers the producer types of the selected buffers and of every prepared buffer that they
1350
+ * import, directly or indirectly. Queries against the same preparation in the same checker
1351
+ * snapshot share the registrations, so each buffer is registered once per snapshot.
1352
+ *
1353
+ * Facts of a buffer can name declarations of any buffer that it imports, so the facts of a
1354
+ * buffer do not depend on the other buffers of a query.
1355
+ *
1356
+ * @param project - Checker project of the current snapshot.
1357
+ * @param prepared - Preparation that produced the snapshot's virtual files.
1358
+ * @param selected - Buffers whose facts the query reads.
1359
+ * @returns A decoder for the identities of `prepared`.
1360
+ */
1361
+ #producers(project, prepared, selected) {
1362
+ if (this.#decoder?.snapshot !== this.stats.snapshots || this.#decoder.prepared !== prepared) this.#decoder = {
1363
+ snapshot: this.stats.snapshots,
1364
+ prepared,
1365
+ decoder: new AssetTypeDecoder(project.checker, prepared.identities, this.#checker.properties),
1366
+ registered: /* @__PURE__ */ new Set()
1367
+ };
1368
+ const { decoder, registered } = this.#decoder;
1369
+ const bySource = /* @__PURE__ */ new Map();
1370
+ for (const mapping of prepared.mappings) {
1371
+ const key = mapping.source.resolverId;
1372
+ bySource.set(key, [...bySource.get(key) ?? [], mapping]);
1373
+ }
1374
+ const pending = [...selected];
1375
+ const reached = /* @__PURE__ */ new Set();
1376
+ const unregistered = [];
1377
+ while (pending.length > 0) {
1378
+ const mapping = pending.pop();
1379
+ if (reached.has(mapping.id)) continue;
1380
+ reached.add(mapping.id);
1381
+ if (!registered.has(mapping.id)) unregistered.push(mapping);
1382
+ for (const resolution of mapping.source.resolutions ?? []) pending.push(...bySource.get(resolution.id) ?? []);
1383
+ }
1384
+ if (unregistered.length === 0) return decoder;
1385
+ const end = startPhase("checker-producers");
1386
+ const producers = [];
1387
+ for (const mapping of unregistered) {
1388
+ registered.add(mapping.id);
1389
+ const file = project.program.getSourceFile(mapping.id);
1390
+ if (!file) continue;
1391
+ producers.push(...this.#checker.expressions(file).filter((node) => isCallExpression(node) && mapping.producers.has(`${node.getStart(file)}:${node.end}`)));
1392
+ }
1393
+ for (const type of this.#checker.types(project.checker, producers)) if (type) decoder.register(type);
1394
+ end(producers.length);
1395
+ return decoder;
1197
1396
  }
1198
1397
  /**
1199
1398
  * Marks the service closed, disposes its retained snapshot, and closes the checker API. Repeated
@@ -1217,31 +1416,25 @@ var TypeScriptFactsService = class {
1217
1416
  if (!this.#closed) this.#restartApi();
1218
1417
  }
1219
1418
  /**
1220
- * Updates the snapshot and collects facts from the prepared checker buffers.
1419
+ * Updates the snapshot and collects facts from the selected checker buffers.
1221
1420
  *
1222
1421
  * @param prepared - Virtual files, original-coordinate mappings, and serialized declaration identities.
1422
+ * @param selected - Mappings of `prepared` whose facts and diagnostics the query requests.
1223
1423
  * @param available - Whether contract failures become unverified ranges where recovery is possible.
1224
1424
  * @returns Deduplicated facts by compiler identity and unverified original UTF-8 ranges.
1225
1425
  * @throws If snapshot update fails, a checker file is missing, facts conflict, or strict collection fails.
1226
1426
  */
1227
- #collectPrepared(prepared, available) {
1228
- const project = this.#checker.updateProject(prepared);
1427
+ #collectPrepared(prepared, selected, available) {
1428
+ const project = tracePhase("checker-update", prepared.mappings.length, () => this.#checker.updateProject(prepared));
1229
1429
  const unverified = [];
1230
1430
  const result = /* @__PURE__ */ new Map();
1231
- const decoder = new AssetTypeDecoder(project.checker, prepared.identities, this.#checker.properties);
1232
- const producers = [];
1233
- for (const mapping of prepared.mappings) {
1234
- const file = project.program.getSourceFile(mapping.id);
1235
- if (!file) continue;
1236
- producers.push(...this.#checker.expressions(file).filter((node) => isCallExpression(node) && mapping.producers.has(`${node.getStart(file)}:${node.end}`)));
1237
- }
1238
- for (const type of this.#checker.types(project.checker, producers)) if (type) decoder.register(type);
1239
- for (const mapping of prepared.mappings) {
1431
+ const decoder = this.#producers(project, prepared, selected);
1432
+ for (const mapping of selected) {
1240
1433
  const sourceFile = project.program.getSourceFile(mapping.id);
1241
- if (!sourceFile) throw new Error(`TypeScript 7 omitted ${mapping.id}`);
1434
+ if (!sourceFile) throw new Error(`tsrs omitted ${mapping.id}`);
1242
1435
  let diagnostics = this.#checker.diagnostics.get(mapping.id);
1243
1436
  if (!diagnostics) {
1244
- diagnostics = [...project.program.getSyntacticDiagnostics(mapping.id), ...project.program.getSemanticDiagnostics(mapping.id)];
1437
+ diagnostics = tracePhase("checker-diagnostics", 1, () => [...project.program.getSyntacticDiagnostics(mapping.id), ...project.program.getSemanticDiagnostics(mapping.id)]);
1245
1438
  this.#checker.diagnostics.set(mapping.id, diagnostics);
1246
1439
  }
1247
1440
  const diagnostic = diagnostics.find((d) => !producerArgumentDiagnostic(d, sourceFile, mapping) && /stillwind\/v1:|StyleResult|StyleRef|StyleKeyframes|StyleViewTransition|StyleStoredVariant|__stillwindDeclarationIdentity|data-__stillwindStyleIdentity/.test(diagnosticText(d)));
@@ -1258,7 +1451,7 @@ var TypeScriptFactsService = class {
1258
1451
  reason: error.message
1259
1452
  });
1260
1453
  }
1261
- const facts = factsForSource(sourceFile, mapping, decoder, this.#checker.expressions(sourceFile), (nodes) => this.#checker.types(project.checker, nodes), available ? unverified : void 0);
1454
+ const facts = tracePhase("checker-facts", 1, () => factsForSource(sourceFile, mapping, decoder, this.#checker.expressions(sourceFile), (nodes) => this.#checker.types(project.checker, nodes), available ? unverified : void 0));
1262
1455
  const previous = result.get(mapping.source.moduleId) ?? [];
1263
1456
  for (const fact of facts) {
1264
1457
  const existing = previous.find((value) => value.start === fact.start && value.end === fact.end);
@@ -1277,9 +1470,21 @@ var TypeScriptFactsService = class {
1277
1470
  */
1278
1471
  #restartApi() {
1279
1472
  this.#prepared = void 0;
1473
+ this.#decoder = void 0;
1280
1474
  this.#checker.restart();
1281
1475
  }
1282
1476
  };
1477
+ /**
1478
+ * Tests whether the installed project provides the text of every requested source.
1479
+ *
1480
+ * @param installed - Sources installed in the checker.
1481
+ * @param requested - Sources of one query.
1482
+ * @returns False when a requested source is missing or has different text.
1483
+ */
1484
+ function installedText(installed, requested) {
1485
+ const texts = new Map(installed.map((source) => [source.resolverId, source.document.code]));
1486
+ return requested.every((source) => texts.get(source.resolverId) === source.document.code);
1487
+ }
1283
1488
  // src/project/diagnostic-map.ts
1284
1489
  /**
1285
1490
  * Maps reports through upstream loader maps to their original source documents.
@@ -1296,6 +1501,7 @@ async function mapAnalysisReports(reports, sources, read) {
1296
1501
  const documents = new Map(sources.map((source) => [source.document.uri, source]));
1297
1502
  /**
1298
1503
  * Maps a location when both endpoints identify exact segments in the same original file.
1504
+ *
1299
1505
  * @param location - Prepared document range with zero-based lines and UTF-16 columns.
1300
1506
  * @param exact - Whether the mapped and prepared ranges must contain identical text.
1301
1507
  * @returns The original location when no upstream map exists, a mapped location, or undefined
@@ -1317,6 +1523,7 @@ async function mapAnalysisReports(reports, sources, read) {
1317
1523
  const mappings = decodedMappings(trace);
1318
1524
  /**
1319
1525
  * Checks whether a generated position has a segment containing an original source position.
1526
+ *
1320
1527
  * @param line - Zero-based generated line.
1321
1528
  * @param column - Zero-based UTF-16 column that must equal a segment start.
1322
1529
  * @returns Whether a matching segment exists, or undefined when the line has no mappings.
@@ -1329,6 +1536,7 @@ async function mapAnalysisReports(reports, sources, read) {
1329
1536
  const code = sourceContentFor(trace, start.source) ?? await read(fileURLToPath(uri));
1330
1537
  /**
1331
1538
  * Converts an original map position to an offset in the captured text.
1539
+ *
1332
1540
  * @param line - One-based original line.
1333
1541
  * @param column - Nonnegative UTF-16 column that excludes a trailing carriage return.
1334
1542
  * @returns A UTF-16 offset, or undefined when the line or column exceeds the text bounds.
@@ -1356,6 +1564,7 @@ async function mapAnalysisReports(reports, sources, read) {
1356
1564
  };
1357
1565
  /**
1358
1566
  * Maps a label or limits it to document scope when its range cannot be mapped.
1567
+ *
1359
1568
  * @param value - Label in a prepared document. The input object is not mutated.
1360
1569
  * @returns A copied label. A readable file fallback receives a current fingerprint and zero range.
1361
1570
  * @throws If map decoding or a required file read fails.
@@ -2159,6 +2368,7 @@ var EditorProject = class {
2159
2368
  };
2160
2369
  /**
2161
2370
  * Requires this analysis to retain the captured project revision and an active signal.
2371
+ *
2162
2372
  * @throws If cancellation or a newer project revision makes this analysis obsolete.
2163
2373
  */
2164
2374
  const assertActive = () => {
@@ -2227,6 +2437,7 @@ var EditorProject = class {
2227
2437
  /**
2228
2438
  * Lists disk children for plugin completion and plugin directory reads, following
2229
2439
  * directory symlinks.
2440
+ *
2230
2441
  * @param id - Absolute directory to enumerate without loading its scripts.
2231
2442
  * @returns Immediate entries in filesystem order. Broken symlinks are treated as files.
2232
2443
  * @throws If the directory cannot be read.
@@ -2815,6 +3026,6 @@ var AnalysisWorkspace = class AnalysisWorkspace {
2815
3026
  if (errors.length) throw new AggregateError(errors, "Failed to close Stillwind analysis hosts");
2816
3027
  }
2817
3028
  };
2818
- 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, queryDesignSystem, resolveTypeFactsEnvironment, warnRejectedNames };
3029
+ export { AnalysisProject, AnalysisWorkspace, CompilationFailure, CompilationProject, EditorProject, EditorSnapshot, PluginRuntime, ResolutionMismatchError, 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, queryDesignSystem, resolveTypeFactsEnvironment, startPhase, tracePhase, warnRejectedNames };
2819
3030
 
2820
3031
  //# sourceMappingURL=index.js.map