@stillwind/host 0.8.0 → 0.9.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.
@@ -209,2225 +209,2604 @@ function byteToUtf16(text, offset) {
209
209
  if (offset < 0 || offset > bytes.length || offset < bytes.length && (bytes[offset] & 192) === 128) throw new Error("Invalid original UTF-8 boundary");
210
210
  return new TextDecoder().decode(bytes.subarray(0, offset)).length;
211
211
  }
212
- // src/compilation/module-graph.ts
212
+ // src/compilation/project.ts
213
213
  /**
214
- * Compilation failure carrying diagnostic batches for the same report format used by collect mode.
215
- * Its message renders those reports with source locations.
214
+ * Two resolver domains resolved the same import to different source targets, so they cannot share
215
+ * one project. Answers that analysis does not read, such as an external package and its runtime
216
+ * file, may differ. The project keeps the answer that it stored first.
216
217
  */
217
- var CompilationFailure = class extends Error {
218
- /**
219
- * Report batches grouped by compiler module identity. The supplied array is retained without
220
- * copying.
221
- */
222
- batches;
218
+ var ResolutionMismatchError = class extends Error {
219
+ importer;
220
+ specifier;
221
+ domain;
223
222
  /**
224
- * Builds an error message from the supplied reports and preserves an optional cause.
225
- *
226
- * @param batches - Reports to retain, in message order.
227
- * @param cause - Optional preparation or checker failure that produced these reports.
223
+ * @param importer - Full resolver ID of the importing source.
224
+ * @param specifier - Authored module request.
225
+ * @param domain - Resolver domain whose answer differs from the stored answer.
228
226
  */
229
- constructor(batches, cause) {
230
- super(batches.flatMap((batch) => batch.reports).map(formatReport).join("\n"), { cause });
231
- this.batches = batches;
227
+ constructor(importer, specifier, domain) {
228
+ super(`Resolver domain ${String(domain)} resolves ${JSON.stringify(specifier)} from ${importer} differently`);
229
+ this.importer = importer;
230
+ this.specifier = specifier;
231
+ this.domain = domain;
232
+ this.name = "ResolutionMismatchError";
232
233
  }
233
234
  };
234
235
  /**
235
- * Formats a compiler report for an Error message or terminal output.
236
+ * Keeps prepared sources and checker inputs between analyses of one project.
236
237
  *
237
- * @param report - Structured report with a primary label, related labels, and notes.
238
- * @returns Text with one-based line and column ranges for source labels, followed by related labels
239
- * and notes. Document-scoped primary labels use only the URI.
238
+ * Hosts whose resolvers can answer differently, such as the client and server environments of one
239
+ * bundler, can share a project when each host sets its own `resolverDomain`. The project stores the
240
+ * first answer for an import, and every other domain checks that answer once before using it.
240
241
  */
241
- function formatReport(report) {
242
- const { location, scope } = report.primary;
243
- const at = scope === "document" ? location.uri : `${location.uri}:${location.startLine + 1}:${location.startColumn + 1}-${location.endLine + 1}:${location.endColumn + 1}`;
244
- const related = report.related.map((label) => {
245
- const loc = label.location;
246
- return ` ${label.scope === "document" ? loc.uri : `${loc.uri}:${loc.startLine + 1}:${loc.startColumn + 1}`}${label.message ? `: ${label.message}` : ""}`;
247
- });
248
- return [
249
- `${at}: ${report.code}: ${report.message}`,
250
- ...related,
251
- ...report.notes.map((note) => ` ${note}`)
252
- ].join("\n");
253
- }
254
- /** Collects prepared sources and semantic facts for one entry's demanded dependency graph. */
255
- var ModuleGraph = class {
256
- session;
257
- factsService;
258
- host;
259
- options;
260
- analysis;
261
- project;
262
- /** Prepared sources keyed by compiler identity, including sources that later fail scanning. */
263
- #attempted = /* @__PURE__ */ new Map();
264
- /** Successful scanner summaries keyed by compiler identity. */
265
- #summaries = /* @__PURE__ */ new Map();
266
- /** Sources retained for compilation, keyed by full host identity. */
242
+ var CompilationProject = class {
243
+ /** Sources keyed by normalized resolver ID. Windows paths ignore case. */
267
244
  #sources = /* @__PURE__ */ new Map();
268
- /** Correspondence from compiler identities to full host resolver identities. */
269
- #resolverIds = /* @__PURE__ */ new Map();
270
- /** Observed import resolutions keyed by importing resolver identity and authored specifier. */
271
- #resolutions = /* @__PURE__ */ new Map();
272
- /** Whether entry probes require semantic traversal and checker collection. */
273
- #needsTypeFacts = false;
274
- /** Only this project revision may store scan results or install shared checker inputs. */
275
- #projectRevision;
245
+ /** Collected facts keyed by normalized resolver ID. Present only when sources stay unchanged. */
246
+ #facts;
276
247
  /**
277
- * Uses a caller-owned session, host, and lazy semantic backend for one entry.
278
- * Supplying `analysis` retains unavailable dependencies and partial facts in that result.
279
- * Omitting it keeps checker and dependency failures strict.
280
- *
281
- * @param session - Initialized native session. The caller retains ownership.
282
- * @param factsService - Lazy backend for checker queries, or undefined when unavailable.
283
- * @param host - Stable source descriptors, loading, and resolver operations for this graph.
284
- * @param options - Diagnostic policy and captured checker inputs for one compilation.
285
- * @param analysis - Optional result object to populate with observed sources, dependencies,
286
- * reports, and unavailable ranges.
287
- * @param project - Optional prepared inputs shared across scoped graphs of the same project.
248
+ * Host import resolutions keyed by importer resolver ID and specifier. Present only when sources
249
+ * stay unchanged.
288
250
  */
289
- constructor(session, factsService, host, options, analysis, project) {
290
- this.session = session;
291
- this.factsService = factsService;
292
- this.host = host;
293
- this.options = options;
294
- this.analysis = analysis;
295
- this.project = project;
296
- this.#projectRevision = project?.revision;
297
- }
251
+ #imports;
252
+ /** Import answers for the currently installed checker inputs. */
253
+ #resolutions;
298
254
  /**
299
- * Prepares source and retains it for report mapping, even if a later scan fails.
300
- *
301
- * @param input - Original or already prepared source. Preparation must preserve resolverId.
302
- * @returns Prepared source. onModule runs before preparation and does not imply success.
303
- * @throws If preparation fails or changes the resolver identity. PreparationError becomes CompilationFailure.
255
+ * Export descriptions of sources that {@link invalidateFile} removed after a content change,
256
+ * keyed by normalized resolver ID. Undefined records a source whose exports could not be
257
+ * described. {@link keepsInterface} compares them with the reloaded sources.
304
258
  */
305
- async prepare(input) {
306
- this.host.onModule?.(input.moduleId, input.resolverId);
307
- try {
308
- const source = this.project?.source(input.resolverId) ?? ("kind" in input ? input : await prepareSource(input));
309
- if (source.resolverId !== input.resolverId) throw new Error(`Host changed resolver identity for ${input.resolverId}`);
310
- this.#attempted.set(source.moduleId, source);
311
- this.analysis?.sources.push(source);
312
- return source;
313
- } catch (error) {
314
- if (error instanceof PreparationError) throw this.#preparationFailure(input, error);
315
- throw error;
316
- }
317
- }
259
+ #interfaces = /* @__PURE__ */ new Map();
260
+ /** Resolver IDs of sources that {@link invalidateFile} removed and {@link prepare} loads again. */
261
+ #reload = /* @__PURE__ */ new Set();
262
+ /** Advances on invalidation so pending loads cannot publish old sources. */
263
+ #revision = 0;
264
+ /** Advances when sources or import links change so checker inputs are installed again. */
265
+ #generation = 0;
266
+ /** Last backend and inputs installed by this project. */
267
+ #installed;
318
268
  /**
319
- * Scans a prepared source without registering it in dependency traversal.
269
+ * Creates an empty project.
320
270
  *
321
- * @param source - Source with validated original document and projection correspondences.
322
- * @returns Native summary of imports, declarations, and semantic probes.
323
- * @throws CompilationFailure when scanning returns source diagnostics.
271
+ * @param fixedSources - True when no source text and no import resolution changes until
272
+ * invalidation. The project then keeps collected facts and host import resolutions. With every
273
+ * file that a source imports installed, the facts of a source depend only on its own text, so
274
+ * other analyses can reuse them.
324
275
  */
325
- scan(source) {
326
- const cached = this.project?.summary(source);
327
- if (cached) return cached;
328
- const result = this.session.scanSource(source);
329
- if (result.kind === "failed") throw new CompilationFailure([result.batch]);
330
- this.project?.retain(source, result.summary, this.#projectRevision);
331
- return result.summary;
276
+ constructor(fixedSources = false) {
277
+ this.#facts = fixedSources ? /* @__PURE__ */ new Map() : void 0;
278
+ this.#imports = fixedSources ? /* @__PURE__ */ new Map() : void 0;
332
279
  }
333
- /**
334
- * Looks up a summary retained during dependency traversal.
335
- *
336
- * @param moduleId - Compiler identity of the source.
337
- * @returns Its cached summary, or undefined when traversal did not retain one.
338
- */
339
- summary(moduleId) {
340
- return this.#summaries.get(moduleId);
280
+ /** Revision that a pending load must still match before it stores a source. */
281
+ get revision() {
282
+ return this.#revision;
341
283
  }
342
284
  /**
343
- * Finds the host identity registered for a compiler module.
285
+ * Finds a source prepared since its last invalidation.
344
286
  *
345
- * @param moduleId - Compiler identity registered by dependency collection.
346
- * @returns Full resolver identity, including any query suffix.
347
- * @throws If the compiler refers to an unregistered module.
287
+ * @param id - Full resolver ID. Windows path spelling may differ in case or slashes.
288
+ * @returns The shared source, or undefined when it has not been prepared. Do not mutate it.
348
289
  */
349
- resolverId(moduleId) {
350
- const id = this.#resolverIds.get(moduleId);
351
- if (id === void 0) throw new Error(`Stillwind returned an unknown module: ${moduleId}`);
352
- return id;
290
+ source(id) {
291
+ return this.#sources.get(sourceKey(id))?.source;
292
+ }
293
+ /** Returns the normalized identities of the prepared sources, as {@link sourceKey} defines them. */
294
+ sourceKeys() {
295
+ return [...this.#sources.keys()];
296
+ }
297
+ /** Returns the prepared documents' original text so plugins can find candidates together. */
298
+ texts() {
299
+ return [...this.#sources.values()].map((record) => record.source.document.code);
353
300
  }
354
301
  /**
355
- * Registers the entry and loads dependencies demanded by its semantic probes.
302
+ * Finds the scan results for a prepared source.
356
303
  *
357
- * @param entry - Prepared entry source.
358
- * @param entrySummary - Successful scan of that entry, with the same module identity.
359
- * @returns A promise that resolves after traversal. Analysis mode retains unresolved and
360
- * unsupported dependencies rather than failing the whole graph.
361
- * @throws If strict traversal fails or source identities conflict.
304
+ * @param source - Source whose text has not changed since preparation.
305
+ * @returns Shared scan results, or undefined when the source is not retained. Do not mutate them.
362
306
  */
363
- async collectDependencies(entry, entrySummary) {
364
- this.#needsTypeFacts = entrySummary.typeProbes.length > 0;
365
- this.#register(entry);
366
- const visited = /* @__PURE__ */ new Map();
367
- const pending = [{
368
- source: entry,
369
- requested: null
370
- }];
371
- while (pending.length > 0) {
372
- const { source, requested } = pending.pop();
373
- const demands = visited.get(source.resolverId) ?? /* @__PURE__ */ new Set();
374
- if (demands.has(requested)) continue;
375
- demands.add(requested);
376
- visited.set(source.resolverId, demands);
377
- const summary = this.#dependencySummary(source, entry, entrySummary);
378
- if (!summary || !this.#needsTypeFacts) continue;
379
- const semanticResolutions = await this.#semanticResolutions(source);
380
- for (const dependency of semanticDependencies(summary, requested)) {
381
- const next = await this.#followDependency(source, dependency.source, semanticResolutions?.get(dependency.source));
382
- if (next) pending.push({
383
- source: next,
384
- requested: dependency.imported
385
- });
386
- }
387
- }
307
+ summary(source) {
308
+ const record = this.#sources.get(sourceKey(source.resolverId));
309
+ return record?.source.document.code === source.document.code ? record.summary : void 0;
388
310
  }
389
311
  /**
390
- * Attaches semantic facts and CSS value imports to the retained graph sources.
312
+ * Finds facts that an earlier analysis collected for a checker source.
391
313
  *
392
- * @param entry - Registered entry whose transport imports remain unchanged.
393
- * @returns Copies of retained sources with native type facts. Analysis mode records unavailable
394
- * queries, while strict compilation requires a backend when facts are needed.
395
- * @throws If strict checker collection or a checker source contract fails.
314
+ * @param source - Checker source that {@link install} returned.
315
+ * @returns Shared facts, or undefined when they are not kept. Do not mutate them.
396
316
  */
397
- async collectTypedSources(entry) {
398
- const facts = await this.#collectFacts();
399
- return [...this.#sources.values()].map((source) => ({
400
- ...source,
401
- moduleCssImport: source.resolverId === entry.resolverId ? source.moduleCssImport : "stillwind/module-css",
402
- typeFacts: facts.get(source.moduleId) ?? []
403
- }));
317
+ facts(source) {
318
+ return this.#facts?.get(sourceKey(source.resolverId));
404
319
  }
405
320
  /**
406
- * Converts a known checker failure to a report in original source coordinates.
321
+ * Keeps collected facts for reuse when the project was created with fixed sources.
407
322
  *
408
- * @param error - Failure caught during compilation.
409
- * @returns CompilationFailure for TypeFactsError whose source was prepared, otherwise the input.
323
+ * @param source - Checker source that {@link install} returned for the current revision.
324
+ * @param facts - Complete facts that the checker collected for that source.
410
325
  */
411
- failure(error) {
412
- if (!(error instanceof TypeFactsError)) return error;
413
- const source = this.#attempted.get(error.moduleId);
414
- if (!source) return error;
415
- const range = error.start !== void 0 && error.end !== void 0 ? {
416
- start: byteToUtf16(source.document.code, error.start),
417
- end: byteToUtf16(source.document.code, error.end)
418
- } : void 0;
419
- return new CompilationFailure([this.session.reportSourceFailure({
420
- moduleId: source.moduleId,
421
- document: source.document,
422
- issue: error.issue,
423
- range,
424
- converter: source.kind === "projected" ? source.projection.converter : void 0
425
- })], error);
326
+ retainFacts(source, facts) {
327
+ this.#facts?.set(sourceKey(source.resolverId), facts);
426
328
  }
427
329
  /**
428
- * Registers the source and enforces one-to-one host and compiler identities within the graph.
330
+ * Stores a source and its successful scan results, copying the source before retaining it.
429
331
  *
430
- * @param source - Prepared source to retain for traversal and compilation.
431
- * @throws If a compiler identity is shared or a host identity changes its compiler identity.
332
+ * @param source - Source passed to the scanner.
333
+ * @param summary - Successful scan results for that source. Do not mutate them after this call.
334
+ * @param revision - Revision captured before loading. Defaults to the current revision.
335
+ * Old revisions and sources already stored under the same ID have no effect.
432
336
  */
433
- #register(source) {
434
- const previous = this.#resolverIds.get(source.moduleId);
435
- if (previous !== void 0 && previous !== source.resolverId) throw new Error(`Module identity ${source.moduleId} is shared by ${previous} and ${source.resolverId}`);
436
- const existing = this.#sources.get(source.resolverId);
437
- if (existing !== void 0 && existing.moduleId !== source.moduleId) throw new Error(`Resolver identity ${source.resolverId} changed module identity`);
438
- this.#resolverIds.set(source.moduleId, source.resolverId);
439
- this.#sources.set(source.resolverId, source);
337
+ retain(source, summary, revision = this.#revision) {
338
+ if (revision !== this.#revision || this.#sources.has(sourceKey(source.resolverId))) return;
339
+ source = structuredClone(source);
340
+ this.#sources.set(sourceKey(source.resolverId), {
341
+ source,
342
+ summary,
343
+ linked: false,
344
+ verified: /* @__PURE__ */ new Set(),
345
+ resolutions: []
346
+ });
347
+ this.#changed();
440
348
  }
441
349
  /**
442
- * Converts a preparation error into an original-document diagnostic batch.
350
+ * Resolves an import through the host. A project with fixed sources asks the host once for each
351
+ * importer, specifier, and resolver domain.
443
352
  *
444
- * @param input - Source whose document metadata identifies the failing preparation.
445
- * @param error - Preparation issue with optional original UTF-16 range and converter identity.
446
- * @returns A compilation failure retaining the preparation error as its cause.
353
+ * @param host - Host that resolves the import. Its `resolverDomain` selects the domain.
354
+ * @param specifier - Authored module request.
355
+ * @param importer - Full resolver ID of the importing source.
356
+ * @returns The stored answer. A failed resolution is not kept.
357
+ * @throws If the host resolution fails, or a ResolutionMismatchError if the host's domain
358
+ * resolves the import to a source target that differs from the stored answer.
447
359
  */
448
- #preparationFailure(input, error) {
449
- return new CompilationFailure([this.session.reportSourceFailure({
450
- moduleId: input.moduleId,
451
- document: input.document,
452
- issue: error.issue,
453
- converter: error.converter,
454
- range: error.range
455
- })], error);
360
+ resolveImport(host, specifier, importer) {
361
+ if (!this.#imports) return host.resolve(specifier, importer, { skipSelf: true });
362
+ const key = `${importer}\0${specifier}`;
363
+ const domain = host.resolverDomain;
364
+ const entry = this.#imports.get(key);
365
+ if (!entry) {
366
+ const resolved = host.resolve(specifier, importer, { skipSelf: true });
367
+ this.#imports.set(key, {
368
+ resolved,
369
+ domains: /* @__PURE__ */ new Set([domain])
370
+ });
371
+ resolved.catch(() => this.#imports?.delete(key));
372
+ return resolved;
373
+ }
374
+ if (entry.domains.has(domain)) return entry.resolved;
375
+ return Promise.all([entry.resolved, host.resolve(specifier, importer, { skipSelf: true })]).then(([stored, own]) => {
376
+ if (analyzedTarget(host, stored) !== analyzedTarget(host, own)) throw new ResolutionMismatchError(importer, specifier, domain);
377
+ entry.domains.add(domain);
378
+ return stored;
379
+ });
456
380
  }
457
381
  /**
458
- * Reuses or scans a source summary and records dependency syntax failures in analysis mode.
382
+ * Loads and scans targets together, then resolves the imports of the sources that the targets
383
+ * reach through the host. Sources that the targets do not reach keep their links, and stay
384
+ * unlinked or unverified for this host's domain until a later call reaches them.
385
+ * Analysis retries failed loads and scans so it can report each target's own error.
459
386
  *
460
- * @param source - Registered dependency or entry source.
461
- * @param entry - Entry source whose initial scan is already available.
462
- * @param entrySummary - Summary with the entry's compiler identity.
463
- * @returns A retained summary, or undefined after an analysis-mode scan failure removes the source.
464
- * @throws If scanning fails in strict mode or a summary changes the source's compiler identity.
387
+ * @param ids - Full resolver IDs of the targets to prepare.
388
+ * @param host - Host used by later analysis of these targets.
389
+ * @param session - Initialized native session that will analyze the prepared sources.
390
+ * @returns Completion of preparation. Invalidation stops old work from storing results.
391
+ * @throws If host import resolution fails. Source loading and scan failures are left for analysis.
465
392
  */
466
- #dependencySummary(source, entry, entrySummary) {
467
- let summary;
468
- try {
469
- summary = this.#summaries.get(source.moduleId) ?? (source.resolverId === entry.resolverId ? entrySummary : this.scan(source));
470
- } catch (error) {
471
- if (!this.analysis || !(error instanceof CompilationFailure)) throw error;
472
- this.analysis.batches.push(...error.batches);
473
- this.#sources.delete(source.resolverId);
474
- for (const dependency of this.analysis.dependencies) if (dependency.id === source.resolverId) dependency.status = "unsupported";
393
+ async prepare(ids, host, session) {
394
+ const revision = this.#revision;
395
+ const reload = [...this.#reload];
396
+ this.#reload.clear();
397
+ await Promise.allSettled([...reload, ...ids].map((id) => this.#load(id, host, session, revision)));
398
+ if (revision !== this.#revision) {
399
+ for (const id of reload) this.#reload.add(id);
475
400
  return;
476
401
  }
477
- if (summary.moduleId !== source.moduleId) throw new Error(`Scanner changed module identity for ${source.resolverId}`);
478
- this.#summaries.set(source.moduleId, summary);
479
- return summary;
402
+ const domain = host.resolverDomain;
403
+ const pending = ids.map(sourceKey);
404
+ const visited = /* @__PURE__ */ new Set();
405
+ for (let key = pending.pop(); key !== void 0; key = pending.pop()) {
406
+ const record = this.#sources.get(key);
407
+ if (!record || visited.has(key)) continue;
408
+ visited.add(key);
409
+ const { source, summary } = record;
410
+ if (record.linked && record.verified.has(domain)) {
411
+ pending.push(...record.resolutions.map((resolution) => sourceKey(resolution.id)));
412
+ continue;
413
+ }
414
+ if (record.linked) {
415
+ await Promise.all(summary.moduleSpecifiers.map((specifier) => this.resolveImport(host, specifier.source, source.resolverId)));
416
+ if (revision !== this.#revision) return;
417
+ record.verified.add(domain);
418
+ pending.push(...record.resolutions.map((resolution) => sourceKey(resolution.id)));
419
+ continue;
420
+ }
421
+ const resolutions = await Promise.all(summary.moduleSpecifiers.map(async (specifier) => {
422
+ const target = analyzedTarget(host, await this.resolveImport(host, specifier.source, source.resolverId));
423
+ if (target === void 0) return;
424
+ await this.#load(target, host, session, revision).catch(() => {});
425
+ return {
426
+ id: this.source(target)?.resolverId ?? target,
427
+ start: specifier.start,
428
+ end: specifier.end
429
+ };
430
+ }));
431
+ if (revision !== this.#revision) return;
432
+ record.linked = true;
433
+ record.verified.add(domain);
434
+ this.#setResolutions(record, resolutions.filter((value) => value !== void 0));
435
+ pending.push(...record.resolutions.map((resolution) => sourceKey(resolution.id)));
436
+ }
480
437
  }
481
438
  /**
482
- * Attaches checker environments, scanner probes, and observed resolutions to retained sources.
439
+ * Removes changed sources and clears all import links and cached resolution answers.
483
440
  *
484
- * @returns Checker inputs in source registration order. Missing summaries are scanned and cached.
485
- * @throws If scanning or checker preparation fails.
441
+ * @param ids - One changed resolver ID or several IDs. Omission removes every source.
442
+ * Advances the revision so pending loads cannot restore the removed sources.
486
443
  */
487
- #checkerSources() {
488
- return [...this.#sources.values()].map((source) => {
489
- const summary = this.#summaries.get(source.moduleId) ?? this.scan(source);
490
- this.#summaries.set(source.moduleId, summary);
491
- let environment;
492
- try {
493
- environment = checkerEnvironment(source);
494
- } catch (error) {
495
- if (error instanceof PreparationError) throw this.#preparationFailure(source, error);
496
- throw error;
497
- }
498
- return {
499
- ...source,
500
- ...environment,
501
- checkerSpans: summary.checkerSpans,
502
- checkerBindings: summary.checkerBindings,
503
- probes: summary.typeProbes,
504
- resolutions: summary.moduleSpecifiers.flatMap((specifier) => {
505
- const id = this.#resolutions.get(source.resolverId)?.get(specifier.source);
506
- return id ? [{
507
- id,
508
- start: specifier.start,
509
- end: specifier.end
510
- }] : [];
511
- })
512
- };
513
- });
444
+ invalidate(ids) {
445
+ this.#revision++;
446
+ this.#facts?.clear();
447
+ this.#imports?.clear();
448
+ this.#interfaces.clear();
449
+ if (ids === void 0) {
450
+ this.#sources.clear();
451
+ this.#reload.clear();
452
+ } else for (const id of typeof ids === "string" ? [ids] : ids) this.#sources.delete(sourceKey(id));
453
+ for (const record of this.#sources.values()) {
454
+ record.resolutions = [];
455
+ if (record.checker) record.checker.resolutions = record.resolutions;
456
+ record.linked = false;
457
+ record.verified.clear();
458
+ }
459
+ this.#changed();
514
460
  }
515
461
  /**
516
- * Collects declared assets for checker interpretation.
462
+ * Removes every source read from a file, including query-qualified sources, and clears every
463
+ * collected fact. The next {@link prepare} call loads the removed sources again.
517
464
  *
518
- * @returns A new map from compiler identity to the corresponding scanner asset array.
465
+ * A content change keeps the import links of other sources, because their resolved targets
466
+ * keep the same IDs. Adding or removing a file can change any resolution, so it also clears
467
+ * all import links and cached resolution answers.
468
+ *
469
+ * @param file - Absolute path of a file that changed, was added, or was removed. A file that
470
+ * no source reads still clears the facts, because the checker reads unprepared files from disk.
471
+ * @param entry - Whether the file was added or removed rather than changed.
519
472
  */
520
- #assets() {
521
- return new Map([...this.#summaries].map(([id, summary]) => [id, summary.assets]));
473
+ invalidateFile(file, entry) {
474
+ const key = sourceKey(file);
475
+ const removed = this.sourceKeys().filter((id) => id === key || id.startsWith(`${key}?`));
476
+ for (const id of removed) this.#reload.add(this.#sources.get(id).source.resolverId);
477
+ if (entry) {
478
+ this.invalidate(removed);
479
+ return;
480
+ }
481
+ for (const id of removed) this.#interfaces.set(id, this.#imported(id) ? this.#describe(id) : void 0);
482
+ this.#revision++;
483
+ this.#facts?.clear();
484
+ for (const importKey of this.#imports?.keys() ?? []) {
485
+ const importer = sourceKey(importKey.slice(0, importKey.indexOf("\0")));
486
+ if (importer === key || importer.startsWith(`${key}?`)) this.#imports?.delete(importKey);
487
+ }
488
+ for (const id of removed) this.#sources.delete(id);
489
+ if (removed.length > 0) this.#changed();
522
490
  }
523
491
  /**
524
- * Adds an unverified range for each retained probe when analysis mode has no usable facts.
492
+ * Tests whether every source read from a changed file exposes the same exports as before the
493
+ * last {@link invalidateFile} call for that file. When it does, the facts and scans that other
494
+ * sources read from it are unchanged, so analyses of those sources may be kept.
525
495
  *
526
- * @param source - Source whose scanner probes use original UTF-8 byte coordinates.
527
- * @param reason - Explanation included in every added range. Strict mode has no analysis to update.
496
+ * Call it after the reloaded sources were prepared again. The result does not cover checker
497
+ * diagnostics of the other sources, global declarations that the file adds, or module
498
+ * augmentation.
499
+ *
500
+ * @param file - Absolute path passed to {@link invalidateFile} with `entry` false.
501
+ * @param backend - Backend for later queries. Receives the current inputs if they changed.
502
+ * @param inputs - File overlays and ambient declarations of the current analyses.
503
+ * @returns False when no source was removed, a removed source is not prepared again, another
504
+ * source did not import it, or the backend cannot describe its exports before and after.
505
+ * @throws If checker input installation fails.
528
506
  */
529
- #unavailable(source, reason) {
530
- this.analysis?.unverified.push(...(this.#summaries.get(source.moduleId)?.typeProbes ?? []).map((probe) => ({
531
- moduleId: source.moduleId,
532
- start: probe.start,
533
- end: probe.end,
534
- reason
535
- })));
507
+ keepsInterface(file, backend, inputs) {
508
+ const key = sourceKey(file);
509
+ const ids = [...this.#interfaces.keys()].filter((id) => id === key || id.startsWith(`${key}?`));
510
+ if (ids.length === 0 || ids.some((id) => !this.#sources.has(id))) return false;
511
+ this.install(backend, [], inputs);
512
+ return ids.every((id) => {
513
+ const before = this.#interfaces.get(id);
514
+ return before !== void 0 && before === this.#describe(id);
515
+ });
536
516
  }
537
517
  /**
538
- * Requests checker resolutions when the host enables them, recording failures as unverified probes.
518
+ * Tests whether another prepared source has a resolved import of a source.
539
519
  *
540
- * @param source - Importing source whose resolver identity selects the returned map.
541
- * @returns Authored specifiers mapped to host identities, or undefined when disabled or unavailable.
542
- * @throws If resolution fails outside analysis mode.
520
+ * @param id - Normalized resolver ID of a prepared source.
543
521
  */
544
- async #semanticResolutions(source) {
545
- if (!this.host.typeFactsResolution) return;
546
- try {
547
- const backend = this.factsService();
548
- if (backend && this.project && this.project.revision === this.#projectRevision) return (await this.project.resolve(backend, this.#checkerSources(), this.options.typeFactsInputs)).get(source.resolverId);
549
- return (await backend?.resolveModules(this.#checkerSources(), this.#assets(), this.options.typeFactsInputs))?.get(source.resolverId);
550
- } catch (error) {
551
- if (!this.analysis) throw error;
552
- this.#unavailable(source, String(error));
553
- }
522
+ #imported(id) {
523
+ const resolverId = this.#sources.get(id)?.source.resolverId;
524
+ return [...this.#sources.values()].some((record) => record.resolutions.some((resolution) => resolution.id === resolverId));
554
525
  }
555
526
  /**
556
- * Resolves a demanded dependency, records its status, and loads supported source for traversal.
527
+ * Describes the exports of a source in the installed checker inputs and its declaration
528
+ * metadata.
557
529
  *
558
- * @param source - Registered importing source.
559
- * @param specifier - Authored module request.
560
- * @param semanticId - Optional checker fallback used when the host returns no resolution.
561
- * @returns Registered dependency source, or undefined for external, unresolved, or unsupported requests.
562
- * @throws If strict loading fails. Analysis mode records loading failures and available diagnostics.
530
+ * @param id - Normalized resolver ID of a prepared source.
531
+ * @returns Undefined when the installed inputs do not contain the current source or the backend
532
+ * cannot describe its exports.
563
533
  */
564
- async #followDependency(source, specifier, semanticId) {
565
- const resolved = await this.#resolveDependency(source, specifier, semanticId);
566
- const observed = {
567
- importer: source.resolverId,
568
- specifier,
569
- id: resolved?.id,
570
- status: !resolved ? "unresolved" : resolved.external ? "external" : "resolved"
571
- };
572
- this.analysis?.dependencies.push(observed);
573
- if (!resolved || resolved.external) return;
574
- const id = this.project?.source(resolved.id)?.resolverId ?? resolved.id;
575
- observed.id = id;
576
- if (!this.#canLoadDependency(id, observed)) return;
577
- let resolutions = this.#resolutions.get(source.resolverId);
578
- if (!resolutions) this.#resolutions.set(source.resolverId, resolutions = /* @__PURE__ */ new Map());
579
- resolutions.set(specifier, id);
580
- this.host.watch(id);
581
- try {
582
- let dependency = this.#sources.get(id);
583
- if (!dependency) {
584
- dependency = await this.prepare(await this.#load(id));
585
- this.#register(dependency);
534
+ #describe(id) {
535
+ const record = this.#sources.get(id);
536
+ const installed = this.#installed;
537
+ if (!record || installed?.generation !== this.#generation) return;
538
+ const exports = installed.backend.exportInterface?.(record.source.resolverId);
539
+ if (exports === void 0) return;
540
+ const assets = record.summary.assets.map(({ identity, metadata }) => ({
541
+ identity,
542
+ metadata
543
+ }));
544
+ return `${JSON.stringify(assets)}
545
+ ${exports}`;
546
+ }
547
+ /**
548
+ * Installs prepared checker inputs when their sources, import links, or supplied files change.
549
+ *
550
+ * @param backend - Backend used by later queries. Receives inputs if it supports setProjectSources.
551
+ * @param sources - Sources requested by the current analysis, with any known import resolutions.
552
+ * @param inputs - File overlays and ambient declarations for these sources.
553
+ * @returns Shared checker sources in the requested order. Do not mutate them.
554
+ * @throws If a requested source's checker environment or backend installation fails.
555
+ * Other sources with unavailable framework dependencies are left out of the installed inputs.
556
+ */
557
+ install(backend, sources, inputs) {
558
+ const requested = sources.map((source) => {
559
+ const record = this.#sources.get(sourceKey(source.resolverId));
560
+ if (!record) return source;
561
+ const checker = this.#checkerSource(record);
562
+ if (!record.linked) {
563
+ const resolutions = new Map(record.resolutions.map((item) => [`${item.start}:${item.end}`, item]));
564
+ for (const item of source.resolutions ?? []) {
565
+ const target = this.source(item.id);
566
+ if (target) resolutions.set(`${item.start}:${item.end}`, {
567
+ ...item,
568
+ id: target.resolverId
569
+ });
570
+ }
571
+ this.#setResolutions(record, [...resolutions.values()]);
586
572
  }
587
- return dependency;
588
- } catch (error) {
589
- if (!this.analysis) throw error;
590
- observed.status = "unsupported";
591
- this.analysis.unverified.push({
592
- moduleId: source.moduleId,
593
- reason: String(error)
573
+ return checker;
574
+ });
575
+ const all = /* @__PURE__ */ new Map();
576
+ for (const [id, record] of this.#sources) try {
577
+ all.set(id, this.#checkerSource(record));
578
+ } catch {}
579
+ for (const source of requested) all.set(sourceKey(source.resolverId), source);
580
+ if (this.#installed?.backend !== backend || this.#installed.generation !== this.#generation || !sameFiles(this.#installed.inputs?.overlayFiles, inputs?.overlayFiles) || !sameFiles(this.#installed.inputs?.ambientDeclarations, inputs?.ambientDeclarations)) {
581
+ const inventory = [...all.values()].sort((a, b) => {
582
+ const left = sourceKey(a.resolverId);
583
+ const right = sourceKey(b.resolverId);
584
+ return left < right ? -1 : left > right ? 1 : 0;
594
585
  });
595
- if (error instanceof CompilationFailure) this.analysis.batches.push(...error.batches);
586
+ backend.setProjectSources?.(inventory, this.assets(), inputs);
587
+ this.#installed = {
588
+ backend,
589
+ generation: this.#generation,
590
+ inputs,
591
+ sources: inventory
592
+ };
593
+ this.#resolutions = void 0;
596
594
  }
595
+ return requested;
597
596
  }
598
597
  /**
599
- * Uses host resolution first and a checker identity only when the host returns null.
600
- *
601
- * @param source - Importer whose full resolver identity is passed to the host.
602
- * @param specifier - Authored module request.
603
- * @param semanticId - Optional identity supplied by checker resolution.
604
- * @returns A resolution, or null when unavailable. Analysis mode converts host exceptions to null.
605
- * @throws If host resolution fails in strict mode.
598
+ * @returns Declarations grouped by module ID. The arrays belong to the retained scans.
606
599
  */
607
- async #resolveDependency(source, specifier, semanticId) {
608
- try {
609
- return await this.host.resolve(specifier, source.resolverId, { skipSelf: true }) ?? (semanticId ? { id: semanticId } : null);
610
- } catch (error) {
611
- if (!this.analysis) throw error;
612
- return null;
613
- }
600
+ assets() {
601
+ return new Map([...this.#sources.values()].map(({ source, summary }) => [source.moduleId, summary.assets]));
614
602
  }
615
603
  /**
616
- * Distinguishes traversable sources from checker declarations and unsupported dependencies.
604
+ * Resolves imports and caches the answers until checker inputs change.
617
605
  *
618
- * @param id - Full resolved host identity.
619
- * @param observed - Mutable dependency record whose status becomes types or unsupported when skipped.
620
- * @returns Whether the dependency should be loaded as source.
606
+ * @param backend - Backend that resolves imports. Backends without setProjectSources query only sources.
607
+ * @param sources - Sources requested by the current analysis, with any known import resolutions.
608
+ * @param inputs - File overlays and ambient declarations for this analysis.
609
+ * @returns Shared maps from resolver ID to authored specifier and resolved ID. Do not mutate them.
610
+ * @throws If checker input preparation, installation, or import resolution fails.
621
611
  */
622
- #canLoadDependency(id, observed) {
623
- const name = cleanModuleId(id);
624
- if (/\.d\.[cm]?ts$/.test(name) || !this.host.typeFactsResolution && /(?:^|[\\/])node_modules[\\/]/.test(name)) {
625
- observed.status = "types";
626
- return false;
627
- }
628
- if (!(this.host.supports?.(id) ?? /\.(?:[cm]?[jt]sx?|astro|svelte|vue)$/.test(name))) {
629
- observed.status = "unsupported";
630
- return false;
612
+ async resolve(backend, sources, inputs) {
613
+ if (!backend.setProjectSources) return backend.resolveModules(sources, this.assets(), inputs);
614
+ this.install(backend, sources, inputs);
615
+ if (!this.#resolutions) {
616
+ const generation = this.#generation;
617
+ const resolutions = await backend.resolveModules(this.#installed.sources, this.assets(), inputs);
618
+ if (generation === this.#generation) this.#resolutions = resolutions;
619
+ return resolutions;
631
620
  }
632
- return true;
621
+ return this.#resolutions;
633
622
  }
634
623
  /**
635
- * Reuses a prepared project source or loads new input through the host.
624
+ * Loads and scans one supported source unless it is already prepared.
636
625
  *
637
- * @param id - Full resolved dependency identity.
638
- * @returns A shared prepared source or new input from the host. Do not mutate cached sources.
639
- * @throws If host loading, description, or reading fails.
626
+ * @param id - Full resolver ID.
627
+ * @param host - Source loader and format metadata for this project.
628
+ * @param session - Initialized session used to scan the source.
629
+ * @param revision - Revision captured before loading. A newer revision discards this work.
630
+ * @returns Completion of loading and scanning. Failed scans are not stored.
631
+ * @throws If loading, projection, or native transport fails.
640
632
  */
641
- async #load(id) {
642
- const cached = this.project?.source(id);
643
- if (cached) return cached;
644
- return loadSource(this.host, id);
633
+ async #load(id, host, session, revision) {
634
+ if (revision !== this.#revision || this.source(id) || sourceSupport(host, id) !== "source") return;
635
+ const input = await loadSource(host, id);
636
+ const source = "kind" in input ? input : await prepareSource(input);
637
+ if (revision !== this.#revision) return;
638
+ const scan = session.scanSource(source);
639
+ if (scan.kind !== "failed") this.retain(source, scan.summary, revision);
645
640
  }
646
641
  /**
647
- * Collects available facts for retained sources when entry probes require semantic information.
642
+ * Creates a source's checker inputs once, loading any required framework declarations.
648
643
  *
649
- * @returns Facts keyed by compiler identity. Analysis mode records unavailable queries and may return partial facts.
650
- * @throws If strict checker collection fails or a compilation failure occurs while preparing checker sources.
644
+ * @param record - Retained source and scan results to update.
645
+ * @returns Shared checker inputs. Later import updates also update this object.
646
+ * @throws If the framework checker environment cannot be prepared.
651
647
  */
652
- async #collectFacts() {
653
- if (!this.#needsTypeFacts) return /* @__PURE__ */ new Map();
654
- try {
655
- const backend = this.factsService();
656
- if (!backend) {
657
- if (!this.analysis) throw new Error("Type facts required for this compilation are unavailable");
658
- for (const source of this.#sources.values()) this.#unavailable(source, "Semantic queries are disabled");
659
- return /* @__PURE__ */ new Map();
660
- }
661
- if (this.analysis) {
662
- const sources = (this.project?.revision === this.#projectRevision ? this.project?.install(backend, this.#checkerSources(), this.options.typeFactsInputs) : void 0) ?? this.#checkerSources();
663
- const available = await backend.collectAvailable(sources, this.#assets(), this.options.typeFactsInputs);
664
- this.analysis.unverified.push(...available.unverified);
665
- return available.facts;
666
- }
667
- return await backend.collect(this.#checkerSources(), this.#assets(), this.options.typeFactsInputs);
668
- } catch (error) {
669
- if (!this.analysis || error instanceof CompilationFailure) throw error;
670
- for (const source of this.#sources.values()) this.#unavailable(source, String(error));
671
- return /* @__PURE__ */ new Map();
672
- }
648
+ #checkerSource(record) {
649
+ return record.checker ??= {
650
+ ...record.source,
651
+ ...checkerEnvironment(record.source),
652
+ probes: record.summary.typeProbes,
653
+ checkerSpans: record.summary.checkerSpans,
654
+ checkerBindings: record.summary.checkerBindings,
655
+ resolutions: record.resolutions
656
+ };
657
+ }
658
+ /**
659
+ * Replaces import links and clears cached answers when a target or range changes.
660
+ *
661
+ * @param record - Retained source whose links are being replaced.
662
+ * @param resolutions - Resolved targets with original UTF-8 byte ranges.
663
+ */
664
+ #setResolutions(record, resolutions) {
665
+ if (record.resolutions.length === resolutions.length && record.resolutions.every((item, index) => item.id === resolutions[index].id && item.start === resolutions[index].start && item.end === resolutions[index].end)) return;
666
+ record.resolutions = resolutions;
667
+ if (record.checker) record.checker.resolutions = resolutions;
668
+ this.#changed();
669
+ }
670
+ /**
671
+ * Clears import answers and marks checker inputs for installation on the next query.
672
+ */
673
+ #changed() {
674
+ this.#resolutions = void 0;
675
+ this.#generation++;
673
676
  }
674
677
  };
675
678
  /**
676
- * Selects imports needed to answer the current semantic demand.
679
+ * Normalizes a resolver ID for map lookups.
677
680
  *
678
- * @param summary - Scanner summary for the source being traversed.
679
- * @param requested - Null for entry probes, `*` for a namespace demand, or a specific exported
680
- * name.
681
- * @returns Probe imports, imports for a matched export, or matching re-export demands. Unmatched
682
- * and namespace demands conservatively retain all imports and re-exports.
681
+ * @param id - Resolver ID, with either slash style for Windows paths.
682
+ * @returns Forward slashes and, for absolute Windows paths, lowercase text.
683
683
  */
684
- function semanticDependencies(summary, requested) {
685
- if (requested === null) return summary.probeImports;
686
- const selected = summary.exportImports.find((entry) => entry.name === requested);
687
- if (requested !== "*" && selected) return selected.imports;
688
- const reExports = summary.reExports.filter((entry) => requested === "*" || entry.exported === requested || entry.exported === "*");
689
- if (requested !== "*" && reExports.length > 0) return reExports.map((entry) => ({
690
- source: entry.source,
691
- imported: entry.exported === "*" ? requested : entry.imported
692
- }));
693
- return [...summary.imports, ...summary.reExports];
684
+ function sourceKey(id) {
685
+ const normalized = id.replaceAll("\\", "/");
686
+ return /^[a-z]:\//i.test(normalized) ? normalized.toLowerCase() : normalized;
694
687
  }
695
- // src/compilation/request.ts
696
688
  /**
697
- * Creates an empty observed graph before loading its semantic dependencies.
689
+ * Compares supplied file contents without depending on map order.
698
690
  *
699
- * @param entry - Compiler module ID of the loaded entry source.
700
- * @returns A mutable graph with no reports or dependencies and generation initially allowed.
691
+ * @param a - First map of filenames to text. Omission means no files.
692
+ * @param b - Second map, interpreted in the same way.
693
+ * @returns Whether both maps contain the same filenames and text.
701
694
  */
702
- function createModuleAnalysis(entry) {
703
- return {
704
- entry,
705
- coverage: "observed",
706
- modules: [],
707
- batches: [],
708
- fixes: [],
709
- sources: [],
710
- dependencies: [],
711
- unverified: [],
712
- generation: "complete"
713
- };
695
+ function sameFiles(a, b) {
696
+ return (a?.size ?? 0) === (b?.size ?? 0) && [...a ?? []].every(([id, text]) => b?.get(id) === text);
714
697
  }
715
- // src/compilation/compiler.ts
716
- /** Most reloads with new plugin definitions during one compilation of a graph. */
717
- const PLUGIN_ROUNDS = 3;
718
698
  /**
719
- * Analyzes an entry and its semantic dependencies without requiring stylesheet delivery IDs.
720
- * Source failures return diagnostic batches. Unavailable semantic information records unverified
721
- * ranges. Entry I/O and native transport failures reject.
722
- * The caller owns the initialized session and the lazy checker service.
699
+ * Selects the part of a host resolution that analysis reads.
723
700
  *
724
- * @param session - Native project session with an initialized design system.
725
- * @param factsService - Supplies a checker configured for the host's TypeScript environment,
726
- * or undefined when semantic facts are unavailable.
727
- * @param id - Full resolver identity of the entry, including query suffixes.
728
- * @param host - Source loading, resolution, metadata, and dependency tracking operations.
729
- * @param typeFactsInputs - Captured overlays and ambient declarations for this analysis.
730
- * @param project - Optional sources prepared by earlier analyses of this project.
731
- * The caller must invalidate changed sources before analysis starts.
732
- * @returns Reports and sources for the semantic dependencies demanded by the entry.
733
- * @throws If entry I/O fails, a host changes resolver identity, or native transport operations fail.
701
+ * @param host - Host whose `supports` and `typeFactsResolution` settings apply.
702
+ * @param resolved - Host resolution, or null when unresolved.
703
+ * @returns The resolved identity when it is loaded as source. Undefined for unresolved, external,
704
+ * declaration, package, and unsupported targets, whose types the checker resolves itself.
734
705
  */
735
- async function analyzeModule(session, factsService, id, host, typeFactsInputs, project) {
736
- const revision = project?.revision;
737
- const captured = project?.source(id);
738
- const input = captured ?? await loadSource(host, id);
739
- if (project?.revision !== revision) project = void 0;
740
- const analysis = createModuleAnalysis(input.moduleId);
741
- if (!captured && input.resolverId !== id) throw new Error(`Host changed resolver identity for ${id}`);
742
- await compileGraph(session, factsService, input.document.code, input.resolverId, host, {
743
- diagnostics: "collect",
744
- moduleCssImport: "stillwind/module-css",
745
- typeFactsInputs
746
- }, analysis, input, project);
747
- for (const batch of analysis.batches) for (const report of batch.reports) {
748
- const edits = report.actions[0]?.edits;
749
- if (edits?.length && report.code !== "prefer-sorted-utilities") analysis.fixes.push(edits);
750
- }
751
- return analysis;
706
+ function analyzedTarget(host, resolved) {
707
+ return resolved && !resolved.external && sourceSupport(host, resolved.id) === "source" ? resolved.id : void 0;
752
708
  }
709
+ // src/compilation/trace.ts
710
+ const channel = (globalThis.process?.getBuiltinModule?.("node:diagnostics_channel"))?.channel("stillwind:host:phase");
711
+ const ignore = () => {};
753
712
  /**
754
- * Compiles an entry buffer and its demanded semantic dependencies into a project session.
755
- * The host descriptor supplies the module identity and parser metadata for each source.
756
- * Type facts are requested lazily for original-coordinate probes in JS/TS or SFC inputs.
757
- *
758
- * Collect mode retains compiler and checker reports, including known syntax and projection
759
- * failures. The default throw mode rejects compiler diagnostics. Lint findings only produce warnings.
760
- * Host I/O, checker process, and malformed native transport failures propagate in both modes.
761
- * Failed compilation can still update the session, register watches, and send warnings.
713
+ * Starts a phase measurement.
762
714
  *
763
- * @param session - Native project session with an initialized design system.
764
- * @param factsService - Supplies the type-facts service when the source graph needs semantic facts.
765
- * @param code - Entry source before Stillwind transformation.
766
- * @param id - Full resolver identity of the entry source, including its query suffix.
767
- * @param host - Source metadata, resolution, reading, dependency tracking, and warning operations.
768
- * @param options - Diagnostic behavior, captured checker inputs, and generated imports for the entry.
769
- * @returns A promise for the entry output and composition metadata, or undefined when normal mode
770
- * produces no entry code.
771
- * @throws If compilation rejects diagnostics, source preparation fails, or host or checker operations fail.
715
+ * @param phase - Phase name to publish.
716
+ * @returns A function that publishes the phase with its item count, which defaults to 1.
717
+ * The function does nothing when no subscriber was present at the start.
772
718
  */
773
- async function compileModule(session, factsService, code, id, host, options = {}) {
774
- return compileGraph(session, factsService, code, id, host, options);
719
+ function startPhase(phase) {
720
+ if (!channel?.hasSubscribers) return ignore;
721
+ const start = performance.now();
722
+ return (items = 1) => {
723
+ channel.publish({
724
+ phase,
725
+ duration: performance.now() - start,
726
+ items
727
+ });
728
+ };
775
729
  }
776
730
  /**
777
- * Prepares the demanded graph, compiles it into the session, and derives the entry output.
731
+ * Measures a synchronous or asynchronous operation as one phase.
778
732
  *
779
- * @param session - Initialized native session that retains successful module artifacts.
780
- * @param factsService - Lazy checker backend for semantic probes.
781
- * @param code - Original entry text used when entryInput is absent.
782
- * @param id - Full host identity of the entry.
783
- * @param host - Stable source metadata, resolution, and notification operations.
784
- * @param options - Diagnostic policy, captured checker inputs, and entry transport imports.
785
- * @param analysis - Optional object populated with sources, dependencies, reports, and generation status.
786
- * @param entryInput - Optional loaded entry, which takes precedence over code and host.describe.
787
- * @param project - Optional prepared sources shared with other analyses of this project.
788
- * @returns Entry output, a diagnostic-only output after a collected failure, or undefined when no code is emitted.
789
- * @throws If strict compilation fails or a host or transport failure cannot be collected.
733
+ * @param phase - Phase name to publish.
734
+ * @param items - Item count to publish.
735
+ * @param run - Operation to measure. A returned promise ends the phase when it settles.
736
+ * @returns The result of `run`. Failures are rethrown after the phase is published.
790
737
  */
791
- async function compileGraph(session, factsService, code, id, host, options, analysis, entryInput, project) {
792
- const graph = new ModuleGraph(session, factsService, host, options, analysis, project);
793
- let hasModuleCssImport = false;
738
+ function tracePhase(phase, items, run) {
739
+ const end = startPhase(phase);
740
+ if (end === ignore) return run();
741
+ let result;
794
742
  try {
795
- const descriptor = entryInput ?? {
796
- resolverId: id,
797
- ...host.describe(id),
798
- document: {
799
- ...host.describe(id).document,
800
- code
801
- }
802
- };
803
- const entrySource = await graph.prepare(descriptor);
804
- const entrySummary = graph.scan(entrySource);
805
- hasModuleCssImport = entrySummary.moduleCssImports > 0;
806
- if (entrySummary.macroImports > 0) entrySource.stylesheetImports = options.stylesheetImports;
807
- if (hasModuleCssImport) entrySource.moduleCssImport = options.moduleCssImport;
808
- await graph.collectDependencies(entrySource, entrySummary);
809
- const typedSources = await graph.collectTypedSources(entrySource);
810
- const producer = analysis ? void 0 : entrySource.moduleId;
811
- const projectOutput = await compileWithPlugins(session, () => session.compile(typedSources, producer), PLUGIN_ROUNDS);
812
- if (analysis) recordAnalysis(analysis, projectOutput.modules, session, typedSources, graph);
813
- reportOutputDiagnostics(projectOutput.modules, graph, host, options);
814
- return entryOutput(projectOutput.modules, entrySource.moduleId, hasModuleCssImport, options);
743
+ result = run();
815
744
  } catch (error) {
816
- const failure = graph.failure(error);
817
- if (failure instanceof CompilationFailure && options.diagnostics === "collect") {
818
- if (analysis) {
819
- analysis.batches = [...failure.batches];
820
- analysis.generation = "blocked";
821
- }
822
- return failedOutput(entryInput?.moduleId ?? host.describe(id).moduleId, failure.batches, hasModuleCssImport);
823
- }
824
- throw failure;
745
+ end(items);
746
+ throw error;
825
747
  }
748
+ if (result instanceof Promise) return result.finally(() => end(items));
749
+ end(items);
750
+ return result;
826
751
  }
752
+ // src/compilation/module-graph.ts
827
753
  /**
828
- * Selects the entry and computes its composition dependency identities and topology fingerprint.
829
- *
830
- * @param modules - Native outputs in compiler order.
831
- * @param entryModuleId - Compiler identity of the requested entry.
832
- * @param hasModuleCssImport - Whether the entry requested an explicit CSS value.
833
- * @param options - Diagnostic policy controlling whether reports from all modules are attached.
834
- * @returns Enriched entry output. Throw mode omits entries without nonempty code, and collect mode retains them.
754
+ * Compilation failure carrying diagnostic batches for the same report format used by collect mode.
755
+ * Its message renders those reports with source locations.
835
756
  */
836
- function entryOutput(modules, entryModuleId, hasModuleCssImport, options) {
837
- const output = modules.find((candidate) => candidate.moduleId === entryModuleId);
838
- const composition = output?.composition ?? [];
839
- const compositionModules = [...new Set(composition.map(({ base }) => base.moduleId))].filter((module) => module !== entryModuleId);
840
- const compositionTopology = JSON.stringify(composition.map(({ derived, base }) => [`${derived.moduleId}:${derived.start}`, `${base.moduleId}:${base.start}`]).sort((a, b) => a[0].localeCompare(b[0]) || a[1].localeCompare(b[1])));
841
- if (options.diagnostics === "collect" && output) return {
842
- ...output,
843
- hasModuleCssImport,
844
- compositionModules,
845
- compositionTopology,
846
- diagnostics: modules.flatMap((module) => module.diagnostics),
847
- reports: modules.flatMap((module) => module.reports)
848
- };
849
- if (!output?.code) return;
850
- return {
851
- ...output,
852
- hasModuleCssImport,
853
- compositionModules,
854
- compositionTopology
855
- };
856
- }
757
+ var CompilationFailure = class extends Error {
758
+ /**
759
+ * Report batches grouped by compiler module identity. The supplied array is retained without
760
+ * copying.
761
+ */
762
+ batches;
763
+ /**
764
+ * Builds an error message from the supplied reports and preserves an optional cause.
765
+ *
766
+ * @param batches - Reports to retain, in message order.
767
+ * @param cause - Optional preparation or checker failure that produced these reports.
768
+ */
769
+ constructor(batches, cause) {
770
+ super(batches.flatMap((batch) => batch.reports).map(formatReport).join("\n"), { cause });
771
+ this.batches = batches;
772
+ }
773
+ };
857
774
  /**
858
- * Populates analysis batches and removes artifacts when missing semantic facts block lowering.
775
+ * Formats a compiler report for an Error message or terminal output.
859
776
  *
860
- * @param analysis - Mutable result whose unverified ranges are deduplicated and generation status updated.
861
- * @param modules - Mutable native outputs whose reports are filtered and artifacts may be cleared.
862
- * @param session - Session used to diagnose sources independently when facts are unavailable.
863
- * @param typedSources - Prepared sources from the same compilation, with available type facts attached.
864
- * @param graph - Graph retaining scanner summaries for the compiled modules.
777
+ * @param report - Structured report with a primary label, related labels, and notes.
778
+ * @returns Text with one-based line and column ranges for source labels, followed by related labels
779
+ * and notes. Document-scoped primary labels use only the URI.
865
780
  */
866
- function recordAnalysis(analysis, modules, session, typedSources, graph) {
867
- analysis.modules = modules;
868
- analysis.unverified = [...new Map(analysis.unverified.map((range) => [JSON.stringify(range), range])).values()];
869
- const localReports = analysis.unverified.length ? session.diagnose(typedSources) : [];
870
- for (const module of modules) {
871
- module.reports = localReports.find((batch) => batch.module === module.moduleId)?.reports ?? module.reports;
872
- const ranges = analysis.unverified.filter((range) => range.moduleId === module.moduleId);
873
- const generationUnverified = generationNeedsFacts(graph.summary(module.moduleId), ranges);
874
- module.reports = verifiedReports(module.reports, ranges);
875
- if (generationUnverified || module.diagnostics.length) analysis.generation = "blocked";
876
- if (generationUnverified) clearArtifacts(module);
877
- analysis.batches.push({
878
- module: module.moduleId,
879
- reports: module.reports
880
- });
881
- }
882
- }
883
- /**
884
- * Checks whether unavailable semantic information affects a probe required for lowering.
885
- *
886
- * @param summary - Scanner summary for the module, or undefined if unavailable.
887
- * @param ranges - Unverified ranges in original UTF-8 bytes. Missing bounds cover the whole module.
888
- * @returns Whether an unbounded range exists or a bounded range overlaps a probe beyond recognition.
889
- */
890
- function generationNeedsFacts(summary, ranges) {
891
- return ranges.some((range) => {
892
- if (range.start === void 0 || range.end === void 0) return true;
893
- return summary?.typeProbes.some((probe) => !probe.recognitionOnly && overlaps(range, probe.start, probe.end));
894
- });
895
- }
896
- /**
897
- * Keeps source failures while omitting missing checker facts errors in unverified ranges.
898
- *
899
- * @param reports - Reports with original UTF-8 locations.
900
- * @param ranges - Unverified original UTF-8 ranges for the same module.
901
- * @returns A filtered array in report order. Other diagnostic codes remain unchanged.
902
- */
903
- function verifiedReports(reports, ranges) {
904
- return reports.filter((report) => {
905
- if (report.code !== checkerFactsRequiredCode) return true;
906
- const { start, end } = report.primary.location;
907
- return !ranges.some((range) => overlaps(range, start, end));
781
+ function formatReport(report) {
782
+ const { location, scope } = report.primary;
783
+ const at = scope === "document" ? location.uri : `${location.uri}:${location.startLine + 1}:${location.startColumn + 1}-${location.endLine + 1}:${location.endColumn + 1}`;
784
+ const related = report.related.map((label) => {
785
+ const loc = label.location;
786
+ return ` ${label.scope === "document" ? loc.uri : `${loc.uri}:${loc.startLine + 1}:${loc.startColumn + 1}`}${label.message ? `: ${label.message}` : ""}`;
908
787
  });
788
+ return [
789
+ `${at}: ${report.code}: ${report.message}`,
790
+ ...related,
791
+ ...report.notes.map((note) => ` ${note}`)
792
+ ].join("\n");
909
793
  }
910
- /** `CompileDiagnostic::CheckerFactsRequired`, which unverified semantic ranges can cause. */
911
- const checkerFactsRequiredCode = "SW30001";
912
- /**
913
- * Tests whether a diagnostic or probe overlaps an unavailable semantic range.
914
- *
915
- * @param range - Half-open original UTF-8 range. Missing bounds cover the entire module.
916
- * @param start - Inclusive original UTF-8 byte offset.
917
- * @param end - Exclusive original UTF-8 byte offset.
918
- * @returns Whether the ranges intersect, treating an unbounded range as intersecting everything.
919
- */
920
- function overlaps(range, start, end) {
921
- if (range.start === void 0 || range.end === void 0) return true;
922
- return start < range.end && end > range.start;
923
- }
924
- /**
925
- * Removes generated artifacts while keeping reports and composition metadata for analysis.
926
- *
927
- * @param module - Mutable output whose missing facts make its generated artifacts unreliable.
928
- */
929
- function clearArtifacts(module) {
930
- module.code = null;
931
- module.css = "";
932
- module.resources = [];
933
- module.classes = [];
934
- module.symbols = [];
935
- module.mappings = [];
936
- }
937
- /**
938
- * Checks output identities, reports lint and rejected-name warnings, and enforces diagnostic policy.
939
- *
940
- * @param modules - Native outputs with identities registered in graph.
941
- * @param graph - Source graph used to verify each output's host identity.
942
- * @param host - Warning receiver, which may receive messages before a later failure.
943
- * @param options - Collect mode retains compiler reports instead of throwing.
944
- * @throws If an output identity is unknown or throw mode encounters compiler errors.
945
- */
946
- function reportOutputDiagnostics(modules, graph, host, options) {
947
- for (const output of modules) {
948
- graph.resolverId(output.moduleId);
949
- if (output.diagnostics.length > 0 && options.diagnostics !== "collect") throw new CompilationFailure(modules.filter((module) => module.diagnostics.length > 0).map((module) => ({
950
- module: module.moduleId,
951
- reports: module.reports
952
- })));
953
- reportLintWarnings(output, host);
954
- warnRejectedNames(output.rejectedNames ?? [], (message) => host.warn(message));
794
+ /** Collects prepared sources and semantic facts for one entry's demanded dependency graph. */
795
+ var ModuleGraph = class {
796
+ session;
797
+ factsService;
798
+ host;
799
+ options;
800
+ analysis;
801
+ project;
802
+ /** Prepared sources keyed by compiler identity, including sources that later fail scanning. */
803
+ #attempted = /* @__PURE__ */ new Map();
804
+ /** Successful scanner summaries keyed by compiler identity. */
805
+ #summaries = /* @__PURE__ */ new Map();
806
+ /** Sources retained for compilation, keyed by full host identity. */
807
+ #sources = /* @__PURE__ */ new Map();
808
+ /** Correspondence from compiler identities to full host resolver identities. */
809
+ #resolverIds = /* @__PURE__ */ new Map();
810
+ /** Observed import resolutions keyed by importing resolver identity and authored specifier. */
811
+ #resolutions = /* @__PURE__ */ new Map();
812
+ /** Whether entry probes require semantic traversal and checker collection. */
813
+ #needsTypeFacts = false;
814
+ /** Only this project revision may store scan results or install shared checker inputs. */
815
+ #projectRevision;
816
+ /**
817
+ * Uses a caller-owned session, host, and lazy semantic backend for one entry.
818
+ * Supplying `analysis` retains unavailable dependencies and partial facts in that result.
819
+ * Omitting it keeps checker and dependency failures strict.
820
+ *
821
+ * @param session - Initialized native session. The caller retains ownership.
822
+ * @param factsService - Lazy backend for checker queries, or undefined when unavailable.
823
+ * @param host - Stable source descriptors, loading, and resolver operations for this graph.
824
+ * @param options - Diagnostic policy and captured checker inputs for one compilation.
825
+ * @param analysis - Optional result object to populate with observed sources, dependencies,
826
+ * reports, and unavailable ranges.
827
+ * @param project - Optional prepared inputs shared across scoped graphs of the same project.
828
+ */
829
+ constructor(session, factsService, host, options, analysis, project) {
830
+ this.session = session;
831
+ this.factsService = factsService;
832
+ this.host = host;
833
+ this.options = options;
834
+ this.analysis = analysis;
835
+ this.project = project;
836
+ this.#projectRevision = project?.revision;
955
837
  }
956
- }
957
- /**
958
- * Reports naming fallbacks through the host warning channel without a source location.
959
- *
960
- * @param rejected - Generator rejections in request order.
961
- * @param warn - Receives the family, input hash, and rejection reason for each fallback.
962
- */
963
- function warnRejectedNames(rejected, warn) {
964
- for (const entry of rejected) warn(`stillwind: the ${entry.kind} name for ${entry.hash} was rejected: ${entry.reason}`);
965
- }
966
- /**
967
- * Sends enabled lint findings through the host without changing their report severity.
968
- *
969
- * @param output - Findings and per-rule lint levels. Missing settings default to off.
970
- * @param host - Receiver for warning text with original source positions.
971
- */
972
- function reportLintWarnings(output, host) {
973
- for (const finding of output.lintFindings ?? []) {
974
- if ((output.lintSettings?.[finding.rule] ?? "off") === "off") continue;
975
- host.warn(`${finding.rule}: ${finding.message} (${finding.uri}:${finding.start})`);
838
+ /**
839
+ * Prepares source and retains it for report mapping, even if a later scan fails.
840
+ *
841
+ * @param input - Original or already prepared source. Preparation must preserve resolverId.
842
+ * @returns Prepared source. onModule runs before preparation and does not imply success.
843
+ * @throws If preparation fails or changes the resolver identity. PreparationError becomes CompilationFailure.
844
+ */
845
+ async prepare(input) {
846
+ this.host.onModule?.(input.moduleId, input.resolverId);
847
+ try {
848
+ const captured = this.project?.source(input.resolverId);
849
+ const source = captured?.document.code === input.document.code ? captured : "kind" in input ? input : await tracePhase("prepare", 1, () => prepareSource(input));
850
+ if (source.resolverId !== input.resolverId) throw new Error(`Host changed resolver identity for ${input.resolverId}`);
851
+ this.#attempted.set(source.moduleId, source);
852
+ this.analysis?.sources.push(source);
853
+ return source;
854
+ } catch (error) {
855
+ if (error instanceof PreparationError) throw this.#preparationFailure(input, error);
856
+ throw error;
857
+ }
976
858
  }
977
- }
978
- /**
979
- * Projects a report's primary label into the diagnostic shape returned by compilation.
980
- *
981
- * @param report - Structured compiler report.
982
- * @returns Primary location and scope, diagnostic code and class, message, and notes. Related
983
- * labels and severity remain in the report.
984
- */
985
- function reportDiagnostic(report) {
986
- return {
987
- ...report.primary.location,
988
- scope: report.primary.scope,
989
- code: report.code,
990
- ...report.class && { class: report.class },
991
- message: report.message,
992
- notes: report.notes
993
- };
994
- }
995
- /**
996
- * Builds a collect-mode entry output when preparation, scanning, or checking failed.
997
- *
998
- * @param moduleId - Compiler identity of the entry module.
999
- * @param batches - Failure reports from the attempted compilation.
1000
- * @param hasModuleCssImport - Whether scanning found an explicit CSS value import in the entry.
1001
- * @returns An output with null code, empty generated artifacts, all reports, and diagnostics
1002
- * derived only from error reports.
1003
- */
1004
- function failedOutput(moduleId, batches, hasModuleCssImport) {
1005
- const reports = batches.flatMap((batch) => batch.reports);
1006
- return {
1007
- moduleId,
1008
- code: null,
1009
- css: "",
1010
- resources: [],
1011
- mappings: [],
1012
- classes: [],
1013
- symbols: [],
1014
- diagnostics: reports.filter((report) => report.severity === "error").map(reportDiagnostic),
1015
- reports,
1016
- rejectedNames: [],
1017
- dynamicCandidates: [],
1018
- lintFindings: [],
1019
- lintSettings: {},
1020
- composition: [],
1021
- hasModuleCssImport,
1022
- compositionModules: [],
1023
- compositionTopology: "[]"
1024
- };
1025
- }
1026
- // src/css/banners.ts
1027
- /**
1028
- * Formats notices as the prefix of a published stylesheet.
1029
- *
1030
- * @param banners - Notices in published order without duplicates, as a native plan or part lists
1031
- * them. Callers that combine lists must order them again with `cssBanners` from `stillwind/css`.
1032
- * @returns The notices in the given order, each followed by a newline.
1033
- */
1034
- function cssBannerPrefix(banners) {
1035
- return banners.map((banner) => `${banner}\n`).join("");
1036
- }
1037
- /**
1038
- * Adds notices before a CSS body without changing the body.
1039
- *
1040
- * @param output - CSS body and the notices that it requires, in the form that
1041
- * {@link cssBannerPrefix} accepts.
1042
- * @returns The published stylesheet text, or an empty string when the body is blank.
1043
- */
1044
- function finalizeCss(output) {
1045
- return output.css.trim() ? cssBannerPrefix(output.banners ?? []) + output.css : "";
1046
- }
1047
- // src/css/plugins/host.ts
1048
- /**
1049
- * Matches an import or `@plugin` specifier that names a file by a relative or absolute path or
1050
- * a `file:` URL, rather than a package.
1051
- */
1052
- const PATH_SPECIFIER = /^(?:\.{1,2}[\\/]|[\\/]|[a-z]:[\\/]|file:)/i;
1053
- /**
1054
- * Recognizes Tailwind's plugin export forms without executing a factory.
1055
- *
1056
- * @param value - Default export of a plugin module.
1057
- * @returns Whether `value` is a function or an object with a `handler` function.
1058
- */
1059
- function isTailwindPlugin(value) {
1060
- return typeof value === "function" || typeof value === "object" && value !== null && typeof value.handler === "function";
1061
- }
1062
- /**
1063
- * Whether a loaded plugin uses the Stillwind plugin contract.
1064
- *
1065
- * @param plugin - Configured or loaded plugin.
1066
- * @returns Whether `plugin` has a `css` function, which Tailwind plugins lack.
1067
- */
1068
- function nativePlugin(plugin) {
1069
- return typeof plugin === "object" && plugin !== null && "css" in plugin && typeof plugin.css === "function";
1070
- }
1071
- /**
1072
- * Selects the plugin that a module exports by default.
1073
- *
1074
- * @param module - Evaluated module namespace.
1075
- * @param specifier - Request that loaded the module, used in the error message.
1076
- * @returns The default export.
1077
- * @throws If the default export is neither a Stillwind plugin object nor a Tailwind v4 plugin.
1078
- */
1079
- function defaultPluginExport(module, specifier) {
1080
- const plugin = module?.default;
1081
- if (isTailwindPlugin(plugin)) return plugin;
1082
- if (typeof plugin !== "object" || plugin === null || typeof plugin.name !== "string" || typeof plugin.css !== "function") throw new Error(`Stillwind plugin ${specifier} must export a plugin object by default, or a Tailwind v4 handler`);
1083
- return plugin;
1084
- }
1085
- /**
1086
- * Returns the utility text before the cursor for plugin catalog lookup.
1087
- *
1088
- * @param text - Text before the cursor. The candidate ends at the cursor and starts after the
1089
- * last whitespace, quote, backtick, `;`, `{`, or `}`.
1090
- * @returns The candidate without its variants, such as `icon-mdi--cl` for `hover:icon-mdi--cl`.
1091
- */
1092
- function catalogInput(text) {
1093
- const candidate = /[^\s"'`;{}]*$/.exec(text)[0];
1094
- let depth = 0;
1095
- for (let index = candidate.length - 1; index >= 0; index--) {
1096
- const character = candidate[index];
1097
- if (character === "]" || character === ")") depth++;
1098
- else if ((character === "[" || character === "(") && depth > 0) depth--;
1099
- else if (character === ":" && depth === 0) return candidate.slice(index + 1);
1100
- }
1101
- return candidate;
1102
- }
1103
- /**
1104
- * Identifies one `@plugin` statement independently of its request ID.
1105
- *
1106
- * @param request - Plugin request.
1107
- * @returns Importer, specifier, and JSON options joined by NUL characters.
1108
- */
1109
- function instanceKey(request) {
1110
- return `${request.importer}\0${request.specifier}\0${JSON.stringify(request.pluginOptions ?? [])}`;
1111
- }
1112
- /**
1113
- * Identifies one request independently of its ID, which changes between loads.
1114
- *
1115
- * @param request - Loader request.
1116
- * @returns Importer, specifier, and JSON plugin options joined by NUL characters. An `@import`
1117
- * has no options part.
1118
- */
1119
- function answerKey(request) {
1120
- return `${request.importer}\0${request.specifier}\0${JSON.stringify(request.pluginOptions) ?? ""}`;
1121
- }
1122
- // src/css/plugins/runtime.ts
1123
- /**
1124
- * Specifier of the `@plugin` request that the native loader adds after the root stylesheet for
1125
- * the Tailwind settings. Decoded CSS never contains NUL, so no authored statement has it.
1126
- */
1127
- const SETTINGS = "\0stillwind-tailwind-settings";
1128
- /**
1129
- * Matches `@stillwind-dynamic <prefix>*;` or `<prefix>[*];` and captures the prefix.
1130
- */
1131
- const DYNAMIC = /@stillwind-dynamic\s+([^\s;*[\]]+)(?:\[\*\]|\*)\s*;/g;
1132
- /**
1133
- * Runs the plugins of one CSS graph and defines candidates of their dynamic families on demand.
1134
- *
1135
- * The runtime records every answer of the graph's load, so {@link PluginRuntime.replay} loads the
1136
- * same graph again without host I/O, with the definitions that plugins have added since. A
1137
- * candidate that a plugin leaves undefined is not requested again for the runtime's lifetime.
1138
- *
1139
- * Tailwind plugins of the graph share one adapter runtime, which {@link PluginRuntime.initialize}
1140
- * creates after the first load because their handlers read the complete CSS theme.
1141
- */
1142
- var PluginRuntime = class {
1143
- options;
1144
- plugins;
1145
- root;
1146
- host;
1147
- watch;
1148
- previous;
1149
- settings;
1150
- /** Plugin statements keyed by importer, specifier, and options text. */
1151
- #instances = /* @__PURE__ */ new Map();
1152
- /** Recorded answers keyed by {@link answerKey}. */
1153
- #answers = /* @__PURE__ */ new Map();
1154
- /** Requests of the load by importer and request ID, which order the plugin statements. */
1155
- #requests = /* @__PURE__ */ new Map();
1156
- /** Root answer, recorded by {@link PluginRuntime.recordRoot}. */
1157
- #root;
1158
- /** Candidates already passed to a plugin, including ones it left undefined. */
1159
- #requested = /* @__PURE__ */ new Set();
1160
- /** Editor catalogs keyed by input, oldest first. The empty input is never evicted. */
1161
- #catalogs = /* @__PURE__ */ new Map();
1162
859
  /**
1163
- * Number of {@link PluginRuntime.resolve} calls that added CSS. The loader of the original
1164
- * load contains the definitions of generation zero.
860
+ * Scans a prepared source without registering it in dependency traversal.
861
+ *
862
+ * @param source - Source with validated original document and projection correspondences.
863
+ * @returns Native summary of imports, declarations, and semantic probes.
864
+ * @throws CompilationFailure when scanning returns source diagnostics.
1165
865
  */
1166
- #generation = 0;
1167
- /** Runtime of every Tailwind plugin of the graph, which share one config and theme. */
1168
- #tailwind;
1169
- /** Loader of the original load, whose source IDs replays share without a session. */
1170
- #loader;
1171
- /** Loader for the last queried definition generation. Source usage remains in separate sessions. */
1172
- #snapshot;
1173
- /** Tailwind statements in stylesheet order; an index is the statement's owner index. */
1174
- #tailwindInstances = [];
1175
- /** Answer to the {@link SETTINGS} request, which the Tailwind runtime generates. */
1176
- #settingsCss = "";
866
+ scan(source) {
867
+ const cached = this.project?.summary(source);
868
+ if (cached) {
869
+ startPhase("scan-reuse")();
870
+ return cached;
871
+ }
872
+ const result = tracePhase("scan", 1, () => this.session.scanSource(source));
873
+ if (result.kind === "failed") throw new CompilationFailure([result.batch]);
874
+ this.project?.retain(source, result.summary, this.#projectRevision);
875
+ return result.summary;
876
+ }
1177
877
  /**
1178
- * Creates a runtime for one load.
878
+ * Looks up a summary retained during dependency traversal.
1179
879
  *
1180
- * @param options - Compiler options of the load, reused by {@link PluginRuntime.replay}.
1181
- * @param plugins - Plugins configured for the project, which take precedence over packages.
1182
- * @param root - Absolute project directory passed to plugins.
1183
- * @param host - Loads plugin packages and plugin files, or undefined when the host can only use
1184
- * configured plugins.
1185
- * @param watch - Registers files and directories that plugins read.
1186
- * @param previous - Runtime of an earlier load of the same project. A statement with the same
1187
- * specifier, options, and plugin resolves the earlier load's candidates of its families again.
1188
- * @param settings - Project's Tailwind settings. Either field makes the graph use the Tailwind
1189
- * plugin adapter, as a Tailwind `@plugin` statement does.
880
+ * @param moduleId - Compiler identity of the source.
881
+ * @returns Its cached summary, or undefined when traversal did not retain one.
1190
882
  */
1191
- constructor(options, plugins, root, host, watch, previous, settings) {
1192
- this.options = options;
1193
- this.plugins = plugins;
1194
- this.root = root;
1195
- this.host = host;
1196
- this.watch = watch;
1197
- this.previous = previous;
1198
- this.settings = settings;
1199
- }
1200
- /** Number of definition batches added after the original load. */
1201
- get generation() {
1202
- return this.#generation;
1203
- }
1204
- /** Whether project settings or a loaded plugin require the Tailwind adapter. */
1205
- get tailwind() {
1206
- return this.settings?.tailwind !== void 0 || this.settings?.important !== void 0 || [...this.#instances.values()].some((instance) => instance.tailwind);
883
+ summary(moduleId) {
884
+ return this.#summaries.get(moduleId);
1207
885
  }
1208
- /** Whether any loaded plugin declares a dynamic family. */
1209
- get dynamic() {
1210
- return !!this.#tailwind || [...this.#instances.values()].some((instance) => instance.prefixes.length > 0);
886
+ /**
887
+ * Finds the host identity registered for a compiler module.
888
+ *
889
+ * @param moduleId - Compiler identity registered by dependency collection.
890
+ * @returns Full resolver identity, including any query suffix.
891
+ * @throws If the compiler refers to an unregistered module.
892
+ */
893
+ resolverId(moduleId) {
894
+ const id = this.#resolverIds.get(moduleId);
895
+ if (id === void 0) throw new Error(`Stillwind returned an unknown module: ${moduleId}`);
896
+ return id;
1211
897
  }
1212
898
  /**
1213
- * Records the root answer of the load.
899
+ * Registers the entry and loads dependencies demanded by its semantic probes.
1214
900
  *
1215
- * @param answer - Root input without its request ID.
901
+ * A loaded dependency is compiled with all of its style calls, so traversal also follows
902
+ * the probes of every loaded module, not only the imports of the demanded export.
903
+ *
904
+ * @param entry - Prepared entry source.
905
+ * @param entrySummary - Successful scan of that entry, with the same module identity.
906
+ * @returns A promise that resolves after traversal. Analysis mode retains unresolved and
907
+ * unsupported dependencies rather than failing the whole graph.
908
+ * @throws If strict traversal fails or source identities conflict.
1216
909
  */
1217
- recordRoot(answer) {
1218
- this.#root = answer;
910
+ async collectDependencies(entry, entrySummary) {
911
+ this.#needsTypeFacts = entrySummary.typeProbes.length > 0;
912
+ this.#register(entry);
913
+ const visited = /* @__PURE__ */ new Map();
914
+ const pending = [{
915
+ source: entry,
916
+ requested: null
917
+ }];
918
+ while (pending.length > 0) {
919
+ const { source, requested } = pending.pop();
920
+ const demands = visited.get(source.resolverId) ?? /* @__PURE__ */ new Set();
921
+ if (demands.has(requested)) continue;
922
+ demands.add(requested);
923
+ visited.set(source.resolverId, demands);
924
+ const summary = this.#dependencySummary(source, entry, entrySummary);
925
+ if (!summary || !this.#needsTypeFacts) continue;
926
+ const semanticResolutions = await this.#semanticResolutions(source);
927
+ for (const dependency of semanticDependencies(summary, requested)) {
928
+ const next = await this.#followDependency(source, dependency.source, semanticResolutions?.get(dependency.source));
929
+ if (next) pending.push({
930
+ source: next,
931
+ requested: dependency.imported
932
+ }, {
933
+ source: next,
934
+ requested: null
935
+ });
936
+ }
937
+ }
1219
938
  }
1220
939
  /**
1221
- * Records the answer to an `@import` request so that a replay can repeat it.
940
+ * Attaches semantic facts and CSS value imports to the retained graph sources.
1222
941
  *
1223
- * @param request - Loader request.
1224
- * @param answer - File input supplied for it, without its request ID.
942
+ * @param entry - Registered entry whose transport imports remain unchanged.
943
+ * @returns Copies of retained sources with native type facts. Analysis mode records unavailable
944
+ * queries, while strict compilation requires a backend when facts are needed.
945
+ * @throws If strict checker collection or a checker source contract fails.
1225
946
  */
1226
- recordImport(request, answer) {
1227
- this.#recordRequest(request);
1228
- this.#answers.set(answerKey(request), answer);
947
+ async collectTypedSources(entry) {
948
+ const styled = this.analysis ? void 0 : this.#styleSources(entry);
949
+ const facts = this.#needsTypeFacts ? await tracePhase("type-facts", styled?.size ?? this.#sources.size, () => this.#collectFacts(styled)) : /* @__PURE__ */ new Map();
950
+ return [...this.#sources.values()].filter((source) => !styled || styled.has(source.resolverId)).map((source) => ({
951
+ ...source,
952
+ ...source.resolverId !== entry.resolverId && this.#summaries.get(source.moduleId)?.macroImports && { stylesheetImports: this.host.stylesheetImports?.(source.resolverId) },
953
+ moduleCssImport: source.resolverId === entry.resolverId ? source.moduleCssImport : "stillwind/module-css",
954
+ typeFacts: facts.get(source.moduleId) ?? []
955
+ }));
1229
956
  }
1230
957
  /**
1231
- * Runs the plugin of an `@plugin` request and returns the answer for it.
958
+ * Selects the retained sources that can change the entry's output.
1232
959
  *
1233
- * The answer's definitions are the user's own when the host loads the plugin from a
1234
- * relative or absolute path and `own` is true. Otherwise, they belong to the plugin that the
1235
- * specifier names, including a plugin configured for the project.
960
+ * A dependency matters when it imports a Stillwind macro module, declares assets, imports module
961
+ * CSS, or reaches such a source through the imports that traversal followed. Other dependencies
962
+ * cannot export assets, and composition checks have nothing to check in them.
1236
963
  *
1237
- * @param request - Loader request whose `pluginOptions` is set.
1238
- * @param own - Whether the stylesheet that contains the statement is the user's own CSS.
1239
- * @returns File input without its request ID. Its name identifies the specifier and options.
1240
- * @throws If no plugin has the specifier's name and the host cannot load it, or the plugin fails.
964
+ * @param entry - Registered entry, which is always selected.
965
+ * @returns Resolver identities of the selected sources.
1241
966
  */
1242
- async answerPlugin(request, own = false) {
1243
- this.#recordRequest(request);
1244
- const key = instanceKey(request);
1245
- let instance = this.#instances.get(key);
1246
- if (!instance) {
1247
- const configured = this.plugins.find((candidate) => candidate.name === request.specifier);
1248
- const plugin = configured ?? await this.host?.load(request.specifier, request.importer, this.watch);
1249
- if (!plugin) throw new Error(`Stillwind plugin ${request.specifier} is not configured, and this host cannot load packages`);
1250
- const context = {
1251
- options: Object.fromEntries((request.pluginOptions ?? []).map((option) => [option.name, option.value])),
1252
- root: this.root,
1253
- watch: this.watch,
1254
- resolve: async (specifier) => this.host?.resolve(specifier, request.importer),
1255
- read: async (path) => {
1256
- if (!this.host) throw new Error(`This host cannot read plugin files: ${path}`);
1257
- return this.host.read(path);
1258
- },
1259
- list: async (path) => {
1260
- if (!this.host?.list) throw new Error(`This host cannot list plugin directories: ${path}`);
1261
- return this.host.list(path);
1262
- }
1263
- };
1264
- const css = nativePlugin(plugin) ? await plugin.css(context) : "";
1265
- const prefixes = [...css.matchAll(DYNAMIC)].map((match) => match[1]);
1266
- const previous = this.previous ? this.previous.#instances.get(key) : void 0;
1267
- const candidates = previous?.plugin === plugin && nativePlugin(plugin) && plugin.resolve ? previous.candidates.filter((candidate) => prefixes.some((prefix) => candidate.startsWith(prefix))) : [];
1268
- const resolved = candidates.length && nativePlugin(plugin) ? await plugin.resolve(candidates, context) : "";
1269
- for (const candidate of candidates) this.#requested.add(candidate);
1270
- instance = {
1271
- plugin,
1272
- context,
1273
- css,
1274
- prefixes,
1275
- candidates,
1276
- definitions: resolved.trim() ? [resolved] : [],
1277
- origin: !configured && own && PATH_SPECIFIER.test(request.specifier) ? { kind: "own" } : {
1278
- kind: "plugin",
1279
- name: request.specifier
1280
- },
1281
- tailwind: nativePlugin(plugin) ? void 0 : (await import("./configuration-MQZe6ufN.js")).configurePlugin(plugin, request.pluginOptions ?? [])
1282
- };
1283
- this.#instances.set(key, instance);
1284
- }
1285
- const answer = this.#pluginAnswer(key, instance);
1286
- this.#answers.set(answerKey(request), answer);
1287
- return answer;
1288
- }
1289
- /**
1290
- * Evaluates Tailwind handlers with the complete CSS theme, then resolves the candidates of
1291
- * dynamic families that the graph's CSS applies with `@apply` and `@variant`.
1292
- *
1293
- * Tailwind handlers run after the first load because their `theme()` calls read the complete
1294
- * CSS theme. Their output then needs one more load of the recorded graph. Dynamic candidates in
1295
- * the graph's CSS need one more load when a plugin defines any of them, with or without
1296
- * Tailwind. Canonical queries prepare spelling indexes on demand.
1297
- *
1298
- * Each later load requests the Tailwind settings after the root stylesheet, as
1299
- * {@link TailwindRuntime.settingsCss} describes.
1300
- *
1301
- * @param loader - Loader of the completed original load. With Tailwind plugins or settings, it
1302
- * can skip its canonical spelling index, as {@link PluginRuntime.tailwind} allows.
1303
- * @returns `loader` when no plugin adds CSS, and otherwise a loader with the added CSS.
1304
- * @throws If the Tailwind configuration is rejected or invalid, a plugin, a handler, or a
1305
- * callback fails, or the native loader rejects the generated CSS.
1306
- */
1307
- async initialize(loader) {
1308
- this.#loader = loader;
1309
- const instances = this.#orderedInstances().filter((instance) => instance.tailwind);
1310
- const project = await this.#projectConfig();
1311
- let current = loader;
1312
- if (instances.length || project) {
1313
- this.#tailwindInstances = instances;
1314
- const { TailwindRuntime } = await import("./plugin-CxD6forV.js");
1315
- const editor = loader.editorQuery();
1316
- this.#tailwind = new TailwindRuntime(instances.map((instance) => instance.tailwind), editor.themeTokens(), editor.legacyThemeKeys(), project);
1317
- if (this.previous) await this.resolve(this.previous.#requested);
1318
- this.#updateTailwindCss();
1319
- current = this.replay(void 0, true);
967
+ #styleSources(entry) {
968
+ const selected = /* @__PURE__ */ new Set([entry.resolverId]);
969
+ for (const source of this.#sources.values()) {
970
+ const summary = this.#summaries.get(source.moduleId);
971
+ if (summary && (summary.macroImports > 0 || summary.moduleCssImports > 0 || summary.assets.length > 0)) selected.add(source.resolverId);
1320
972
  }
1321
- if (!this.dynamic) {
1322
- this.#snapshot = {
1323
- generation: this.#generation,
1324
- loader: current
1325
- };
1326
- return current;
973
+ let changed = true;
974
+ while (changed) {
975
+ changed = false;
976
+ for (const [importer, targets] of this.#resolutions) if (!selected.has(importer) && [...targets.values()].some((id) => selected.has(id))) {
977
+ selected.add(importer);
978
+ changed = true;
979
+ }
1327
980
  }
1328
- const query = current.editorQuery();
1329
- const sources = [this.#root?.content ?? "", ...[...this.#answers.values()].map((a) => a.content)];
1330
- if (await this.resolve(sources.flatMap((css) => query.stylesheetDynamicCandidates(css)))) current = this.replay(void 0, true);
1331
- this.#snapshot = {
1332
- generation: this.#generation,
1333
- loader: current
1334
- };
1335
- return current;
981
+ return selected;
1336
982
  }
1337
983
  /**
1338
- * Loads the runtime's current CSS definitions once per definition generation.
984
+ * Converts a known checker failure to a report in original source coordinates.
1339
985
  *
1340
- * @returns The shared loader for editor queries. Do not add CSS or session usage to it.
1341
- * @throws If the native loader rejects the plugin definitions.
986
+ * @param error - Failure caught during compilation.
987
+ * @returns CompilationFailure for TypeFactsError whose source was prepared, otherwise the input.
1342
988
  */
1343
- snapshot() {
1344
- if (this.#snapshot?.generation !== this.#generation) this.#snapshot = {
1345
- generation: this.#generation,
1346
- loader: this.replay(void 0, true)
1347
- };
1348
- return this.#snapshot.loader;
989
+ failure(error) {
990
+ if (!(error instanceof TypeFactsError)) return error;
991
+ const source = this.#attempted.get(error.moduleId);
992
+ if (!source) return error;
993
+ const range = error.start !== void 0 && error.end !== void 0 ? {
994
+ start: byteToUtf16(source.document.code, error.start),
995
+ end: byteToUtf16(source.document.code, error.end)
996
+ } : void 0;
997
+ return new CompilationFailure([this.session.reportSourceFailure({
998
+ moduleId: source.moduleId,
999
+ document: source.document,
1000
+ issue: error.issue,
1001
+ range,
1002
+ converter: source.kind === "projected" ? source.projection.converter : void 0
1003
+ })], error);
1349
1004
  }
1350
1005
  /**
1351
- * Resolves one editor candidate in a separate loader without changing a session's used CSS.
1006
+ * Registers the source and enforces one-to-one host and compiler identities within the graph.
1352
1007
  *
1353
- * @param candidate - Candidate as an editor offers it, such as `probe-4` or `state-open:`.
1354
- * @returns Queries over the shared loader containing the candidate's definitions.
1355
- * @throws If a plugin fails or the native loader rejects the generated CSS.
1008
+ * @param source - Prepared source to retain for traversal and compilation.
1009
+ * @throws If a compiler identity is shared or a host identity changes its compiler identity.
1356
1010
  */
1357
- async query(candidate) {
1358
- const query = this.snapshot().editorQuery();
1359
- return await this.resolve(query.dynamicCandidates(candidate)) ? this.snapshot().editorQuery() : query;
1011
+ #register(source) {
1012
+ const previous = this.#resolverIds.get(source.moduleId);
1013
+ if (previous !== void 0 && previous !== source.resolverId) throw new Error(`Module identity ${source.moduleId} is shared by ${previous} and ${source.resolverId}`);
1014
+ const existing = this.#sources.get(source.resolverId);
1015
+ if (existing !== void 0 && existing.moduleId !== source.moduleId) throw new Error(`Resolver identity ${source.resolverId} changed module identity`);
1016
+ this.#resolverIds.set(source.moduleId, source.resolverId);
1017
+ this.#sources.set(source.resolverId, source);
1360
1018
  }
1361
1019
  /**
1362
- * Passes new candidates to the plugins that declare their families.
1020
+ * Converts a preparation error into an original-document diagnostic batch.
1363
1021
  *
1364
- * @param candidates - Compiler requests for native utility names, complete Tailwind utility
1365
- * keys, or variant names with an `@variant ` prefix. Previously requested keys are skipped.
1366
- * @returns Whether any plugin returned CSS, so that the design system must be loaded again.
1367
- * @throws If a plugin fails.
1022
+ * @param input - Source whose document metadata identifies the failing preparation.
1023
+ * @param error - Preparation issue with optional original UTF-16 range and converter identity.
1024
+ * @returns A compilation failure retaining the preparation error as its cause.
1368
1025
  */
1369
- async resolve(candidates) {
1370
- const pending = /* @__PURE__ */ new Map();
1371
- const tailwind = [];
1372
- for (const candidate of candidates) {
1373
- if (this.#requested.has(candidate)) continue;
1374
- this.#requested.add(candidate);
1375
- if (this.#tailwind?.accepts(candidate)) tailwind.push(candidate);
1376
- for (const instance of this.#instances.values()) if (nativePlugin(instance.plugin) && instance.plugin.resolve && instance.prefixes.some((prefix) => candidate.startsWith(prefix))) {
1377
- pending.set(instance, [...pending.get(instance) ?? [], candidate]);
1378
- break;
1379
- }
1380
- }
1381
- let changed = this.#tailwind?.resolve(tailwind) ?? false;
1382
- if (changed) this.#updateTailwindCss();
1383
- for (const [instance, names] of pending) {
1384
- instance.candidates.push(...names);
1385
- const css = nativePlugin(instance.plugin) ? await instance.plugin.resolve(names, instance.context) : "";
1386
- if (css.trim()) {
1387
- instance.definitions.push(css);
1388
- changed = true;
1389
- }
1390
- }
1391
- if (changed) this.#generation++;
1392
- return changed;
1026
+ #preparationFailure(input, error) {
1027
+ return new CompilationFailure([this.session.reportSourceFailure({
1028
+ moduleId: input.moduleId,
1029
+ document: input.document,
1030
+ issue: error.issue,
1031
+ converter: error.converter,
1032
+ range: error.range
1033
+ })], error);
1393
1034
  }
1394
1035
  /**
1395
- * Lists the candidates that editors complete for the loaded dynamic families.
1036
+ * Reuses or scans a source summary and records dependency syntax failures in analysis mode.
1396
1037
  *
1397
- * @param input - Utility text before an editor's cursor, without variants, or an empty string
1398
- * for the candidates that editors always offer.
1399
- * @returns Candidate names that start with `input`, from every plugin with a catalog, sorted
1400
- * and deduplicated. Names that end with `-` are incomplete. The runtime keeps the answers for
1401
- * the empty input and for the {@link CATALOG_INPUTS} most recent other inputs.
1038
+ * @param source - Registered dependency or entry source.
1039
+ * @param entry - Entry source whose initial scan is already available.
1040
+ * @param entrySummary - Summary with the entry's compiler identity.
1041
+ * @returns A retained summary, or undefined after an analysis-mode scan failure removes the source.
1042
+ * @throws If scanning fails in strict mode or a summary changes the source's compiler identity.
1402
1043
  */
1403
- catalog(input = "") {
1404
- let names = this.#catalogs.get(input);
1405
- if (names) this.#catalogs.delete(input);
1406
- else names = Promise.all([...this.#instances.values()].map(async (instance) => nativePlugin(instance.plugin) && instance.plugin.catalog ? await instance.plugin.catalog(instance.context, input) : [])).then((lists) => [.../* @__PURE__ */ new Set([...lists.flat(), ...this.#tailwind?.catalog() ?? []])].filter((name) => name.startsWith(input)).sort());
1407
- this.#catalogs.set(input, names);
1408
- for (const key of this.#catalogs.keys()) {
1409
- if (this.#catalogs.size <= 17) break;
1410
- if (key) this.#catalogs.delete(key);
1044
+ #dependencySummary(source, entry, entrySummary) {
1045
+ let summary;
1046
+ try {
1047
+ summary = this.#summaries.get(source.moduleId) ?? (source.resolverId === entry.resolverId ? entrySummary : this.scan(source));
1048
+ } catch (error) {
1049
+ if (!this.analysis || !(error instanceof CompilationFailure)) throw error;
1050
+ this.analysis.batches.push(...error.batches);
1051
+ this.#sources.delete(source.resolverId);
1052
+ for (const dependency of this.analysis.dependencies) if (dependency.id === source.resolverId) dependency.status = "unsupported";
1053
+ return;
1411
1054
  }
1412
- return names;
1055
+ if (summary.moduleId !== source.moduleId) throw new Error(`Scanner changed module identity for ${source.resolverId}`);
1056
+ this.#summaries.set(source.moduleId, summary);
1057
+ return summary;
1413
1058
  }
1414
1059
  /**
1415
- * Loads the recorded graph again into a loader of `session`, with the current definitions.
1060
+ * Attaches checker environments, scanner probes, and observed resolutions to retained sources.
1416
1061
  *
1417
- * @param session - Session whose source IDs the new loader shares. Omission shares the
1418
- * original loader's source IDs.
1419
- * @param intermediate - Skips preparing the canonical spelling index for a loader that only
1420
- * serves a later load or a short query. Canonical queries still prepare it on first use.
1421
- * @returns A complete loader with the load's compiler options, for
1422
- * {@link NativeProjectSession.reload}.
1423
- * @throws If the recorded graph is incomplete or the native loader rejects it.
1062
+ * @returns Checker inputs in source registration order. Missing summaries are scanned and cached.
1063
+ * @throws If scanning or checker preparation fails.
1424
1064
  */
1425
- replay(session, intermediate = false) {
1426
- if (!this.#root) throw new Error("Stillwind plugin runtime has no recorded CSS graph");
1427
- const loader = session ? session.newLoader(this.options) : this.#loader?.newLoader(this.options) ?? new NativeDesignSystemLoader(this.options);
1428
- if (intermediate) loader.deferCanonicalIndex();
1429
- if (this.#tailwind) loader.requestTrailingPlugin(SETTINGS);
1430
- let step = loader.provide(0, this.#root.name, this.#root.content, this.#root.uri, this.#root.sourceMapSource, this.#root.lint);
1431
- while (step.kind !== "complete") step = loader.provideMany(step.requests.map((request) => {
1432
- if (this.#tailwind && request.specifier === SETTINGS && request.pluginOptions !== void 0) return {
1433
- id: request.id,
1434
- name: `stillwind-plugin:${SETTINGS.slice(1)}#${this.#generation}`,
1435
- content: this.#settingsCss
1436
- };
1437
- const instance = request.pluginOptions !== void 0 ? this.#instances.get(instanceKey(request)) : void 0;
1438
- const answer = instance ? this.#pluginAnswer(instanceKey(request), instance) : this.#answers.get(answerKey(request));
1439
- if (!answer) throw new Error(`Stillwind plugin runtime has no answer for ${request.specifier}`);
1065
+ #checkerSources() {
1066
+ return [...this.#sources.values()].map((source) => {
1067
+ const summary = this.#summaries.get(source.moduleId) ?? this.scan(source);
1068
+ this.#summaries.set(source.moduleId, summary);
1069
+ let environment;
1070
+ try {
1071
+ environment = checkerEnvironment(source);
1072
+ } catch (error) {
1073
+ if (error instanceof PreparationError) throw this.#preparationFailure(source, error);
1074
+ throw error;
1075
+ }
1440
1076
  return {
1441
- id: request.id,
1442
- ...answer
1077
+ ...source,
1078
+ ...environment,
1079
+ checkerSpans: summary.checkerSpans,
1080
+ checkerBindings: summary.checkerBindings,
1081
+ probes: summary.typeProbes,
1082
+ resolutions: summary.moduleSpecifiers.flatMap((specifier) => {
1083
+ const id = this.#resolutions.get(source.resolverId)?.get(specifier.source);
1084
+ return id ? [{
1085
+ id,
1086
+ start: specifier.start,
1087
+ end: specifier.end
1088
+ }] : [];
1089
+ })
1443
1090
  };
1444
- }));
1445
- return loader;
1091
+ });
1446
1092
  }
1447
1093
  /**
1448
- * Returns the answer to a plugin request with the instance's current definitions.
1094
+ * Collects declared assets for checker interpretation.
1449
1095
  *
1450
- * @param key - Importer, specifier, and options text of the instance.
1451
- * @param instance - Loaded plugin statement.
1452
- * @returns An internal buffer whose name changes with its content.
1096
+ * @returns A new map from compiler identity to the corresponding scanner asset array.
1453
1097
  */
1454
- #pluginAnswer(key, instance) {
1455
- return {
1456
- name: `stillwind-plugin:${key.replaceAll("\0", "#")}#${this.#generation}#${instance.definitions.length}`,
1457
- content: [instance.css, ...instance.definitions].join("\n"),
1458
- origin: instance.origin
1459
- };
1098
+ #assets() {
1099
+ return new Map([...this.#summaries].map(([id, summary]) => [id, summary.assets]));
1460
1100
  }
1461
1101
  /**
1462
- * Stores the generated CSS of each Tailwind statement and of the settings as their answers.
1102
+ * Adds an unverified range for each retained probe when analysis mode has no usable facts.
1103
+ *
1104
+ * @param source - Source whose scanner probes use original UTF-8 byte coordinates.
1105
+ * @param reason - Explanation included in every added range. Strict mode has no analysis to update.
1463
1106
  */
1464
- #updateTailwindCss() {
1465
- for (const [owner, instance] of this.#tailwindInstances.entries()) instance.css = this.#tailwind.css(owner);
1466
- this.#settingsCss = this.#tailwind.settingsCss();
1107
+ #unavailable(source, reason) {
1108
+ this.analysis?.unverified.push(...(this.#summaries.get(source.moduleId)?.typeProbes ?? []).map((probe) => ({
1109
+ moduleId: source.moduleId,
1110
+ start: probe.start,
1111
+ end: probe.end,
1112
+ reason
1113
+ })));
1467
1114
  }
1468
1115
  /**
1469
- * Awaits the project's Tailwind configuration and applies its `important` field.
1116
+ * Requests checker resolutions when the host enables them, recording failures as unverified probes.
1470
1117
  *
1471
- * @returns The configuration with `important` applied, or undefined without settings.
1472
- * @throws If the configuration promise rejects, its value is not an object, or both the field
1473
- * and the configuration set `important`.
1118
+ * @param source - Importing source whose resolver identity selects the returned map.
1119
+ * @returns Authored specifiers mapped to host identities, or undefined when disabled or unavailable.
1120
+ * @throws If resolution fails outside analysis mode.
1474
1121
  */
1475
- async #projectConfig() {
1476
- const { important } = this.settings ?? {};
1477
- const tailwind = await this.settings?.tailwind;
1478
- if (tailwind === void 0) return important === void 0 ? void 0 : { important };
1479
- if (typeof tailwind !== "object" || tailwind === null || Array.isArray(tailwind)) throw new Error("Stillwind config tailwind must resolve to a Tailwind configuration object");
1480
- const config = tailwind;
1481
- if (important === void 0) return config;
1482
- if (config.important !== void 0) throw new Error("Stillwind config important must not be set together with tailwind.important");
1483
- return {
1484
- ...config,
1485
- important
1122
+ async #semanticResolutions(source) {
1123
+ if (!this.host.typeFactsResolution) return;
1124
+ try {
1125
+ const backend = this.factsService();
1126
+ if (!backend) return;
1127
+ const end = startPhase("semantic-resolution");
1128
+ const sources = this.#checkerSources();
1129
+ const resolutions = this.project && this.project.revision === this.#projectRevision ? await this.project.resolve(backend, sources, this.options.typeFactsInputs) : await backend.resolveModules(sources, this.#assets(), this.options.typeFactsInputs);
1130
+ end(sources.length);
1131
+ return resolutions.get(source.resolverId);
1132
+ } catch (error) {
1133
+ if (!this.analysis) throw error;
1134
+ this.#unavailable(source, String(error));
1135
+ }
1136
+ }
1137
+ /**
1138
+ * Resolves a demanded dependency, records its status, and loads supported source for traversal.
1139
+ *
1140
+ * @param source - Registered importing source.
1141
+ * @param specifier - Authored module request.
1142
+ * @param semanticId - Optional checker fallback used when the host returns no resolution.
1143
+ * @returns Registered dependency source, or undefined for external, unresolved, or unsupported requests.
1144
+ * @throws If strict loading fails. Analysis mode records loading failures and available diagnostics.
1145
+ */
1146
+ async #followDependency(source, specifier, semanticId) {
1147
+ const resolved = await tracePhase("resolve", 1, () => this.#resolveDependency(source, specifier, semanticId));
1148
+ const observed = {
1149
+ importer: source.resolverId,
1150
+ specifier,
1151
+ id: resolved?.id,
1152
+ status: !resolved ? "unresolved" : resolved.external ? "external" : "resolved"
1486
1153
  };
1154
+ this.analysis?.dependencies.push(observed);
1155
+ if (!resolved || resolved.external) return;
1156
+ const id = this.project?.source(resolved.id)?.resolverId ?? resolved.id;
1157
+ observed.id = id;
1158
+ if (!this.#canLoadDependency(id, observed)) return;
1159
+ let resolutions = this.#resolutions.get(source.resolverId);
1160
+ if (!resolutions) this.#resolutions.set(source.resolverId, resolutions = /* @__PURE__ */ new Map());
1161
+ resolutions.set(specifier, id);
1162
+ this.host.watch(id);
1163
+ try {
1164
+ let dependency = this.#sources.get(id);
1165
+ if (!dependency) {
1166
+ dependency = await this.prepare(await tracePhase("load", 1, () => this.#load(id)));
1167
+ this.#register(dependency);
1168
+ }
1169
+ return dependency;
1170
+ } catch (error) {
1171
+ if (!this.analysis) throw error;
1172
+ observed.status = "unsupported";
1173
+ this.analysis.unverified.push({
1174
+ moduleId: source.moduleId,
1175
+ reason: String(error)
1176
+ });
1177
+ if (error instanceof CompilationFailure) this.analysis.batches.push(...error.batches);
1178
+ }
1487
1179
  }
1488
1180
  /**
1489
- * Records a request of the load, which orders the plugin statements.
1181
+ * Uses host resolution first and a checker identity only when the host returns null.
1490
1182
  *
1491
- * @param request - Import or plugin request.
1183
+ * @param source - Importer whose full resolver identity is passed to the host.
1184
+ * @param specifier - Authored module request.
1185
+ * @param semanticId - Optional identity supplied by checker resolution.
1186
+ * @returns A resolution, or null when unavailable. Analysis mode converts host exceptions to null.
1187
+ * @throws If host resolution fails in strict mode.
1492
1188
  */
1493
- #recordRequest(request) {
1494
- let requests = this.#requests.get(request.importer);
1495
- if (!requests) this.#requests.set(request.importer, requests = /* @__PURE__ */ new Map());
1496
- requests.set(request.id, request);
1189
+ async #resolveDependency(source, specifier, semanticId) {
1190
+ try {
1191
+ return await (this.project ? this.project.resolveImport(this.host, specifier, source.resolverId) : this.host.resolve(specifier, source.resolverId, { skipSelf: true })) ?? (semanticId ? { id: semanticId } : null);
1192
+ } catch (error) {
1193
+ if (!this.analysis || error instanceof ResolutionMismatchError) throw error;
1194
+ return null;
1195
+ }
1497
1196
  }
1498
1197
  /**
1499
- * Orders the plugin statements as the import-expanded stylesheet does.
1198
+ * Distinguishes traversable sources from checker declarations and unsupported dependencies.
1500
1199
  *
1501
- * @returns Each statement once, depth first from the root in request order.
1200
+ * @param id - Full resolved host identity.
1201
+ * @param observed - Mutable dependency record whose status becomes types or unsupported when skipped.
1202
+ * @returns Whether the dependency should be loaded as source.
1502
1203
  */
1503
- #orderedInstances() {
1504
- const result = /* @__PURE__ */ new Set();
1505
- const visited = /* @__PURE__ */ new Set();
1506
- /**
1507
- * Adds the statements of one stylesheet and of the stylesheets it imports.
1508
- *
1509
- * @param name - Recorded identity of the stylesheet.
1510
- */
1511
- const visit = (name) => {
1512
- if (visited.has(name)) return;
1513
- visited.add(name);
1514
- for (const request of [...this.#requests.get(name)?.values() ?? []].sort((a, b) => a.id - b.id)) {
1515
- const instance = this.#instances.get(instanceKey(request));
1516
- if (request.pluginOptions !== void 0 && instance) result.add(instance);
1517
- else {
1518
- const answer = this.#answers.get(answerKey(request));
1519
- if (answer) visit(answer.name);
1520
- }
1204
+ #canLoadDependency(id, observed) {
1205
+ const support = sourceSupport(this.host, id);
1206
+ if (support !== "source") {
1207
+ observed.status = support;
1208
+ return false;
1209
+ }
1210
+ return true;
1211
+ }
1212
+ /**
1213
+ * Reuses a prepared project source or loads new input through the host.
1214
+ *
1215
+ * @param id - Full resolved dependency identity.
1216
+ * @returns A shared prepared source or new input from the host. Do not mutate cached sources.
1217
+ * @throws If host loading, description, or reading fails.
1218
+ */
1219
+ async #load(id) {
1220
+ const cached = this.project?.source(id);
1221
+ if (cached) return cached;
1222
+ return loadSource(this.host, id);
1223
+ }
1224
+ /**
1225
+ * Reuses facts that the project keeps and collects facts only for the other sources.
1226
+ *
1227
+ * @param backend - Backend whose installed project contains the sources.
1228
+ * @param project - Project that installed the sources for the current revision.
1229
+ * @param sources - Checker sources that {@link CompilationProject.install} returned.
1230
+ * @param selected - Resolver identities of the sources that need facts. Omission selects all.
1231
+ * @returns Facts keyed by compiler identity for every selected source.
1232
+ * @throws If strict checker collection fails.
1233
+ */
1234
+ async #collectWithRetainedFacts(backend, project, sources, selected) {
1235
+ const facts = /* @__PURE__ */ new Map();
1236
+ const missing = sources.filter((source) => {
1237
+ if (selected && !selected.has(source.resolverId)) return false;
1238
+ const retained = project.facts(source);
1239
+ if (retained) facts.set(source.moduleId, [...retained]);
1240
+ return !retained;
1241
+ });
1242
+ if (missing.length === 0) return facts;
1243
+ const collected = await backend.collect(missing, this.#assets(), this.options.typeFactsInputs);
1244
+ for (const source of missing) {
1245
+ const value = collected.get(source.moduleId) ?? [];
1246
+ project.retainFacts(source, value);
1247
+ facts.set(source.moduleId, value);
1248
+ }
1249
+ return facts;
1250
+ }
1251
+ /**
1252
+ * Collects available facts for retained sources when entry probes require semantic information.
1253
+ *
1254
+ * @param selected - Resolver identities of the sources that need facts. Omission selects all.
1255
+ * Sources outside it still supply checker files when no project is installed.
1256
+ * @returns Facts keyed by compiler identity. Analysis mode records unavailable queries and may return partial facts.
1257
+ * @throws If strict checker collection fails or a compilation failure occurs while preparing checker sources.
1258
+ */
1259
+ async #collectFacts(selected) {
1260
+ if (!this.#needsTypeFacts) return /* @__PURE__ */ new Map();
1261
+ try {
1262
+ const backend = this.factsService();
1263
+ if (!backend) {
1264
+ if (!this.analysis) throw new Error("Type facts required for this compilation are unavailable");
1265
+ for (const source of this.#sources.values()) this.#unavailable(source, "Semantic queries are disabled");
1266
+ return /* @__PURE__ */ new Map();
1521
1267
  }
1522
- };
1523
- if (this.#root) visit(this.#root.name);
1524
- return [...result];
1268
+ const project = this.project?.revision === this.#projectRevision ? this.project : void 0;
1269
+ const sources = project?.install(backend, this.#checkerSources(), this.options.typeFactsInputs) ?? this.#checkerSources();
1270
+ if (project && !this.analysis) return await this.#collectWithRetainedFacts(backend, project, sources, selected);
1271
+ if (this.analysis) {
1272
+ const available = await backend.collectAvailable(sources, this.#assets(), this.options.typeFactsInputs);
1273
+ this.analysis.unverified.push(...available.unverified);
1274
+ return available.facts;
1275
+ }
1276
+ return await backend.collect(sources, this.#assets(), this.options.typeFactsInputs);
1277
+ } catch (error) {
1278
+ if (!this.analysis || error instanceof CompilationFailure) throw error;
1279
+ for (const source of this.#sources.values()) this.#unavailable(source, String(error));
1280
+ return /* @__PURE__ */ new Map();
1281
+ }
1525
1282
  }
1526
1283
  };
1527
- // src/css/css.ts
1528
1284
  /**
1529
- * Checks whether an identity names a stylesheet.
1285
+ * Decides whether a resolved dependency is loaded as source.
1530
1286
  *
1531
- * @param id - Resolver identity or file path.
1532
- * @returns Whether the complete identity ends in `.css`, ignoring case. The check includes any
1533
- * query suffix.
1287
+ * @param host - Host whose `supports` and `typeFactsResolution` settings apply.
1288
+ * @param id - Full resolved host identity.
1289
+ * @returns `types` for declaration files, and for package files when the host does not resolve
1290
+ * imports through the checker. Returns `unsupported` for files that the host or the default
1291
+ * extension list rejects, and `source` otherwise.
1534
1292
  */
1535
- function isStylesheet(id) {
1536
- return /\.css$/i.test(id);
1293
+ function sourceSupport(host, id) {
1294
+ const name = cleanModuleId(id);
1295
+ if (/\.d\.[cm]?ts$/.test(name) || !host.typeFactsResolution && /(?:^|[\\/])node_modules[\\/]/.test(name)) return "types";
1296
+ if (!(host.supports?.(id) ?? /\.(?:[cm]?[jt]sx?|astro|svelte|vue)$/.test(name))) return "unsupported";
1297
+ return "source";
1537
1298
  }
1538
1299
  /**
1539
- * Loads original CSS, then retries with recovered definitions if that load fails.
1300
+ * Selects imports needed to answer the current semantic demand.
1540
1301
  *
1541
- * @param root - Resolved CSS entrypoint.
1542
- * @param options - Compiler policies used by semantic queries.
1543
- * @param host - Resolver and reads of the captured original buffers.
1544
- * @param pluginInputs - Plugins for `@plugin` statements, as {@link loadCssGraph} describes.
1545
- * @returns A query graph and whether its sources were recovered. Original buffers remain unchanged.
1546
- * The recovered graph must only supply editor queries, because its text omits authored rules.
1547
- * @throws If both loads fail, including unresolved imports or unreadable files.
1302
+ * @param summary - Scanner summary for the source being traversed.
1303
+ * @param requested - Null for entry probes, `*` for a namespace demand, or a specific exported
1304
+ * name.
1305
+ * @returns Probe imports, imports for a matched export, or matching re-export demands. Unmatched
1306
+ * and namespace demands conservatively retain all imports and re-exports.
1548
1307
  */
1549
- async function loadEditorCssGraph(root, options, host, pluginInputs) {
1550
- try {
1551
- return {
1552
- ...await loadCssGraph(root, options, host, void 0, void 0, pluginInputs),
1553
- recovered: false
1554
- };
1555
- } catch {
1556
- return {
1557
- ...await loadCssGraph(root, options, {
1558
- ...host,
1559
- read: async (id) => editorCssSource(await host.read(id))
1560
- }, void 0, void 0, pluginInputs),
1561
- recovered: true
1562
- };
1563
- }
1308
+ function semanticDependencies(summary, requested) {
1309
+ if (requested === null) return summary.probeImports;
1310
+ const selected = summary.exportImports.find((entry) => entry.name === requested);
1311
+ if (requested !== "*" && selected) return selected.imports;
1312
+ const reExports = summary.reExports.filter((entry) => requested === "*" || entry.exported === requested || entry.exported === "*");
1313
+ if (requested !== "*" && reExports.length > 0) return reExports.map((entry) => ({
1314
+ source: entry.source,
1315
+ imported: entry.exported === "*" ? requested : entry.imported
1316
+ }));
1317
+ return [...summary.imports, ...summary.reExports];
1564
1318
  }
1319
+ // src/compilation/request.ts
1565
1320
  /**
1566
- * Selects the user's own CSS for stylesheet lint. The root is linted unless it lies under
1567
- * `node_modules`. An import is linted when lint checks its importer, its specifier is a relative
1568
- * or absolute path, and its file does not lie under `node_modules`. A package specifier such as
1569
- * `stillwind` or `tailwindcss` therefore excludes the package and everything it imports, even when
1570
- * the package resolves outside `node_modules`.
1321
+ * Creates an empty observed graph before loading its semantic dependencies.
1571
1322
  *
1572
- * @param id - Resolved CSS file identity.
1573
- * @param importer - Importing file and its lint mark, or undefined for the root.
1574
- * @param specifier - Import request text, or undefined for the root.
1575
- * @returns Whether stylesheet lint checks the file.
1323
+ * @param entry - Compiler module ID of the loaded entry source.
1324
+ * @returns A mutable graph with no reports or dependencies and generation initially allowed.
1576
1325
  */
1577
- function lintsStylesheet(id, importer, specifier) {
1578
- if (/[\\/]node_modules[\\/]/.test(id)) return false;
1579
- return !importer || importer.lint && specifier !== void 0 && PATH_SPECIFIER.test(specifier);
1326
+ function createModuleAnalysis(entry) {
1327
+ return {
1328
+ entry,
1329
+ coverage: "observed",
1330
+ modules: [],
1331
+ batches: [],
1332
+ fixes: [],
1333
+ sources: [],
1334
+ dependencies: [],
1335
+ unverified: [],
1336
+ generation: "complete"
1337
+ };
1580
1338
  }
1339
+ // src/compilation/compiler.ts
1340
+ /** Most reloads with new plugin definitions during one compilation of a graph. */
1341
+ const PLUGIN_ROUNDS = 3;
1581
1342
  /**
1582
- * Names the package that supplies an imported stylesheet that is not the user's own CSS.
1343
+ * Analyzes an entry and its semantic dependencies without requiring stylesheet delivery IDs.
1344
+ * Source failures return diagnostic batches. Unavailable semantic information records unverified
1345
+ * ranges. Entry I/O and native transport failures reject.
1346
+ * The caller owns the initialized session and the lazy checker service.
1583
1347
  *
1584
- * A package specifier, such as `stillwind` or `@scope/name/theme.css`, names its package. A path
1585
- * specifier keeps the package of its importer, so a package's relative imports stay in the
1586
- * package. Otherwise, the last `node_modules` directory in `id` names the package.
1587
- *
1588
- * @param id - Resolved CSS file identity.
1589
- * @param specifier - Import request text.
1590
- * @param importerPackage - Package of the importing file, or undefined when it has none.
1591
- * @returns The package name, or undefined when none of these rules names one.
1348
+ * @param session - Native project session with an initialized design system.
1349
+ * @param factsService - Supplies a checker configured for the host's TypeScript environment,
1350
+ * or undefined when semantic facts are unavailable.
1351
+ * @param id - Full resolver identity of the entry, including query suffixes.
1352
+ * @param host - Source loading, resolution, metadata, and dependency tracking operations.
1353
+ * @param typeFactsInputs - Captured overlays and ambient declarations for this analysis.
1354
+ * @param project - Optional sources prepared by earlier analyses of this project.
1355
+ * The caller must invalidate changed sources before analysis starts.
1356
+ * @returns Reports and sources for the semantic dependencies demanded by the entry.
1357
+ * @throws If entry I/O fails, a host changes resolver identity, or native transport operations fail.
1592
1358
  */
1593
- function stylesheetPackage(id, specifier, importerPackage) {
1594
- if (!PATH_SPECIFIER.test(specifier)) {
1595
- const [first, second] = specifier.split("/");
1596
- return first.startsWith("@") && second !== void 0 ? `${first}/${second}` : first;
1359
+ async function analyzeModule(session, factsService, id, host, typeFactsInputs, project) {
1360
+ const revision = project?.revision;
1361
+ const captured = project?.source(id);
1362
+ const input = captured ?? await loadSource(host, id);
1363
+ if (project?.revision !== revision) project = void 0;
1364
+ const analysis = createModuleAnalysis(input.moduleId);
1365
+ if (!captured && input.resolverId !== id) throw new Error(`Host changed resolver identity for ${id}`);
1366
+ await compileGraph(session, factsService, input.document.code, input.resolverId, host, {
1367
+ diagnostics: "collect",
1368
+ moduleCssImport: "stillwind/module-css",
1369
+ typeFactsInputs
1370
+ }, analysis, input, project);
1371
+ for (const batch of analysis.batches) for (const report of batch.reports) {
1372
+ const edits = report.actions[0]?.edits;
1373
+ if (edits?.length && report.code !== "prefer-sorted-utilities") analysis.fixes.push(edits);
1597
1374
  }
1598
- if (importerPackage !== void 0) return importerPackage;
1599
- return [...id.matchAll(/[\\/]node_modules[\\/]((?:@[^\\/]+[\\/])?[^\\/]+)/g)].at(-1)?.[1].replace("\\", "/");
1375
+ return analysis;
1600
1376
  }
1601
1377
  /**
1602
- * Loads a CSS graph and returns the completed native loader and its resource references.
1603
- * `root` must already be resolved and accepted by the host's read and watch methods.
1604
- * `options` configures a new loader. If `suppliedLoader` is given, it must not have
1605
- * received any input yet, and this function uses its existing configuration.
1606
- * `rootContent` skips reading the root file. The function still watches that file
1607
- * and all resolved dependencies. Each file is marked for stylesheet lint as `host.lint` decides,
1608
- * or as {@link lintsStylesheet} decides when the host omits it.
1609
- * Canonical queries build their indexes on first use.
1378
+ * Compiles an entry buffer and its demanded semantic dependencies into a project session.
1379
+ * The host descriptor supplies the module identity and parser metadata for each source.
1380
+ * Type facts are requested lazily for original-coordinate probes in JS/TS or SFC inputs.
1610
1381
  *
1611
- * Reads run concurrently, and each request ID is read only once. Responses ready
1612
- * in the same event-loop turn are sent together to reduce native calls. Faster reads
1613
- * can reveal more imports without waiting for slower reads.
1614
- * Resolution, read, and native loading errors reject the promise. Reads already
1615
- * started continue, and files already registered with the watcher stay registered.
1382
+ * Collect mode retains compiler and checker reports, including known syntax and projection
1383
+ * failures. The default throw mode rejects compiler diagnostics. Lint findings only produce warnings.
1384
+ * Host I/O, checker process, and malformed native transport failures propagate in both modes.
1385
+ * Failed compilation can still update the session, register watches, and send warnings.
1616
1386
  *
1617
- * @param root - Resolved CSS entrypoint accepted by the host's read and watch operations.
1618
- * @param options - Compiler settings used when creating a new loader.
1619
- * @param host - CSS resolver, reader, source identity operations, and dependency watcher.
1620
- * @param rootContent - Optional entrypoint text that replaces the initial filesystem read.
1621
- * @param suppliedLoader - Optional configured loader that has not received any CSS input.
1622
- * @param pluginInputs - Plugins for `@plugin` statements. Omission uses no configured plugins,
1623
- * the root's directory as the project directory, and the host's plugin operations.
1624
- * @returns A promise for the completed native loader and its authored resource references.
1625
- * @throws If resolving, reading, or loading the CSS graph fails.
1387
+ * @param session - Native project session with an initialized design system.
1388
+ * @param factsService - Supplies the type-facts service when the source graph needs semantic facts.
1389
+ * @param code - Entry source before Stillwind transformation.
1390
+ * @param id - Full resolver identity of the entry source, including its query suffix.
1391
+ * @param host - Source metadata, resolution, reading, dependency tracking, and warning operations.
1392
+ * @param options - Diagnostic behavior, captured checker inputs, and generated imports for the entry.
1393
+ * @param project - Optional sources shared across compilations whose dependency text does not
1394
+ * change. When the project holds different text for the entry, this compilation does not use it.
1395
+ * @returns A promise for the entry output and composition metadata, or undefined when normal mode
1396
+ * produces no entry code.
1397
+ * @throws If compilation rejects diagnostics, source preparation fails, or host or checker operations fail.
1626
1398
  */
1627
- async function loadCssGraph(root, options, host, rootContent, suppliedLoader, pluginInputs) {
1628
- const loader = suppliedLoader ?? new NativeDesignSystemLoader(options);
1629
- loader.deferCanonicalIndex();
1630
- const plugins = new PluginRuntime(options, pluginInputs?.plugins ?? [], pluginInputs?.root ?? root.replace(/[\\/][^\\/]*$/, ""), host.plugins, (path, kind) => {
1631
- if (kind === "directory") host.watchDirectory?.(path);
1632
- else host.watch(path);
1633
- }, pluginInputs?.previous, pluginInputs && {
1634
- tailwind: pluginInputs.tailwind,
1635
- important: pluginInputs.important
1636
- });
1637
- host.watch(root);
1638
- const lints = /* @__PURE__ */ new Map();
1639
- const packages = /* @__PURE__ */ new Map();
1640
- const lint = (id, importer, specifier) => host.lint ? host.lint(id, importer, specifier) : lintsStylesheet(id, importer, specifier);
1641
- lints.set(root, lint(root));
1642
- const rootAnswer = {
1643
- name: root,
1644
- content: rootContent ?? await host.read(root),
1645
- uri: host.documentUri(root),
1646
- sourceMapSource: host.sourceMapSource(root),
1647
- lint: lints.get(root)
1648
- };
1649
- plugins.recordRoot(rootAnswer);
1650
- const initial = loader.provide(0, rootAnswer.name, rootAnswer.content, rootAnswer.uri, rootAnswer.sourceMapSource, rootAnswer.lint);
1651
- let completion;
1652
- await new Promise((resolveLoad, rejectLoad) => {
1653
- const started = /* @__PURE__ */ new Set();
1654
- let stopped = false;
1655
- let queued = false;
1656
- let ready = [];
1657
- /**
1658
- * Stops graph advancement and rejects the pending load.
1659
- * @param error - Resolution, reading, or native loading failure passed to the caller.
1660
- */
1661
- const fail = (error) => {
1662
- stopped = true;
1663
- rejectLoad(error);
1664
- };
1665
- /**
1666
- * Completes the graph or starts reads for requests that have not already started.
1667
- * @param step - Native loading step. Completion stores resources and resolves the load.
1668
- */
1669
- const advance = (step) => {
1670
- if (step.kind === "complete") {
1671
- completion = step;
1672
- stopped = true;
1673
- resolveLoad();
1674
- return;
1675
- }
1676
- for (const request of step.requests) {
1677
- if (started.has(request.id)) continue;
1678
- started.add(request.id);
1679
- /**
1680
- * Resolves, watches, and reads this request, then schedules a batch of ready responses.
1681
- * An import that the host cannot resolve or read is answered as unresolved.
1682
- * @returns A promise that resolves after queuing the response, or after observing a stopped load.
1683
- * @throws If a plugin fails to load. The attached rejection handler stops the load.
1684
- */
1685
- const read = async () => {
1686
- if (request.pluginOptions !== void 0) {
1687
- const answer = await plugins.answerPlugin(request, lints.get(request.importer) ?? false);
1688
- if (plugins.tailwind) loader.deferCanonicalIndex();
1689
- if (!stopped) {
1690
- ready.push({
1691
- id: request.id,
1692
- ...answer
1693
- });
1694
- schedule();
1695
- }
1696
- return;
1697
- }
1698
- /**
1699
- * Answers the request as unresolved, so the loader skips the import and stylesheet lint
1700
- * reports it.
1701
- */
1702
- const unresolved = () => {
1703
- if (stopped) return;
1704
- const answer = {
1705
- name: request.specifier,
1706
- content: "",
1707
- lint: false,
1708
- unresolved: true
1709
- };
1710
- plugins.recordImport(request, answer);
1711
- ready.push({
1712
- id: request.id,
1713
- ...answer
1714
- });
1715
- schedule();
1716
- };
1717
- let name;
1718
- try {
1719
- name = await host.resolve(request.specifier, request.importer);
1720
- } catch {
1721
- unresolved();
1722
- return;
1723
- }
1724
- if (stopped) return;
1725
- host.watch(name);
1726
- let content;
1727
- try {
1728
- content = await host.read(name);
1729
- } catch {
1730
- unresolved();
1731
- return;
1732
- }
1733
- if (stopped) return;
1734
- const marked = lint(name, {
1735
- id: request.importer,
1736
- lint: lints.get(request.importer) ?? false
1737
- }, request.specifier);
1738
- lints.set(name, (lints.get(name) ?? false) || marked);
1739
- const library = marked ? void 0 : stylesheetPackage(name, request.specifier, packages.get(request.importer));
1740
- if (!marked && !packages.has(name)) packages.set(name, library);
1741
- const answer = {
1742
- name,
1743
- content,
1744
- uri: host.documentUri(name),
1745
- sourceMapSource: host.sourceMapSource(name),
1746
- lint: marked,
1747
- ...marked ? {} : { origin: {
1748
- kind: "library",
1749
- name: library
1750
- } }
1751
- };
1752
- plugins.recordImport(request, answer);
1753
- ready.push({
1754
- id: request.id,
1755
- ...answer
1756
- });
1757
- schedule();
1758
- };
1759
- read().catch(fail);
1399
+ async function compileModule(session, factsService, code, id, host, options = {}, project) {
1400
+ const captured = project?.source(id);
1401
+ return compileGraph(session, factsService, code, id, host, options, void 0, void 0, captured && captured.document.code !== code ? void 0 : project);
1402
+ }
1403
+ /**
1404
+ * Prepares the demanded graph, compiles it into the session, and derives the entry output.
1405
+ *
1406
+ * @param session - Initialized native session that retains successful module artifacts.
1407
+ * @param factsService - Lazy checker backend for semantic probes.
1408
+ * @param code - Original entry text used when entryInput is absent.
1409
+ * @param id - Full host identity of the entry.
1410
+ * @param host - Stable source metadata, resolution, and notification operations.
1411
+ * @param options - Diagnostic policy, captured checker inputs, and entry transport imports.
1412
+ * @param analysis - Optional object populated with sources, dependencies, reports, and generation status.
1413
+ * @param entryInput - Optional loaded entry, which takes precedence over code and host.describe.
1414
+ * @param project - Optional prepared sources shared with other analyses of this project.
1415
+ * @returns Entry output, a diagnostic-only output after a collected failure, or undefined when no code is emitted.
1416
+ * @throws If strict compilation fails or a host or transport failure cannot be collected.
1417
+ */
1418
+ async function compileGraph(session, factsService, code, id, host, options, analysis, entryInput, project) {
1419
+ const graph = new ModuleGraph(session, factsService, host, options, analysis, project);
1420
+ const end = startPhase("entry");
1421
+ let hasModuleCssImport = false;
1422
+ try {
1423
+ const descriptor = entryInput ?? {
1424
+ resolverId: id,
1425
+ ...host.describe(id),
1426
+ document: {
1427
+ ...host.describe(id).document,
1428
+ code
1760
1429
  }
1761
1430
  };
1762
- /** Sends the responses that are ready in the current event-loop turn together. */
1763
- const schedule = () => {
1764
- if (!queued) {
1765
- queued = true;
1766
- setTimeout(() => {
1767
- queued = false;
1768
- const responses = ready;
1769
- ready = [];
1770
- if (stopped) return;
1771
- try {
1772
- advance(loader.provideMany(responses));
1773
- } catch (error) {
1774
- fail(error);
1775
- }
1776
- });
1777
- }
1431
+ const entrySource = { ...await graph.prepare(descriptor) };
1432
+ const entrySummary = graph.scan(entrySource);
1433
+ hasModuleCssImport = entrySummary.moduleCssImports > 0;
1434
+ if (entrySummary.macroImports > 0) entrySource.stylesheetImports = options.stylesheetImports;
1435
+ entrySource.moduleCssImport = hasModuleCssImport ? options.moduleCssImport : "stillwind/module-css";
1436
+ await graph.collectDependencies(entrySource, entrySummary);
1437
+ const typedSources = await graph.collectTypedSources(entrySource);
1438
+ const producer = analysis ? void 0 : entrySource.moduleId;
1439
+ const projectOutput = await tracePhase("native-compile", typedSources.length, () => compileWithPlugins(session, () => session.compile(typedSources, producer), PLUGIN_ROUNDS));
1440
+ if (analysis) recordAnalysis(analysis, projectOutput.modules, session, typedSources, graph);
1441
+ reportOutputDiagnostics(projectOutput.modules, graph, host, options);
1442
+ return entryOutput(projectOutput.modules, entrySource.moduleId, hasModuleCssImport, options);
1443
+ } catch (error) {
1444
+ const failure = graph.failure(error);
1445
+ if (failure instanceof CompilationFailure && options.diagnostics === "collect") {
1446
+ if (analysis) {
1447
+ analysis.batches = [...failure.batches];
1448
+ analysis.generation = "blocked";
1449
+ }
1450
+ return failedOutput(entryInput?.moduleId ?? host.describe(id).moduleId, failure.batches, hasModuleCssImport);
1451
+ }
1452
+ throw failure;
1453
+ } finally {
1454
+ end();
1455
+ }
1456
+ }
1457
+ /**
1458
+ * Selects the entry and computes its composition dependency identities and topology fingerprint.
1459
+ *
1460
+ * @param modules - Native outputs in compiler order.
1461
+ * @param entryModuleId - Compiler identity of the requested entry.
1462
+ * @param hasModuleCssImport - Whether the entry requested an explicit CSS value.
1463
+ * @param options - Diagnostic policy controlling whether reports from all modules are attached.
1464
+ * @returns Enriched entry output. Throw mode omits entries without nonempty code, and collect mode retains them.
1465
+ */
1466
+ function entryOutput(modules, entryModuleId, hasModuleCssImport, options) {
1467
+ const output = modules.find((candidate) => candidate.moduleId === entryModuleId);
1468
+ const composition = output?.composition ?? [];
1469
+ const compositionModules = [...new Set(composition.map(({ base }) => base.moduleId))].filter((module) => module !== entryModuleId);
1470
+ const compositionTopology = JSON.stringify(composition.map(({ derived, base }) => [JSON.stringify([
1471
+ derived.moduleId,
1472
+ derived.path,
1473
+ derived.ordinal
1474
+ ]), JSON.stringify([
1475
+ base.moduleId,
1476
+ base.path,
1477
+ base.ordinal
1478
+ ])]).sort((a, b) => a[0].localeCompare(b[0]) || a[1].localeCompare(b[1])));
1479
+ if (options.diagnostics === "collect" && output) return {
1480
+ ...output,
1481
+ hasModuleCssImport,
1482
+ compositionModules,
1483
+ compositionTopology,
1484
+ diagnostics: modules.flatMap((module) => module.diagnostics),
1485
+ reports: modules.flatMap((module) => module.reports)
1486
+ };
1487
+ if (!output?.code) return;
1488
+ return {
1489
+ ...output,
1490
+ hasModuleCssImport,
1491
+ compositionModules,
1492
+ compositionTopology
1493
+ };
1494
+ }
1495
+ /**
1496
+ * Populates analysis batches and removes artifacts when missing semantic facts block lowering.
1497
+ *
1498
+ * @param analysis - Mutable result whose unverified ranges are deduplicated and generation status updated.
1499
+ * @param modules - Mutable native outputs whose reports are filtered and artifacts may be cleared.
1500
+ * @param session - Session used to diagnose sources independently when facts are unavailable.
1501
+ * @param typedSources - Prepared sources from the same compilation, with available type facts attached.
1502
+ * @param graph - Graph retaining scanner summaries for the compiled modules.
1503
+ */
1504
+ function recordAnalysis(analysis, modules, session, typedSources, graph) {
1505
+ analysis.modules = modules;
1506
+ analysis.unverified = [...new Map(analysis.unverified.map((range) => [JSON.stringify(range), range])).values()];
1507
+ const localReports = analysis.unverified.length ? session.diagnose(typedSources) : [];
1508
+ for (const module of modules) {
1509
+ module.reports = localReports.find((batch) => batch.module === module.moduleId)?.reports ?? module.reports;
1510
+ const ranges = analysis.unverified.filter((range) => range.moduleId === module.moduleId);
1511
+ const generationUnverified = generationNeedsFacts(graph.summary(module.moduleId), ranges);
1512
+ module.reports = verifiedReports(module.reports, ranges);
1513
+ if (generationUnverified || module.diagnostics.length) analysis.generation = "blocked";
1514
+ if (generationUnverified) clearArtifacts(module);
1515
+ analysis.batches.push({
1516
+ module: module.moduleId,
1517
+ reports: module.reports
1518
+ });
1519
+ }
1520
+ }
1521
+ /**
1522
+ * Checks whether unavailable semantic information affects a probe required for lowering.
1523
+ *
1524
+ * @param summary - Scanner summary for the module, or undefined if unavailable.
1525
+ * @param ranges - Unverified ranges in original UTF-8 bytes. Missing bounds cover the whole module.
1526
+ * @returns Whether an unbounded range exists or a bounded range overlaps a probe beyond recognition.
1527
+ */
1528
+ function generationNeedsFacts(summary, ranges) {
1529
+ return ranges.some((range) => {
1530
+ if (range.start === void 0 || range.end === void 0) return true;
1531
+ return summary?.typeProbes.some((probe) => !probe.recognitionOnly && overlaps(range, probe.start, probe.end));
1532
+ });
1533
+ }
1534
+ /**
1535
+ * Keeps source failures while omitting missing checker facts errors in unverified ranges.
1536
+ *
1537
+ * @param reports - Reports with original UTF-8 locations.
1538
+ * @param ranges - Unverified original UTF-8 ranges for the same module.
1539
+ * @returns A filtered array in report order. Other diagnostic codes remain unchanged.
1540
+ */
1541
+ function verifiedReports(reports, ranges) {
1542
+ return reports.filter((report) => {
1543
+ if (report.code !== checkerFactsRequiredCode) return true;
1544
+ const { start, end } = report.primary.location;
1545
+ return !ranges.some((range) => overlaps(range, start, end));
1546
+ });
1547
+ }
1548
+ /** `CompileDiagnostic::CheckerFactsRequired`, which unverified semantic ranges can cause. */
1549
+ const checkerFactsRequiredCode = "SW30001";
1550
+ /**
1551
+ * Tests whether a diagnostic or probe overlaps an unavailable semantic range.
1552
+ *
1553
+ * @param range - Half-open original UTF-8 range. Missing bounds cover the entire module.
1554
+ * @param start - Inclusive original UTF-8 byte offset.
1555
+ * @param end - Exclusive original UTF-8 byte offset.
1556
+ * @returns Whether the ranges intersect, treating an unbounded range as intersecting everything.
1557
+ */
1558
+ function overlaps(range, start, end) {
1559
+ if (range.start === void 0 || range.end === void 0) return true;
1560
+ return start < range.end && end > range.start;
1561
+ }
1562
+ /**
1563
+ * Removes generated artifacts while keeping reports and composition metadata for analysis.
1564
+ *
1565
+ * @param module - Mutable output whose missing facts make its generated artifacts unreliable.
1566
+ */
1567
+ function clearArtifacts(module) {
1568
+ module.code = null;
1569
+ module.css = "";
1570
+ module.resources = [];
1571
+ module.classes = [];
1572
+ module.symbols = [];
1573
+ module.mappings = [];
1574
+ }
1575
+ /**
1576
+ * Checks output identities, reports lint and rejected-name warnings, and enforces diagnostic policy.
1577
+ *
1578
+ * @param modules - Native outputs with identities registered in graph.
1579
+ * @param graph - Source graph used to verify each output's host identity.
1580
+ * @param host - Warning receiver, which may receive messages before a later failure.
1581
+ * @param options - Collect mode retains compiler reports instead of throwing.
1582
+ * @throws If an output identity is unknown or throw mode encounters compiler errors.
1583
+ */
1584
+ function reportOutputDiagnostics(modules, graph, host, options) {
1585
+ for (const output of modules) {
1586
+ graph.resolverId(output.moduleId);
1587
+ if (output.diagnostics.length > 0 && options.diagnostics !== "collect") throw new CompilationFailure(modules.filter((module) => module.diagnostics.length > 0).map((module) => ({
1588
+ module: module.moduleId,
1589
+ reports: module.reports
1590
+ })));
1591
+ reportLintWarnings(output, host);
1592
+ warnRejectedNames(output.rejectedNames ?? [], (message) => host.warn(message));
1593
+ }
1594
+ }
1595
+ /**
1596
+ * Reports naming fallbacks through the host warning channel without a source location.
1597
+ *
1598
+ * @param rejected - Generator rejections in request order.
1599
+ * @param warn - Receives the family, input hash, and rejection reason for each fallback.
1600
+ */
1601
+ function warnRejectedNames(rejected, warn) {
1602
+ for (const entry of rejected) warn(`stillwind: the ${entry.kind} name for ${entry.hash} was rejected: ${entry.reason}`);
1603
+ }
1604
+ /**
1605
+ * Sends enabled lint findings through the host without changing their report severity.
1606
+ *
1607
+ * @param output - Findings and per-rule lint levels. Missing settings default to off.
1608
+ * @param host - Receiver for warning text with original source positions.
1609
+ */
1610
+ function reportLintWarnings(output, host) {
1611
+ for (const finding of output.lintFindings ?? []) {
1612
+ if ((output.lintSettings?.[finding.rule] ?? "off") === "off") continue;
1613
+ host.warn(`${finding.rule}: ${finding.message} (${finding.uri}:${finding.start})`);
1614
+ }
1615
+ }
1616
+ /**
1617
+ * Projects a report's primary label into the diagnostic shape returned by compilation.
1618
+ *
1619
+ * @param report - Structured compiler report.
1620
+ * @returns Primary location and scope, diagnostic code and class, message, and notes. Related
1621
+ * labels and severity remain in the report.
1622
+ */
1623
+ function reportDiagnostic(report) {
1624
+ return {
1625
+ ...report.primary.location,
1626
+ scope: report.primary.scope,
1627
+ code: report.code,
1628
+ ...report.class && { class: report.class },
1629
+ message: report.message,
1630
+ notes: report.notes
1631
+ };
1632
+ }
1633
+ /**
1634
+ * Builds a collect-mode entry output when preparation, scanning, or checking failed.
1635
+ *
1636
+ * @param moduleId - Compiler identity of the entry module.
1637
+ * @param batches - Failure reports from the attempted compilation.
1638
+ * @param hasModuleCssImport - Whether scanning found an explicit CSS value import in the entry.
1639
+ * @returns An output with null code, empty generated artifacts, all reports, and diagnostics
1640
+ * derived only from error reports.
1641
+ */
1642
+ function failedOutput(moduleId, batches, hasModuleCssImport) {
1643
+ const reports = batches.flatMap((batch) => batch.reports);
1644
+ return {
1645
+ moduleId,
1646
+ code: null,
1647
+ css: "",
1648
+ resources: [],
1649
+ mappings: [],
1650
+ classes: [],
1651
+ symbols: [],
1652
+ diagnostics: reports.filter((report) => report.severity === "error").map(reportDiagnostic),
1653
+ reports,
1654
+ rejectedNames: [],
1655
+ dynamicCandidates: [],
1656
+ lintFindings: [],
1657
+ lintSettings: {},
1658
+ composition: [],
1659
+ hasModuleCssImport,
1660
+ compositionModules: [],
1661
+ compositionTopology: "[]"
1662
+ };
1663
+ }
1664
+ // src/css/banners.ts
1665
+ /**
1666
+ * Formats notices as the prefix of a published stylesheet.
1667
+ *
1668
+ * @param banners - Notices in published order without duplicates, as a native plan or part lists
1669
+ * them. Callers that combine lists must order them again with `cssBanners` from `stillwind/css`.
1670
+ * @returns The notices in the given order, each followed by a newline.
1671
+ */
1672
+ function cssBannerPrefix(banners) {
1673
+ return banners.map((banner) => `${banner}\n`).join("");
1674
+ }
1675
+ /**
1676
+ * Adds notices before a CSS body without changing the body.
1677
+ *
1678
+ * @param output - CSS body and the notices that it requires, in the form that
1679
+ * {@link cssBannerPrefix} accepts.
1680
+ * @returns The published stylesheet text, or an empty string when the body is blank.
1681
+ */
1682
+ function finalizeCss(output) {
1683
+ return output.css.trim() ? cssBannerPrefix(output.banners ?? []) + output.css : "";
1684
+ }
1685
+ // src/css/plugins/host.ts
1686
+ /**
1687
+ * Matches an import or `@plugin` specifier that names a file by a relative or absolute path or
1688
+ * a `file:` URL, rather than a package.
1689
+ */
1690
+ const PATH_SPECIFIER = /^(?:\.{1,2}[\\/]|[\\/]|[a-z]:[\\/]|file:)/i;
1691
+ /**
1692
+ * Recognizes Tailwind's plugin export forms without executing a factory.
1693
+ *
1694
+ * @param value - Default export of a plugin module.
1695
+ * @returns Whether `value` is a function or an object with a `handler` function.
1696
+ */
1697
+ function isTailwindPlugin(value) {
1698
+ return typeof value === "function" || typeof value === "object" && value !== null && typeof value.handler === "function";
1699
+ }
1700
+ /**
1701
+ * Whether a loaded plugin uses the Stillwind plugin contract.
1702
+ *
1703
+ * @param plugin - Configured or loaded plugin.
1704
+ * @returns Whether `plugin` has a `css` function, which Tailwind plugins lack.
1705
+ */
1706
+ function nativePlugin(plugin) {
1707
+ return typeof plugin === "object" && plugin !== null && "css" in plugin && typeof plugin.css === "function";
1708
+ }
1709
+ /**
1710
+ * Selects the plugin that a module exports by default.
1711
+ *
1712
+ * @param module - Evaluated module namespace.
1713
+ * @param specifier - Request that loaded the module, used in the error message.
1714
+ * @returns The default export.
1715
+ * @throws If the default export is neither a Stillwind plugin object nor a Tailwind v4 plugin.
1716
+ */
1717
+ function defaultPluginExport(module, specifier) {
1718
+ const plugin = module?.default;
1719
+ if (isTailwindPlugin(plugin)) return plugin;
1720
+ if (typeof plugin !== "object" || plugin === null || typeof plugin.name !== "string" || typeof plugin.css !== "function") throw new Error(`Stillwind plugin ${specifier} must export a plugin object by default, or a Tailwind v4 handler`);
1721
+ return plugin;
1722
+ }
1723
+ /**
1724
+ * Returns the utility text before the cursor for plugin catalog lookup.
1725
+ *
1726
+ * @param text - Text before the cursor. The candidate ends at the cursor and starts after the
1727
+ * last whitespace, quote, backtick, `;`, `{`, or `}`.
1728
+ * @returns The candidate without its variants, such as `icon-mdi--cl` for `hover:icon-mdi--cl`.
1729
+ */
1730
+ function catalogInput(text) {
1731
+ const candidate = /[^\s"'`;{}]*$/.exec(text)[0];
1732
+ let depth = 0;
1733
+ for (let index = candidate.length - 1; index >= 0; index--) {
1734
+ const character = candidate[index];
1735
+ if (character === "]" || character === ")") depth++;
1736
+ else if ((character === "[" || character === "(") && depth > 0) depth--;
1737
+ else if (character === ":" && depth === 0) return candidate.slice(index + 1);
1738
+ }
1739
+ return candidate;
1740
+ }
1741
+ /**
1742
+ * Identifies one `@plugin` statement independently of its request ID.
1743
+ *
1744
+ * @param request - Plugin request.
1745
+ * @returns Importer, specifier, and JSON options joined by NUL characters.
1746
+ */
1747
+ function instanceKey(request) {
1748
+ return `${request.importer}\0${request.specifier}\0${JSON.stringify(request.pluginOptions ?? [])}`;
1749
+ }
1750
+ /**
1751
+ * Identifies one request independently of its ID, which changes between loads.
1752
+ *
1753
+ * @param request - Loader request.
1754
+ * @returns Importer, specifier, and JSON plugin options joined by NUL characters. An `@import`
1755
+ * has no options part.
1756
+ */
1757
+ function answerKey(request) {
1758
+ return `${request.importer}\0${request.specifier}\0${JSON.stringify(request.pluginOptions) ?? ""}`;
1759
+ }
1760
+ // src/css/plugins/runtime.ts
1761
+ /**
1762
+ * Specifier of the `@plugin` request that the native loader adds after the root stylesheet for
1763
+ * the Tailwind settings. Decoded CSS never contains NUL, so no authored statement has it.
1764
+ */
1765
+ const SETTINGS = "\0stillwind-tailwind-settings";
1766
+ /**
1767
+ * Matches `@stillwind-dynamic <prefix>*;` or `<prefix>[*];` and captures the prefix.
1768
+ */
1769
+ const DYNAMIC = /@stillwind-dynamic\s+([^\s;*[\]]+)(?:\[\*\]|\*)\s*;/g;
1770
+ /**
1771
+ * Runs the plugins of one CSS graph and defines candidates of their dynamic families on demand.
1772
+ *
1773
+ * The runtime records every answer of the graph's load, so {@link PluginRuntime.replay} loads the
1774
+ * same graph again without host I/O, with the definitions that plugins have added since. A
1775
+ * candidate that a plugin leaves undefined is not requested again for the runtime's lifetime.
1776
+ *
1777
+ * Tailwind plugins of the graph share one adapter runtime, which {@link PluginRuntime.initialize}
1778
+ * creates after the first load because their handlers read the complete CSS theme.
1779
+ */
1780
+ var PluginRuntime = class {
1781
+ options;
1782
+ plugins;
1783
+ root;
1784
+ host;
1785
+ watch;
1786
+ previous;
1787
+ settings;
1788
+ /** Plugin statements keyed by importer, specifier, and options text. */
1789
+ #instances = /* @__PURE__ */ new Map();
1790
+ /** Recorded answers keyed by {@link answerKey}. */
1791
+ #answers = /* @__PURE__ */ new Map();
1792
+ /** Requests of the load by importer and request ID, which order the plugin statements. */
1793
+ #requests = /* @__PURE__ */ new Map();
1794
+ /** Root answer, recorded by {@link PluginRuntime.recordRoot}. */
1795
+ #root;
1796
+ /** Candidates already passed to a plugin, including ones it left undefined. */
1797
+ #requested = /* @__PURE__ */ new Set();
1798
+ /** Editor catalogs keyed by input, oldest first. The empty input is never evicted. */
1799
+ #catalogs = /* @__PURE__ */ new Map();
1800
+ /**
1801
+ * Number of {@link PluginRuntime.resolve} calls that added CSS. The loader of the original
1802
+ * load contains the definitions of generation zero.
1803
+ */
1804
+ #generation = 0;
1805
+ /** Runtime of every Tailwind plugin of the graph, which share one config and theme. */
1806
+ #tailwind;
1807
+ /** Loader of the original load, whose source IDs replays share without a session. */
1808
+ #loader;
1809
+ /** Loader for the last queried definition generation. Source usage remains in separate sessions. */
1810
+ #snapshot;
1811
+ /** Tailwind statements in stylesheet order; an index is the statement's owner index. */
1812
+ #tailwindInstances = [];
1813
+ /** Answer to the {@link SETTINGS} request, which the Tailwind runtime generates. */
1814
+ #settingsCss = "";
1815
+ /**
1816
+ * Creates a runtime for one load.
1817
+ *
1818
+ * @param options - Compiler options of the load, reused by {@link PluginRuntime.replay}.
1819
+ * @param plugins - Plugins configured for the project, which take precedence over packages.
1820
+ * @param root - Absolute project directory passed to plugins.
1821
+ * @param host - Loads plugin packages and plugin files, or undefined when the host can only use
1822
+ * configured plugins.
1823
+ * @param watch - Registers files and directories that plugins read.
1824
+ * @param previous - Runtime of an earlier load of the same project. A statement with the same
1825
+ * specifier, options, and plugin resolves the earlier load's candidates of its families again.
1826
+ * @param settings - Project's Tailwind settings. Either field makes the graph use the Tailwind
1827
+ * plugin adapter, as a Tailwind `@plugin` statement does.
1828
+ */
1829
+ constructor(options, plugins, root, host, watch, previous, settings) {
1830
+ this.options = options;
1831
+ this.plugins = plugins;
1832
+ this.root = root;
1833
+ this.host = host;
1834
+ this.watch = watch;
1835
+ this.previous = previous;
1836
+ this.settings = settings;
1837
+ }
1838
+ /** Number of definition batches added after the original load. */
1839
+ get generation() {
1840
+ return this.#generation;
1841
+ }
1842
+ /** Whether project settings or a loaded plugin require the Tailwind adapter. */
1843
+ get tailwind() {
1844
+ return this.settings?.tailwind !== void 0 || this.settings?.important !== void 0 || [...this.#instances.values()].some((instance) => instance.tailwind);
1845
+ }
1846
+ /** Whether any loaded plugin declares a dynamic family. */
1847
+ get dynamic() {
1848
+ return !!this.#tailwind || [...this.#instances.values()].some((instance) => instance.prefixes.length > 0);
1849
+ }
1850
+ /**
1851
+ * Records the root answer of the load.
1852
+ *
1853
+ * @param answer - Root input without its request ID.
1854
+ */
1855
+ recordRoot(answer) {
1856
+ this.#root = answer;
1857
+ }
1858
+ /**
1859
+ * Records the answer to an `@import` request so that a replay can repeat it.
1860
+ *
1861
+ * @param request - Loader request.
1862
+ * @param answer - File input supplied for it, without its request ID.
1863
+ */
1864
+ recordImport(request, answer) {
1865
+ this.#recordRequest(request);
1866
+ this.#answers.set(answerKey(request), answer);
1867
+ }
1868
+ /**
1869
+ * Runs the plugin of an `@plugin` request and returns the answer for it.
1870
+ *
1871
+ * The answer's definitions are the user's own when the host loads the plugin from a
1872
+ * relative or absolute path and `own` is true. Otherwise, they belong to the plugin that the
1873
+ * specifier names, including a plugin configured for the project.
1874
+ *
1875
+ * @param request - Loader request whose `pluginOptions` is set.
1876
+ * @param own - Whether the stylesheet that contains the statement is the user's own CSS.
1877
+ * @returns File input without its request ID. Its name identifies the specifier and options.
1878
+ * @throws If no plugin has the specifier's name and the host cannot load it, or the plugin fails.
1879
+ */
1880
+ async answerPlugin(request, own = false) {
1881
+ this.#recordRequest(request);
1882
+ const key = instanceKey(request);
1883
+ let instance = this.#instances.get(key);
1884
+ if (!instance) {
1885
+ const configured = this.plugins.find((candidate) => candidate.name === request.specifier);
1886
+ const plugin = configured ?? await this.host?.load(request.specifier, request.importer, this.watch);
1887
+ if (!plugin) throw new Error(`Stillwind plugin ${request.specifier} is not configured, and this host cannot load packages`);
1888
+ const context = {
1889
+ options: Object.fromEntries((request.pluginOptions ?? []).map((option) => [option.name, option.value])),
1890
+ root: this.root,
1891
+ watch: this.watch,
1892
+ resolve: async (specifier) => this.host?.resolve(specifier, request.importer),
1893
+ read: async (path) => {
1894
+ if (!this.host) throw new Error(`This host cannot read plugin files: ${path}`);
1895
+ return this.host.read(path);
1896
+ },
1897
+ list: async (path) => {
1898
+ if (!this.host?.list) throw new Error(`This host cannot list plugin directories: ${path}`);
1899
+ return this.host.list(path);
1900
+ }
1901
+ };
1902
+ const css = nativePlugin(plugin) ? await plugin.css(context) : "";
1903
+ const prefixes = [...css.matchAll(DYNAMIC)].map((match) => match[1]);
1904
+ const previous = this.previous ? this.previous.#instances.get(key) : void 0;
1905
+ const candidates = previous?.plugin === plugin && nativePlugin(plugin) && plugin.resolve ? previous.candidates.filter((candidate) => prefixes.some((prefix) => candidate.startsWith(prefix))) : [];
1906
+ const resolved = candidates.length && nativePlugin(plugin) ? await plugin.resolve(candidates, context) : "";
1907
+ for (const candidate of candidates) this.#requested.add(candidate);
1908
+ instance = {
1909
+ plugin,
1910
+ context,
1911
+ css,
1912
+ prefixes,
1913
+ candidates,
1914
+ definitions: resolved.trim() ? [resolved] : [],
1915
+ origin: !configured && own && PATH_SPECIFIER.test(request.specifier) ? { kind: "own" } : {
1916
+ kind: "plugin",
1917
+ name: request.specifier
1918
+ },
1919
+ tailwind: nativePlugin(plugin) ? void 0 : (await import("./configuration-MQZe6ufN.js")).configurePlugin(plugin, request.pluginOptions ?? [])
1920
+ };
1921
+ this.#instances.set(key, instance);
1922
+ }
1923
+ const answer = this.#pluginAnswer(key, instance);
1924
+ this.#answers.set(answerKey(request), answer);
1925
+ return answer;
1926
+ }
1927
+ /**
1928
+ * Evaluates Tailwind handlers with the complete CSS theme, then resolves the candidates of
1929
+ * dynamic families that the graph's CSS applies with `@apply` and `@variant`.
1930
+ *
1931
+ * Tailwind handlers run after the first load because their `theme()` calls read the complete
1932
+ * CSS theme. Their output then needs one more load of the recorded graph. Dynamic candidates in
1933
+ * the graph's CSS need one more load when a plugin defines any of them, with or without
1934
+ * Tailwind. Canonical queries prepare spelling indexes on demand.
1935
+ *
1936
+ * Each later load requests the Tailwind settings after the root stylesheet, as
1937
+ * {@link TailwindRuntime.settingsCss} describes.
1938
+ *
1939
+ * @param loader - Loader of the completed original load. With Tailwind plugins or settings, it
1940
+ * can skip its canonical spelling index, as {@link PluginRuntime.tailwind} allows.
1941
+ * @returns `loader` when no plugin adds CSS, and otherwise a loader with the added CSS.
1942
+ * @throws If the Tailwind configuration is rejected or invalid, a plugin, a handler, or a
1943
+ * callback fails, or the native loader rejects the generated CSS.
1944
+ */
1945
+ async initialize(loader) {
1946
+ this.#loader = loader;
1947
+ const instances = this.#orderedInstances().filter((instance) => instance.tailwind);
1948
+ const project = await this.#projectConfig();
1949
+ let current = loader;
1950
+ if (instances.length || project) {
1951
+ this.#tailwindInstances = instances;
1952
+ const { TailwindRuntime } = await import("./plugin-CNOsrkrd.js");
1953
+ const editor = loader.editorQuery();
1954
+ this.#tailwind = new TailwindRuntime(instances.map((instance) => instance.tailwind), editor.themeTokens(), editor.legacyThemeKeys(), project);
1955
+ if (this.previous) await this.resolve(this.previous.#requested);
1956
+ this.#updateTailwindCss();
1957
+ current = this.replay(void 0, true);
1958
+ }
1959
+ if (!this.dynamic) {
1960
+ this.#snapshot = {
1961
+ generation: this.#generation,
1962
+ loader: current
1963
+ };
1964
+ return current;
1965
+ }
1966
+ const query = current.editorQuery();
1967
+ const sources = [this.#root?.content ?? "", ...[...this.#answers.values()].map((a) => a.content)];
1968
+ if (await this.resolve(sources.flatMap((css) => query.stylesheetDynamicCandidates(css)))) current = this.replay(void 0, true);
1969
+ this.#snapshot = {
1970
+ generation: this.#generation,
1971
+ loader: current
1778
1972
  };
1779
- advance(initial);
1780
- });
1781
- return {
1782
- loader: await plugins.initialize(loader),
1783
- resources: completion?.resources ?? [],
1784
- lintSources: completion?.lintSources ?? [],
1785
- skipped: completion?.skipped ?? [],
1786
- plugins
1787
- };
1788
- }
1789
- // src/editor/candidates.ts
1790
- /**
1791
- * Shares previews, batch ordering, completion catalogs, and summaries for one captured design system.
1792
- */
1793
- var CandidateQueries = class {
1794
- /** Native query pinned to the design system used for candidate validation and previews. */
1795
- #query;
1796
- /** Successful and failed CSS previews keyed by preview kind, input role, and decoded candidate. */
1797
- #previews = /* @__PURE__ */ new Map();
1798
- /** Shared completion arrays keyed by input role, decoded prefix, and snippet support. */
1799
- #completions = /* @__PURE__ */ new Map();
1800
- /** Added marker classes and null results keyed by input role and decoded candidate. */
1801
- #markers = /* @__PURE__ */ new Map();
1802
- /** Summaries and empty results keyed by the full generated CSS, including preview annotations. */
1803
- #details = /* @__PURE__ */ new Map();
1973
+ return current;
1974
+ }
1804
1975
  /**
1805
- * Creates empty caches for one captured design system.
1976
+ * Loads the runtime's current CSS definitions once per definition generation.
1806
1977
  *
1807
- * @param query - Native query whose theme, utility definitions, and compiler settings supply
1808
- * all results. A different design system requires a new instance.
1978
+ * @returns The shared loader for editor queries. Do not add CSS or session usage to it.
1979
+ * @throws If the native loader rejects the plugin definitions.
1809
1980
  */
1810
- constructor(query) {
1811
- this.#query = query;
1981
+ snapshot() {
1982
+ if (this.#snapshot?.generation !== this.#generation) this.#snapshot = {
1983
+ generation: this.#generation,
1984
+ loader: this.replay(void 0, true)
1985
+ };
1986
+ return this.#snapshot.loader;
1812
1987
  }
1813
1988
  /**
1814
- * Caches standalone CSS for one candidate and its input role, including failed resolution.
1815
- * Ordinary utilities use `&` as their subject. Previews omit enclosing source conditions.
1989
+ * Resolves one editor candidate in a separate loader without changing a session's used CSS.
1816
1990
  *
1817
- * @param candidate - Decoded candidate text, including any variants supplied by the caller.
1818
- * Option roles also accept the option text supported by their registry.
1819
- * @param context - Input role used for validation and emission. Defaults to ordinary utilities.
1820
- * @returns CSS for valid input, or null when the native query cannot emit it.
1821
- * @throws If a matching ordinary utility definition has a malformed requirement.
1991
+ * @param candidate - Candidate as an editor offers it, such as `probe-4` or `state-open:`.
1992
+ * @returns Queries over the shared loader containing the candidate's definitions.
1993
+ * @throws If a plugin fails or the native loader rejects the generated CSS.
1822
1994
  */
1823
- preview(candidate, context = "utility") {
1824
- const key = `${context}\0${candidate}`;
1825
- if (!this.#previews.has(key)) this.#previews.set(key, this.#query.previewCandidate(candidate, context));
1826
- return this.#previews.get(key);
1995
+ async query(candidate) {
1996
+ const query = this.snapshot().editorQuery();
1997
+ return await this.resolve(query.dynamicCandidates(candidate)) ? this.snapshot().editorQuery() : query;
1827
1998
  }
1828
1999
  /**
1829
- * Caches the marker class that one candidate adds to the element as written.
2000
+ * Passes new candidates to the plugins that declare their families.
1830
2001
  *
1831
- * @param candidate - Decoded candidate text, including enclosing variants.
1832
- * @param context - Input role of the candidate. Only ordinary utilities add marker classes.
1833
- * @returns The class and its origins, or null when the candidate adds no marker class.
1834
- * Ref conditions of an enclosing style object are not checked.
2002
+ * @param candidates - Compiler requests for native utility names, complete Tailwind utility
2003
+ * keys, or variant names with an `@variant ` prefix. Previously requested keys are skipped.
2004
+ * @returns Whether any plugin returned CSS, so that the design system must be loaded again.
2005
+ * @throws If a plugin fails.
1835
2006
  */
1836
- marker(candidate, context = "utility") {
1837
- const key = `${context}\0${candidate}`;
1838
- if (!this.#markers.has(key)) this.#markers.set(key, this.#query.addedMarker(candidate, context));
1839
- return this.#markers.get(key);
2007
+ async resolve(candidates) {
2008
+ const pending = /* @__PURE__ */ new Map();
2009
+ const tailwind = [];
2010
+ for (const candidate of candidates) {
2011
+ if (this.#requested.has(candidate)) continue;
2012
+ this.#requested.add(candidate);
2013
+ if (this.#tailwind?.accepts(candidate)) tailwind.push(candidate);
2014
+ for (const instance of this.#instances.values()) if (nativePlugin(instance.plugin) && instance.plugin.resolve && instance.prefixes.some((prefix) => candidate.startsWith(prefix))) {
2015
+ pending.set(instance, [...pending.get(instance) ?? [], candidate]);
2016
+ break;
2017
+ }
2018
+ }
2019
+ let changed = this.#tailwind?.resolve(tailwind) ?? false;
2020
+ if (changed) this.#updateTailwindCss();
2021
+ for (const [instance, names] of pending) {
2022
+ instance.candidates.push(...names);
2023
+ const css = nativePlugin(instance.plugin) ? await instance.plugin.resolve(names, instance.context) : "";
2024
+ if (css.trim()) {
2025
+ instance.definitions.push(css);
2026
+ changed = true;
2027
+ }
2028
+ }
2029
+ if (changed) this.#generation++;
2030
+ return changed;
1840
2031
  }
1841
2032
  /**
1842
- * Caches the selectors, at-rule conditions, and declarations of a variant chain.
2033
+ * Lists the candidates that editors complete for the loaded dynamic families.
1843
2034
  *
1844
- * @param candidate - Decoded variant chain, with or without a trailing colon.
1845
- * @param context - Original input role whose constraints must allow the entire chain.
1846
- * @returns CSS introduced by the variants, or null when the chain or role is unsupported.
1847
- * Utility output and surrounding source conditions are omitted.
2035
+ * @param input - Utility text before an editor's cursor, without variants, or an empty string
2036
+ * for the candidates that editors always offer.
2037
+ * @returns Candidate names that start with `input`, from every plugin with a catalog, sorted
2038
+ * and deduplicated. Names that end with `-` are incomplete. The runtime keeps the answers for
2039
+ * the empty input and for the {@link CATALOG_INPUTS} most recent other inputs.
1848
2040
  */
1849
- variant(candidate, context) {
1850
- const key = `variant\0${context}\0${candidate}`;
1851
- if (!this.#previews.has(key)) this.#previews.set(key, this.#query.previewVariant(candidate, context));
1852
- return this.#previews.get(key);
2041
+ catalog(input = "") {
2042
+ let names = this.#catalogs.get(input);
2043
+ if (names) this.#catalogs.delete(input);
2044
+ else names = Promise.all([...this.#instances.values()].map(async (instance) => nativePlugin(instance.plugin) && instance.plugin.catalog ? await instance.plugin.catalog(instance.context, input) : [])).then((lists) => [.../* @__PURE__ */ new Set([...lists.flat(), ...this.#tailwind?.catalog() ?? []])].filter((name) => name.startsWith(input)).sort());
2045
+ this.#catalogs.set(input, names);
2046
+ for (const key of this.#catalogs.keys()) {
2047
+ if (this.#catalogs.size <= 17) break;
2048
+ if (key) this.#catalogs.delete(key);
2049
+ }
2050
+ return names;
1853
2051
  }
1854
2052
  /**
1855
- * Compares two ordinary utility candidates using the compiler's variant and utility order.
2053
+ * Loads the recorded graph again into a loader of `session`, with the current definitions.
1856
2054
  *
1857
- * @param left - Full decoded candidate spelling, including its variants.
1858
- * @param right - Full decoded candidate spelling, including its variants.
1859
- * @returns -1, 0, or 1, or null when either candidate cannot resolve.
1860
- * @throws If a matching utility definition has a malformed requirement.
2055
+ * @param session - Session whose source IDs the new loader shares. Omission shares the
2056
+ * original loader's source IDs.
2057
+ * @param intermediate - Skips preparing the canonical spelling index for a loader that only
2058
+ * serves a later load or a short query. Canonical queries still prepare it on first use.
2059
+ * @returns A complete loader with the load's compiler options, for
2060
+ * {@link NativeProjectSession.reload}.
2061
+ * @throws If the recorded graph is incomplete or the native loader rejects it.
1861
2062
  */
1862
- compare(left, right) {
1863
- return this.#query.compareCandidates(left, right);
2063
+ replay(session, intermediate = false) {
2064
+ if (!this.#root) throw new Error("Stillwind plugin runtime has no recorded CSS graph");
2065
+ const loader = session ? session.newLoader(this.options) : this.#loader?.newLoader(this.options) ?? new NativeDesignSystemLoader(this.options);
2066
+ if (intermediate) loader.deferCanonicalIndex();
2067
+ if (this.#tailwind) loader.requestTrailingPlugin(SETTINGS);
2068
+ let step = loader.provide(0, this.#root.name, this.#root.content, this.#root.uri, this.#root.sourceMapSource, this.#root.lint);
2069
+ while (step.kind !== "complete") step = loader.provideMany(step.requests.map((request) => {
2070
+ if (this.#tailwind && request.specifier === SETTINGS && request.pluginOptions !== void 0) return {
2071
+ id: request.id,
2072
+ name: `stillwind-plugin:${SETTINGS.slice(1)}#${this.#generation}`,
2073
+ content: this.#settingsCss
2074
+ };
2075
+ const instance = request.pluginOptions !== void 0 ? this.#instances.get(instanceKey(request)) : void 0;
2076
+ const answer = instance ? this.#pluginAnswer(instanceKey(request), instance) : this.#answers.get(answerKey(request));
2077
+ if (!answer) throw new Error(`Stillwind plugin runtime has no answer for ${request.specifier}`);
2078
+ return {
2079
+ id: request.id,
2080
+ ...answer
2081
+ };
2082
+ }));
2083
+ return loader;
1864
2084
  }
1865
2085
  /**
1866
- * Prepares all spellings in `values` with one native request.
1867
- * Repeated spellings are resolved once. The input array remains unchanged.
2086
+ * Returns the answer to a plugin request with the instance's current definitions.
1868
2087
  *
1869
- * @param values - Full decoded ordinary utility candidates, including their variants.
1870
- * @returns A comparator whose numeric rank differences belong only to this batch.
1871
- * It returns null for unresolved candidates or spellings absent from `values`.
1872
- * An empty batch returns a comparator that always returns null.
1873
- * @throws If a matching utility requirement is malformed or a native rank exceeds uint32.
2088
+ * @param key - Importer, specifier, and options text of the instance.
2089
+ * @param instance - Loaded plugin statement.
2090
+ * @returns An internal buffer whose name changes with its content.
1874
2091
  */
1875
- order(values) {
1876
- const unique = [...new Set(values)];
1877
- if (unique.length === 0) return () => null;
1878
- const ranks = this.#query.candidateRanks(unique);
1879
- const positions = new Map(unique.map((value, index) => [value, ranks[index]]));
1880
- return (left, right) => {
1881
- const a = positions.get(left);
1882
- const b = positions.get(right);
1883
- return a == null || b == null ? null : a - b;
2092
+ #pluginAnswer(key, instance) {
2093
+ return {
2094
+ name: `stillwind-plugin:${key.replaceAll("\0", "#")}#${this.#generation}#${instance.definitions.length}`,
2095
+ content: [instance.css, ...instance.definitions].join("\n"),
2096
+ origin: instance.origin
1884
2097
  };
1885
2098
  }
1886
2099
  /**
1887
- * Caches unique labels in lexical order for one decoded partial candidate and its role.
1888
- * Existing variant prefixes remain present, and variant labels end in `:`.
1889
- * Suggestions do not append a variant already present in the prefix. An ordinary utility
1890
- * prefix without variants, `!`, or `-` also receives marker class names, which may have no
1891
- * preview.
1892
- *
1893
- * @param prefix - Decoded partial candidate, including any enclosing variants.
1894
- * @param context - Input role that selects the candidate registry and permitted variants.
1895
- * Defaults to ordinary utilities.
1896
- * @param snippets - Whether to include empty brackets for arbitrary variant values and `name/`
1897
- * labels for modifiable markers. Defaults to false.
1898
- * @returns A shared readonly array of matching labels.
1899
- * @throws If a matching ordinary utility definition has a malformed requirement.
2100
+ * Stores the generated CSS of each Tailwind statement and of the settings as their answers.
1900
2101
  */
1901
- complete(prefix, context = "utility", snippets = false) {
1902
- const key = `${context}\0${prefix}\0${snippets}`;
1903
- if (!this.#completions.has(key)) this.#completions.set(key, this.#query.completeCandidate(prefix, context, snippets));
1904
- return this.#completions.get(key);
2102
+ #updateTailwindCss() {
2103
+ for (const [owner, instance] of this.#tailwindInstances.entries()) instance.css = this.#tailwind.css(owner);
2104
+ this.#settingsCss = this.#tailwind.settingsCss();
1905
2105
  }
1906
2106
  /**
1907
- * Caches a short declaration or rule summary for selected completion CSS.
2107
+ * Awaits the project's Tailwind configuration and applies its `important` field.
1908
2108
  *
1909
- * @param css - Generated CSS to summarize, including optional preview annotations.
1910
- * @returns A summary of at most 160 Unicode code points, or undefined when the CSS has
1911
- * no declarations or descriptive rule wrappers.
2109
+ * @returns The configuration with `important` applied, or undefined without settings.
2110
+ * @throws If the configuration promise rejects, its value is not an object, or both the field
2111
+ * and the configuration set `important`.
1912
2112
  */
1913
- detail(css) {
1914
- if (!this.#details.has(css)) this.#details.set(css, completionDetail(css) ?? void 0);
1915
- return this.#details.get(css);
2113
+ async #projectConfig() {
2114
+ const { important } = this.settings ?? {};
2115
+ const tailwind = await this.settings?.tailwind;
2116
+ if (tailwind === void 0) return important === void 0 ? void 0 : { important };
2117
+ if (typeof tailwind !== "object" || tailwind === null || Array.isArray(tailwind)) throw new Error("Stillwind config tailwind must resolve to a Tailwind configuration object");
2118
+ const config = tailwind;
2119
+ if (important === void 0) return config;
2120
+ if (config.important !== void 0) throw new Error("Stillwind config important must not be set together with tailwind.important");
2121
+ return {
2122
+ ...config,
2123
+ important
2124
+ };
1916
2125
  }
1917
2126
  /**
1918
- * Resolves a color utility's concrete color against this query's theme.
2127
+ * Records a request of the load, which orders the plugin statements.
1919
2128
  *
1920
- * @param candidate - Full decoded ordinary utility candidate, including variants and modifiers.
1921
- * @returns sRGB red, green, blue, and effective alpha components in 0..1, or undefined when
1922
- * the candidate is not a color utility or has no unambiguous concrete color.
1923
- * @throws If a matching utility definition has a malformed requirement.
1924
- */
1925
- color(candidate) {
1926
- return this.#query.candidateColor(candidate) ?? void 0;
2129
+ * @param request - Import or plugin request.
2130
+ */
2131
+ #recordRequest(request) {
2132
+ let requests = this.#requests.get(request.importer);
2133
+ if (!requests) this.#requests.set(request.importer, requests = /* @__PURE__ */ new Map());
2134
+ requests.set(request.id, request);
1927
2135
  }
1928
2136
  /**
1929
- * Resolves a color utility's concrete colors in both color schemes against this query's theme.
2137
+ * Orders the plugin statements as the import-expanded stylesheet does.
1930
2138
  *
1931
- * @param candidate - Full decoded ordinary utility candidate, including variants and modifiers.
1932
- * @returns One color without a scheme, a light color followed by a dark color when
1933
- * `light-dark()` selects different colors, or an empty array when the candidate is not a color
1934
- * utility or has no unambiguous concrete color in either scheme.
1935
- * @throws If a matching utility definition has a malformed requirement.
2139
+ * @returns Each statement once, depth first from the root in request order.
1936
2140
  */
1937
- colors(candidate) {
1938
- return this.#query.candidateColors(candidate);
2141
+ #orderedInstances() {
2142
+ const result = /* @__PURE__ */ new Set();
2143
+ const visited = /* @__PURE__ */ new Set();
2144
+ /**
2145
+ * Adds the statements of one stylesheet and of the stylesheets it imports.
2146
+ *
2147
+ * @param name - Recorded identity of the stylesheet.
2148
+ */
2149
+ const visit = (name) => {
2150
+ if (visited.has(name)) return;
2151
+ visited.add(name);
2152
+ for (const request of [...this.#requests.get(name)?.values() ?? []].sort((a, b) => a.id - b.id)) {
2153
+ const instance = this.#instances.get(instanceKey(request));
2154
+ if (request.pluginOptions !== void 0 && instance) result.add(instance);
2155
+ else {
2156
+ const answer = this.#answers.get(answerKey(request));
2157
+ if (answer) visit(answer.name);
2158
+ }
2159
+ }
2160
+ };
2161
+ if (this.#root) visit(this.#root.name);
2162
+ return [...result];
1939
2163
  }
1940
2164
  };
2165
+ // src/css/css.ts
1941
2166
  /**
1942
- * Splits at delimiters outside brackets, parentheses, single or double quotes, and escapes.
1943
- * The operation preserves source spelling and does not validate nesting syntax.
1944
- *
1945
- * @param text - Candidate text whose backslashes escape the following UTF-16 code unit.
1946
- * @param delimiter - One UTF-16 code unit, such as `:` or `/`, that is not a bracket,
1947
- * parenthesis, quote, or backslash.
1948
- * @returns Segments in their original order, including empty segments. Nothing is trimmed
1949
- * or unescaped, and an empty input returns one empty segment.
1950
- */
1951
- function segments(text, delimiter) {
1952
- const result = [];
1953
- let start = 0;
1954
- let depth = 0;
1955
- let quote = "";
1956
- let escaped = false;
1957
- for (let index = 0; index < text.length; index++) {
1958
- const character = text[index];
1959
- if (escaped) {
1960
- escaped = false;
1961
- continue;
1962
- }
1963
- if (character === "\\") {
1964
- escaped = true;
1965
- continue;
1966
- }
1967
- if (quote) {
1968
- if (character === quote) quote = "";
1969
- continue;
1970
- }
1971
- if (character === "'" || character === "\"") quote = character;
1972
- else if (character === "[" || character === "(") depth++;
1973
- else if (character === "]" || character === ")") depth--;
1974
- else if (character === delimiter && depth === 0) {
1975
- result.push(text.slice(start, index));
1976
- start = index + 1;
1977
- }
1978
- }
1979
- result.push(text.slice(start));
1980
- return result;
1981
- }
1982
- /**
1983
- * Describes an added marker class and the definitions that make it a marker.
1984
- *
1985
- * @param marker - Marker class returned by {@link CandidateQueries.marker}.
1986
- * @returns Markdown with the class name first, followed by one line for each kind of origin.
1987
- */
1988
- function markerDocumentation(marker) {
1989
- const code = (text) => {
1990
- const ticks = "`".repeat(Math.max(0, ...[...text.matchAll(/`+/g)].map((match) => match[0].length)) + 1);
1991
- return `${ticks}${text.startsWith("`") || text.endsWith("`") ? ` ${text} ` : text}${ticks}`;
1992
- };
1993
- const definitions = marker.origins.flatMap((origin) => origin.kind === "utility" || origin.kind === "variant" ? [`the ${code(origin.name)} ${origin.kind}`] : []);
1994
- const kinds = new Set(marker.origins.map((origin) => origin.kind));
1995
- return [
1996
- `Adds the marker class ${code(marker.class)} to the element as written.`,
1997
- kinds.has("declared") ? "A `@stillwind-marker` statement declares this class." : void 0,
1998
- definitions.length ? `Selectors in ${list(definitions)} select this class.` : void 0,
1999
- kinds.has("source") ? "Selectors in plugin CSS select this class." : void 0
2000
- ].filter(Boolean).join("\n\n");
2001
- }
2002
- /**
2003
- * Joins phrases into an English list.
2167
+ * Checks whether an identity names a stylesheet.
2004
2168
  *
2005
- * @param items - At least one phrase, in display order.
2006
- * @returns The phrases separated by commas, with "and" before the last one.
2169
+ * @param id - Resolver identity or file path.
2170
+ * @returns Whether the complete identity ends in `.css`, ignoring case. The check includes any
2171
+ * query suffix.
2007
2172
  */
2008
- function list(items) {
2009
- return items.length < 3 ? items.join(" and ") : `${items.slice(0, -1).join(", ")}, and ${items.at(-1)}`;
2173
+ function isStylesheet(id) {
2174
+ return /\.css$/i.test(id);
2010
2175
  }
2011
- // src/editor/design-system.ts
2012
2176
  /**
2013
- * Tests whether a target contains a wildcard outside brackets and parentheses.
2177
+ * Loads original CSS, then retries with recovered definitions if that load fails.
2014
2178
  *
2015
- * @param target - Decoded target text.
2016
- * @returns Whether the target is a pattern.
2179
+ * @param root - Resolved CSS entrypoint.
2180
+ * @param options - Compiler policies used by semantic queries.
2181
+ * @param host - Resolver and reads of the captured original buffers.
2182
+ * @param pluginInputs - Plugins for `@plugin` statements, as {@link loadCssGraph} describes.
2183
+ * @returns A query graph and whether its sources were recovered. Original buffers remain unchanged.
2184
+ * The recovered graph must only supply editor queries, because its text omits authored rules.
2185
+ * @throws If both loads fail, including unresolved imports or unreadable files.
2017
2186
  */
2018
- function isPattern(target) {
2019
- return segments(target, "*").length > 1;
2187
+ async function loadEditorCssGraph(root, options, host, pluginInputs) {
2188
+ try {
2189
+ return {
2190
+ ...await loadCssGraph(root, options, host, void 0, void 0, pluginInputs),
2191
+ recovered: false
2192
+ };
2193
+ } catch {
2194
+ return {
2195
+ ...await loadCssGraph(root, options, {
2196
+ ...host,
2197
+ read: async (id) => editorCssSource(await host.read(id))
2198
+ }, void 0, void 0, pluginInputs),
2199
+ recovered: true
2200
+ };
2201
+ }
2020
2202
  }
2021
2203
  /**
2022
- * Compiles a target whose `*` matches any text, including `/` and `:`.
2204
+ * Selects the user's own CSS for stylesheet lint. The root is linted unless it lies under
2205
+ * `node_modules`. An import is linted when lint checks its importer, its specifier is a relative
2206
+ * or absolute path, and its file does not lie under `node_modules`. A package specifier such as
2207
+ * `stillwind` or `tailwindcss` therefore excludes the package and everything it imports, even when
2208
+ * the package resolves outside `node_modules`.
2023
2209
  *
2024
- * @param target - Decoded pattern.
2025
- * @returns An anchored expression.
2210
+ * @param id - Resolved CSS file identity.
2211
+ * @param importer - Importing file and its lint mark, or undefined for the root.
2212
+ * @param specifier - Import request text, or undefined for the root.
2213
+ * @returns Whether stylesheet lint checks the file.
2026
2214
  */
2027
- function patternExpression(target) {
2028
- const parts = segments(target, "*").map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
2029
- return new RegExp(`^${parts.join(".*")}$`, "s");
2215
+ function lintsStylesheet(id, importer, specifier) {
2216
+ if (/[\\/]node_modules[\\/]/.test(id)) return false;
2217
+ return !importer || importer.lint && specifier !== void 0 && PATH_SPECIFIER.test(specifier);
2030
2218
  }
2031
2219
  /**
2032
- * Answers a theme request.
2220
+ * Names the package that supplies an imported stylesheet that is not the user's own CSS.
2033
2221
  *
2034
- * @param context - Loaded design system.
2035
- * @param request - Theme request.
2036
- * @returns Tokens that match, or every token for an empty target list, and unmatched targets.
2037
- */
2038
- function theme(context, request) {
2039
- const tokens = context.query.themeTokens().map(({ name, value, fallback, inline }) => ({
2040
- name,
2041
- value,
2042
- source: fallback ? "default" : "project",
2043
- inline
2044
- })).filter(({ source }) => !request.source || source === request.source);
2045
- const targets = request.targets.map((target) => ({
2046
- target,
2047
- expression: patternExpression(`--${target.replace(/^--/, "")}`)
2048
- }));
2049
- return {
2050
- tokens: targets.length ? tokens.filter(({ name }) => targets.some(({ expression }) => expression.test(name))) : tokens,
2051
- candidates: [],
2052
- unmatched: targets.filter(({ expression }) => !tokens.some(({ name }) => expression.test(name))).map(({ target }) => target)
2053
- };
2054
- }
2055
- /**
2056
- * Describes one candidate.
2222
+ * A package specifier, such as `stillwind` or `@scope/name/theme.css`, names its package. A path
2223
+ * specifier keeps the package of its importer, so a package's relative imports stay in the
2224
+ * package. Otherwise, the last `node_modules` directory in `id` names the package.
2057
2225
  *
2058
- * @param query - Query that contains the definitions of the plugin candidates in the request.
2059
- * @param candidates - Preview cache over that query.
2060
- * @param annotations - Preview comment settings.
2061
- * @param name - Decoded candidate, or a variant name without its trailing colon.
2062
- * @param kind - Selects utility or variant resolution.
2063
- * @returns The candidate, with a suggestion when it is invalid.
2064
- * @throws If a matching utility definition is malformed.
2226
+ * @param id - Resolved CSS file identity.
2227
+ * @param specifier - Import request text.
2228
+ * @param importerPackage - Package of the importing file, or undefined when it has none.
2229
+ * @returns The package name, or undefined when none of these rules names one.
2065
2230
  */
2066
- function describe(query, candidates, annotations, name, kind) {
2067
- const css = kind === "variants" ? candidates.variant(name, "utility") : candidates.preview(name);
2068
- const marker = kind === "utilities" ? candidates.marker(name) : null;
2069
- if (css || marker) return {
2070
- name,
2071
- kind: kind === "variants" ? "variant" : marker ? "marker" : "utility",
2072
- valid: true,
2073
- css: css ? query.formatCss(css, annotations) : ""
2074
- };
2075
- const suggestion = kind === "variants" ? query.suggestCandidate(`${name}:flex`)?.replace(/:flex$/, "") : query.suggestCandidate(name);
2076
- return {
2077
- name,
2078
- kind: kind === "variants" ? "variant" : "utility",
2079
- valid: false,
2080
- css: "",
2081
- ...suggestion ? { suggestion } : {}
2082
- };
2231
+ function stylesheetPackage(id, specifier, importerPackage) {
2232
+ if (!PATH_SPECIFIER.test(specifier)) {
2233
+ const [first, second] = specifier.split("/");
2234
+ return first.startsWith("@") && second !== void 0 ? `${first}/${second}` : first;
2235
+ }
2236
+ if (importerPackage !== void 0) return importerPackage;
2237
+ return [...id.matchAll(/[\\/]node_modules[\\/]((?:@[^\\/]+[\\/])?[^\\/]+)/g)].at(-1)?.[1].replace("\\", "/");
2083
2238
  }
2084
2239
  /**
2085
- * Returns the canonical spelling of a valid candidate under the lint options of the project.
2240
+ * Loads a CSS graph and returns the completed native loader and its resource references.
2241
+ * `root` must already be resolved and accepted by the host's read and watch methods.
2242
+ * `options` configures a new loader. If `suppliedLoader` is given, it must not have
2243
+ * received any input yet, and this function uses its existing configuration.
2244
+ * `rootContent` skips reading the root file. The function still watches that file
2245
+ * and all resolved dependencies. Each file is marked for stylesheet lint as `host.lint` decides,
2246
+ * or as {@link lintsStylesheet} decides when the host omits it.
2247
+ * Canonical queries build their indexes on first use.
2086
2248
  *
2087
- * @param query - Query that contains the definitions of the plugin candidates in the request.
2088
- * @param name - Decoded candidate, or a variant name without its trailing colon.
2089
- * @param kind - Selects utility or variant spelling.
2090
- * @returns The spelling, or undefined when `name` has no different canonical spelling.
2091
- * @throws If a matching utility definition is malformed.
2092
- */
2093
- function canonicalSpelling(query, name, kind) {
2094
- return kind === "variants" ? query.canonicalCandidate(`${name}:flex`)?.replace(/:flex$/, "") : query.canonicalCandidate(name) ?? void 0;
2095
- }
2096
- /**
2097
- * Answers a utility or variant request.
2249
+ * Reads run concurrently, and each request ID is read only once. Responses ready
2250
+ * in the same event-loop turn are sent together to reduce native calls. Faster reads
2251
+ * can reveal more imports without waiting for slower reads.
2252
+ * Resolution, read, and native loading errors reject the promise. Reads already
2253
+ * started continue, and files already registered with the watcher stay registered.
2098
2254
  *
2099
- * @param context - Loaded design system.
2100
- * @param request - Candidate request. An empty target list means every listed name.
2101
- * @returns Exact candidates, then the names that match patterns. Patterns read the completion
2102
- * catalog, so they omit numeric and arbitrary values that exact candidates accept.
2103
- * @throws If a plugin fails or a matching utility definition is malformed.
2255
+ * @param root - Resolved CSS entrypoint accepted by the host's read and watch operations.
2256
+ * @param options - Compiler settings used when creating a new loader.
2257
+ * @param host - CSS resolver, reader, source identity operations, and dependency watcher.
2258
+ * @param rootContent - Optional entrypoint text that replaces the initial filesystem read.
2259
+ * @param suppliedLoader - Optional configured loader that has not received any CSS input.
2260
+ * @param pluginInputs - Plugins for `@plugin` statements. Omission uses no configured plugins,
2261
+ * the root's directory as the project directory, and the host's plugin operations.
2262
+ * @returns A promise for the completed native loader and its authored resource references.
2263
+ * @throws If resolving, reading, or loading the CSS graph fails.
2104
2264
  */
2105
- async function candidates(context, request) {
2106
- const { kind } = request;
2107
- const catalog = new CandidateQueries(context.query);
2108
- const targets = request.targets.length ? request.targets : ["*"];
2109
- const exact = targets.filter((target) => !isPattern(target));
2110
- const patterns = [];
2111
- for (const target of targets.filter(isPattern)) {
2112
- const expression = patternExpression(target);
2113
- const prefix = segments(target, "*")[0];
2114
- const names = [...catalog.complete(prefix).map(({ label }) => label), ...await context.plugins?.catalog(prefix) ?? []].flatMap((label) => {
2115
- const variant = label.endsWith(":");
2116
- const name = variant ? label.slice(0, -1) : label;
2117
- return variant === (kind === "variants") && !name.endsWith("-") && expression.test(name) ? [name] : [];
2118
- });
2119
- patterns.push({
2120
- target,
2121
- names: [...new Set(names)].sort()
2122
- });
2123
- }
2124
- const dynamic = [...exact, ...patterns.flatMap(({ names }) => names)].map((name) => kind === "variants" ? `${name}:` : name).filter((text) => context.query.dynamicCandidates(text).length > 0);
2125
- const query = context.plugins && dynamic.length ? await context.plugins.query(dynamic.join(" ")) : context.query;
2126
- const queries = query === context.query ? catalog : new CandidateQueries(query);
2127
- const seen = new Set(exact);
2128
- const listed = [];
2129
- const unmatched = [];
2130
- for (const { target, names } of patterns) {
2131
- let matched = false;
2132
- for (const name of names) {
2133
- if (seen.has(name)) {
2134
- matched = true;
2135
- continue;
2265
+ async function loadCssGraph(root, options, host, rootContent, suppliedLoader, pluginInputs) {
2266
+ const loader = suppliedLoader ?? new NativeDesignSystemLoader(options);
2267
+ loader.deferCanonicalIndex();
2268
+ const plugins = new PluginRuntime(options, pluginInputs?.plugins ?? [], pluginInputs?.root ?? root.replace(/[\\/][^\\/]*$/, ""), host.plugins, (path, kind) => {
2269
+ if (kind === "directory") host.watchDirectory?.(path);
2270
+ else host.watch(path);
2271
+ }, pluginInputs?.previous, pluginInputs && {
2272
+ tailwind: pluginInputs.tailwind,
2273
+ important: pluginInputs.important
2274
+ });
2275
+ host.watch(root);
2276
+ const lints = /* @__PURE__ */ new Map();
2277
+ const packages = /* @__PURE__ */ new Map();
2278
+ const lint = (id, importer, specifier) => host.lint ? host.lint(id, importer, specifier) : lintsStylesheet(id, importer, specifier);
2279
+ lints.set(root, lint(root));
2280
+ const rootAnswer = {
2281
+ name: root,
2282
+ content: rootContent ?? await host.read(root),
2283
+ uri: host.documentUri(root),
2284
+ sourceMapSource: host.sourceMapSource(root),
2285
+ lint: lints.get(root)
2286
+ };
2287
+ plugins.recordRoot(rootAnswer);
2288
+ const initial = loader.provide(0, rootAnswer.name, rootAnswer.content, rootAnswer.uri, rootAnswer.sourceMapSource, rootAnswer.lint);
2289
+ let completion;
2290
+ await new Promise((resolveLoad, rejectLoad) => {
2291
+ const started = /* @__PURE__ */ new Set();
2292
+ let stopped = false;
2293
+ let queued = false;
2294
+ let ready = [];
2295
+ /**
2296
+ * Stops graph advancement and rejects the pending load.
2297
+ *
2298
+ * @param error - Resolution, reading, or native loading failure passed to the caller.
2299
+ */
2300
+ const fail = (error) => {
2301
+ stopped = true;
2302
+ rejectLoad(error);
2303
+ };
2304
+ /**
2305
+ * Completes the graph or starts reads for requests that have not already started.
2306
+ *
2307
+ * @param step - Native loading step. Completion stores resources and resolves the load.
2308
+ */
2309
+ const advance = (step) => {
2310
+ if (step.kind === "complete") {
2311
+ completion = step;
2312
+ stopped = true;
2313
+ resolveLoad();
2314
+ return;
2136
2315
  }
2137
- const candidate = describe(query, queries, context.annotations, name, kind);
2138
- if (candidate.valid) {
2139
- matched = true;
2140
- seen.add(name);
2141
- listed.push(candidate);
2316
+ for (const request of step.requests) {
2317
+ if (started.has(request.id)) continue;
2318
+ started.add(request.id);
2319
+ /**
2320
+ * Resolves, watches, and reads this request, then schedules a batch of ready responses.
2321
+ * An import that the host cannot resolve or read is answered as unresolved.
2322
+ *
2323
+ * @returns A promise that resolves after queuing the response, or after observing a stopped load.
2324
+ * @throws If a plugin fails to load. The attached rejection handler stops the load.
2325
+ */
2326
+ const read = async () => {
2327
+ if (request.pluginOptions !== void 0) {
2328
+ const answer = await plugins.answerPlugin(request, lints.get(request.importer) ?? false);
2329
+ if (plugins.tailwind) loader.deferCanonicalIndex();
2330
+ if (!stopped) {
2331
+ ready.push({
2332
+ id: request.id,
2333
+ ...answer
2334
+ });
2335
+ schedule();
2336
+ }
2337
+ return;
2338
+ }
2339
+ /**
2340
+ * Answers the request as unresolved, so the loader skips the import and stylesheet lint
2341
+ * reports it.
2342
+ */
2343
+ const unresolved = () => {
2344
+ if (stopped) return;
2345
+ const answer = {
2346
+ name: request.specifier,
2347
+ content: "",
2348
+ lint: false,
2349
+ unresolved: true
2350
+ };
2351
+ plugins.recordImport(request, answer);
2352
+ ready.push({
2353
+ id: request.id,
2354
+ ...answer
2355
+ });
2356
+ schedule();
2357
+ };
2358
+ let name;
2359
+ try {
2360
+ name = await host.resolve(request.specifier, request.importer);
2361
+ } catch {
2362
+ unresolved();
2363
+ return;
2364
+ }
2365
+ if (stopped) return;
2366
+ host.watch(name);
2367
+ let content;
2368
+ try {
2369
+ content = await host.read(name);
2370
+ } catch {
2371
+ unresolved();
2372
+ return;
2373
+ }
2374
+ if (stopped) return;
2375
+ const marked = lint(name, {
2376
+ id: request.importer,
2377
+ lint: lints.get(request.importer) ?? false
2378
+ }, request.specifier);
2379
+ lints.set(name, (lints.get(name) ?? false) || marked);
2380
+ const library = marked ? void 0 : stylesheetPackage(name, request.specifier, packages.get(request.importer));
2381
+ if (!marked && !packages.has(name)) packages.set(name, library);
2382
+ const answer = {
2383
+ name,
2384
+ content,
2385
+ uri: host.documentUri(name),
2386
+ sourceMapSource: host.sourceMapSource(name),
2387
+ lint: marked,
2388
+ ...marked ? {} : { origin: {
2389
+ kind: "library",
2390
+ name: library
2391
+ } }
2392
+ };
2393
+ plugins.recordImport(request, answer);
2394
+ ready.push({
2395
+ id: request.id,
2396
+ ...answer
2397
+ });
2398
+ schedule();
2399
+ };
2400
+ read().catch(fail);
2142
2401
  }
2143
- }
2144
- if (!matched) unmatched.push(target);
2145
- }
2402
+ };
2403
+ /** Sends the responses that are ready in the current event-loop turn together. */
2404
+ const schedule = () => {
2405
+ if (!queued) {
2406
+ queued = true;
2407
+ setTimeout(() => {
2408
+ queued = false;
2409
+ const responses = ready;
2410
+ ready = [];
2411
+ if (stopped) return;
2412
+ try {
2413
+ advance(loader.provideMany(responses));
2414
+ } catch (error) {
2415
+ fail(error);
2416
+ }
2417
+ });
2418
+ }
2419
+ };
2420
+ advance(initial);
2421
+ });
2146
2422
  return {
2147
- tokens: [],
2148
- candidates: [...exact.map((name) => {
2149
- const candidate = describe(query, queries, context.annotations, name, kind);
2150
- const canonical = candidate.valid ? canonicalSpelling(query, name, kind) : void 0;
2151
- return canonical ? {
2152
- ...candidate,
2153
- canonical
2154
- } : candidate;
2155
- }), ...listed],
2156
- unmatched
2423
+ loader: await plugins.initialize(loader),
2424
+ resources: completion?.resources ?? [],
2425
+ lintSources: completion?.lintSources ?? [],
2426
+ skipped: completion?.skipped ?? [],
2427
+ plugins
2157
2428
  };
2158
2429
  }
2430
+ // src/editor/candidates.ts
2159
2431
  /**
2160
- * Answers a question about a loaded design system.
2161
- *
2162
- * @param context - Loaded design system.
2163
- * @param request - Theme, utility, or variant request.
2164
- * @returns The answer. Invalid names and unmatched targets are data.
2165
- * @throws If a plugin fails or a matching utility definition is malformed.
2166
- */
2167
- function queryDesignSystem(context, request) {
2168
- return request.kind === "theme" ? Promise.resolve(theme(context, request)) : candidates(context, request);
2169
- }
2170
- // src/compilation/project.ts
2171
- /** Keeps prepared sources and checker inputs between analyses of one project. */
2172
- var CompilationProject = class {
2173
- /** Sources keyed by normalized resolver ID. Windows paths ignore case. */
2174
- #sources = /* @__PURE__ */ new Map();
2175
- /** Import answers for the currently installed checker inputs. */
2176
- #resolutions;
2177
- /** Advances on invalidation so pending loads cannot publish old sources. */
2178
- #revision = 0;
2179
- /** Advances when sources or import links change so checker inputs are installed again. */
2180
- #generation = 0;
2181
- /** Last backend and inputs installed by this project. */
2182
- #installed;
2183
- /** Revision that a pending load must still match before it stores a source. */
2184
- get revision() {
2185
- return this.#revision;
2186
- }
2187
- /**
2188
- * Finds a source prepared since its last invalidation.
2189
- *
2190
- * @param id - Full resolver ID. Windows path spelling may differ in case or slashes.
2191
- * @returns The shared source, or undefined when it has not been prepared. Do not mutate it.
2192
- */
2193
- source(id) {
2194
- return this.#sources.get(sourceKey(id))?.source;
2195
- }
2196
- /** Returns the normalized identities of the prepared sources, as {@link sourceKey} defines them. */
2197
- sourceKeys() {
2198
- return [...this.#sources.keys()];
2199
- }
2200
- /** Returns the prepared documents' original text so plugins can find candidates together. */
2201
- texts() {
2202
- return [...this.#sources.values()].map((record) => record.source.document.code);
2203
- }
2432
+ * Shares previews, batch ordering, completion catalogs, and summaries for one captured design system.
2433
+ */
2434
+ var CandidateQueries = class {
2435
+ /** Native query pinned to the design system used for candidate validation and previews. */
2436
+ #query;
2437
+ /** Successful and failed CSS previews keyed by preview kind, input role, and decoded candidate. */
2438
+ #previews = /* @__PURE__ */ new Map();
2439
+ /** Shared completion arrays keyed by input role, decoded prefix, and snippet support. */
2440
+ #completions = /* @__PURE__ */ new Map();
2441
+ /** Added marker classes and null results keyed by input role and decoded candidate. */
2442
+ #markers = /* @__PURE__ */ new Map();
2443
+ /** Summaries and empty results keyed by the full generated CSS, including preview annotations. */
2444
+ #details = /* @__PURE__ */ new Map();
2204
2445
  /**
2205
- * Finds the scan results for a prepared source.
2446
+ * Creates empty caches for one captured design system.
2206
2447
  *
2207
- * @param source - Source whose text has not changed since preparation.
2208
- * @returns Shared scan results, or undefined when the source is not retained. Do not mutate them.
2448
+ * @param query - Native query whose theme, utility definitions, and compiler settings supply
2449
+ * all results. A different design system requires a new instance.
2209
2450
  */
2210
- summary(source) {
2211
- return this.#sources.get(sourceKey(source.resolverId))?.summary;
2451
+ constructor(query) {
2452
+ this.#query = query;
2212
2453
  }
2213
2454
  /**
2214
- * Stores a source and its successful scan results, copying the source before retaining it.
2455
+ * Caches standalone CSS for one candidate and its input role, including failed resolution.
2456
+ * Ordinary utilities use `&` as their subject. Previews omit enclosing source conditions.
2215
2457
  *
2216
- * @param source - Source passed to the scanner.
2217
- * @param summary - Successful scan results for that source. Do not mutate them after this call.
2218
- * @param revision - Revision captured before loading. Defaults to the current revision.
2219
- * Old revisions and sources already stored under the same ID have no effect.
2458
+ * @param candidate - Decoded candidate text, including any variants supplied by the caller.
2459
+ * Option roles also accept the option text supported by their registry.
2460
+ * @param context - Input role used for validation and emission. Defaults to ordinary utilities.
2461
+ * @returns CSS for valid input, or null when the native query cannot emit it.
2462
+ * @throws If a matching ordinary utility definition has a malformed requirement.
2220
2463
  */
2221
- retain(source, summary, revision = this.#revision) {
2222
- if (revision !== this.#revision || this.#sources.has(sourceKey(source.resolverId))) return;
2223
- source = structuredClone(source);
2224
- this.#sources.set(sourceKey(source.resolverId), {
2225
- source,
2226
- summary,
2227
- linked: false,
2228
- resolutions: []
2229
- });
2230
- this.#changed();
2464
+ preview(candidate, context = "utility") {
2465
+ const key = `${context}\0${candidate}`;
2466
+ if (!this.#previews.has(key)) this.#previews.set(key, this.#query.previewCandidate(candidate, context));
2467
+ return this.#previews.get(key);
2231
2468
  }
2232
2469
  /**
2233
- * Loads and scans targets together, then resolves their imports through the host.
2234
- * Analysis retries failed loads and scans so it can report each target's own error.
2470
+ * Caches the marker class that one candidate adds to the element as written.
2235
2471
  *
2236
- * @param ids - Full resolver IDs of the targets to prepare.
2237
- * @param host - Host used by later analysis of these targets.
2238
- * @param session - Initialized native session that will analyze the prepared sources.
2239
- * @returns Completion of preparation. Invalidation stops old work from storing results.
2240
- * @throws If host import resolution fails. Source loading and scan failures are left for analysis.
2472
+ * @param candidate - Decoded candidate text, including enclosing variants.
2473
+ * @param context - Input role of the candidate. Only ordinary utilities add marker classes.
2474
+ * @returns The class and its origins, or null when the candidate adds no marker class.
2475
+ * Ref conditions of an enclosing style object are not checked.
2241
2476
  */
2242
- async prepare(ids, host, session) {
2243
- const revision = this.#revision;
2244
- await Promise.allSettled(ids.map((id) => this.#load(id, host, session, revision)));
2245
- if (revision !== this.#revision) return;
2246
- for (const record of this.#sources.values()) {
2247
- const { source, summary } = record;
2248
- if (record.linked) continue;
2249
- const resolutions = await Promise.all(summary.moduleSpecifiers.map(async (specifier) => {
2250
- const resolved = await host.resolve(specifier.source, source.resolverId, { skipSelf: true });
2251
- if (!resolved || resolved.external) return;
2252
- await this.#load(resolved.id, host, session, revision).catch(() => {});
2253
- return {
2254
- id: this.source(resolved.id)?.resolverId ?? resolved.id,
2255
- start: specifier.start,
2256
- end: specifier.end
2257
- };
2258
- }));
2259
- if (revision !== this.#revision) return;
2260
- record.linked = true;
2261
- this.#setResolutions(record, resolutions.filter((value) => value !== void 0));
2262
- }
2477
+ marker(candidate, context = "utility") {
2478
+ const key = `${context}\0${candidate}`;
2479
+ if (!this.#markers.has(key)) this.#markers.set(key, this.#query.addedMarker(candidate, context));
2480
+ return this.#markers.get(key);
2263
2481
  }
2264
2482
  /**
2265
- * Removes changed sources and clears all import links and cached resolution answers.
2483
+ * Caches the selectors, at-rule conditions, and declarations of a variant chain.
2266
2484
  *
2267
- * @param ids - One changed resolver ID or several IDs. Omission removes every source.
2268
- * Advances the revision so pending loads cannot restore the removed sources.
2485
+ * @param candidate - Decoded variant chain, with or without a trailing colon.
2486
+ * @param context - Original input role whose constraints must allow the entire chain.
2487
+ * @returns CSS introduced by the variants, or null when the chain or role is unsupported.
2488
+ * Utility output and surrounding source conditions are omitted.
2269
2489
  */
2270
- invalidate(ids) {
2271
- this.#revision++;
2272
- if (ids === void 0) this.#sources.clear();
2273
- else for (const id of typeof ids === "string" ? [ids] : ids) this.#sources.delete(sourceKey(id));
2274
- for (const record of this.#sources.values()) {
2275
- record.resolutions = [];
2276
- if (record.checker) record.checker.resolutions = record.resolutions;
2277
- record.linked = false;
2278
- }
2279
- this.#changed();
2490
+ variant(candidate, context) {
2491
+ const key = `variant\0${context}\0${candidate}`;
2492
+ if (!this.#previews.has(key)) this.#previews.set(key, this.#query.previewVariant(candidate, context));
2493
+ return this.#previews.get(key);
2280
2494
  }
2281
2495
  /**
2282
- * Installs prepared checker inputs when their sources, import links, or supplied files change.
2496
+ * Compares two ordinary utility candidates using the compiler's variant and utility order.
2283
2497
  *
2284
- * @param backend - Backend used by later queries. Receives inputs if it supports setProjectSources.
2285
- * @param sources - Sources requested by the current analysis, with any known import resolutions.
2286
- * @param inputs - File overlays and ambient declarations for these sources.
2287
- * @returns Shared checker sources in the requested order. Do not mutate them.
2288
- * @throws If a requested source's checker environment or backend installation fails.
2289
- * Other sources with unavailable framework dependencies are left out of the installed inputs.
2290
- */
2291
- install(backend, sources, inputs) {
2292
- const requested = sources.map((source) => {
2293
- const record = this.#sources.get(sourceKey(source.resolverId));
2294
- if (!record) return source;
2295
- const checker = this.#checkerSource(record);
2296
- if (!record.linked) {
2297
- const resolutions = new Map(record.resolutions.map((item) => [`${item.start}:${item.end}`, item]));
2298
- for (const item of source.resolutions ?? []) {
2299
- const target = this.source(item.id);
2300
- if (target) resolutions.set(`${item.start}:${item.end}`, {
2301
- ...item,
2302
- id: target.resolverId
2303
- });
2304
- }
2305
- this.#setResolutions(record, [...resolutions.values()]);
2306
- }
2307
- return checker;
2308
- });
2309
- const all = /* @__PURE__ */ new Map();
2310
- for (const [id, record] of this.#sources) try {
2311
- all.set(id, this.#checkerSource(record));
2312
- } catch {}
2313
- for (const source of requested) all.set(sourceKey(source.resolverId), source);
2314
- if (this.#installed?.backend !== backend || this.#installed.generation !== this.#generation || !sameFiles(this.#installed.inputs?.overlayFiles, inputs?.overlayFiles) || !sameFiles(this.#installed.inputs?.ambientDeclarations, inputs?.ambientDeclarations)) {
2315
- const inventory = [...all.values()].sort((a, b) => {
2316
- const left = sourceKey(a.resolverId);
2317
- const right = sourceKey(b.resolverId);
2318
- return left < right ? -1 : left > right ? 1 : 0;
2319
- });
2320
- backend.setProjectSources?.(inventory, this.assets(), inputs);
2321
- this.#installed = {
2322
- backend,
2323
- generation: this.#generation,
2324
- inputs,
2325
- sources: inventory
2326
- };
2327
- this.#resolutions = void 0;
2328
- }
2329
- return requested;
2330
- }
2331
- /**
2332
- * @returns Declarations grouped by module ID. The arrays belong to the retained scans.
2498
+ * @param left - Full decoded candidate spelling, including its variants.
2499
+ * @param right - Full decoded candidate spelling, including its variants.
2500
+ * @returns -1, 0, or 1, or null when either candidate cannot resolve.
2501
+ * @throws If a matching utility definition has a malformed requirement.
2333
2502
  */
2334
- assets() {
2335
- return new Map([...this.#sources.values()].map(({ source, summary }) => [source.moduleId, summary.assets]));
2503
+ compare(left, right) {
2504
+ return this.#query.compareCandidates(left, right);
2336
2505
  }
2337
2506
  /**
2338
- * Resolves imports and caches the answers until checker inputs change.
2507
+ * Prepares all spellings in `values` with one native request.
2508
+ * Repeated spellings are resolved once. The input array remains unchanged.
2339
2509
  *
2340
- * @param backend - Backend that resolves imports. Backends without setProjectSources query only sources.
2341
- * @param sources - Sources requested by the current analysis, with any known import resolutions.
2342
- * @param inputs - File overlays and ambient declarations for this analysis.
2343
- * @returns Shared maps from resolver ID to authored specifier and resolved ID. Do not mutate them.
2344
- * @throws If checker input preparation, installation, or import resolution fails.
2510
+ * @param values - Full decoded ordinary utility candidates, including their variants.
2511
+ * @returns A comparator whose numeric rank differences belong only to this batch.
2512
+ * It returns null for unresolved candidates or spellings absent from `values`.
2513
+ * An empty batch returns a comparator that always returns null.
2514
+ * @throws If a matching utility requirement is malformed or a native rank exceeds uint32.
2345
2515
  */
2346
- async resolve(backend, sources, inputs) {
2347
- if (!backend.setProjectSources) return backend.resolveModules(sources, this.assets(), inputs);
2348
- this.install(backend, sources, inputs);
2349
- if (!this.#resolutions) {
2350
- const generation = this.#generation;
2351
- const resolutions = await backend.resolveModules(this.#installed.sources, this.assets(), inputs);
2352
- if (generation === this.#generation) this.#resolutions = resolutions;
2353
- return resolutions;
2354
- }
2355
- return this.#resolutions;
2516
+ order(values) {
2517
+ const unique = [...new Set(values)];
2518
+ if (unique.length === 0) return () => null;
2519
+ const ranks = this.#query.candidateRanks(unique);
2520
+ const positions = new Map(unique.map((value, index) => [value, ranks[index]]));
2521
+ return (left, right) => {
2522
+ const a = positions.get(left);
2523
+ const b = positions.get(right);
2524
+ return a == null || b == null ? null : a - b;
2525
+ };
2356
2526
  }
2357
2527
  /**
2358
- * Loads and scans one supported source unless it is already prepared.
2528
+ * Caches unique labels in lexical order for one decoded partial candidate and its role.
2529
+ * Existing variant prefixes remain present, and variant labels end in `:`.
2530
+ * Suggestions do not append a variant already present in the prefix. An ordinary utility
2531
+ * prefix without variants, `!`, or `-` also receives marker class names, which may have no
2532
+ * preview.
2359
2533
  *
2360
- * @param id - Full resolver ID.
2361
- * @param host - Source loader and format metadata for this project.
2362
- * @param session - Initialized session used to scan the source.
2363
- * @param revision - Revision captured before loading. A newer revision discards this work.
2364
- * @returns Completion of loading and scanning. Failed scans are not stored.
2365
- * @throws If loading, projection, or native transport fails.
2534
+ * @param prefix - Decoded partial candidate, including any enclosing variants.
2535
+ * @param context - Input role that selects the candidate registry and permitted variants.
2536
+ * Defaults to ordinary utilities.
2537
+ * @param snippets - Whether to include empty brackets for arbitrary variant values and `name/`
2538
+ * labels for modifiable markers. Defaults to false.
2539
+ * @returns A shared readonly array of matching labels.
2540
+ * @throws If a matching ordinary utility definition has a malformed requirement.
2366
2541
  */
2367
- async #load(id, host, session, revision) {
2368
- if (revision !== this.#revision || this.source(id) || host.supports?.(id) === false) return;
2369
- const input = await loadSource(host, id);
2370
- const source = "kind" in input ? input : await prepareSource(input);
2371
- if (revision !== this.#revision) return;
2372
- const scan = session.scanSource(source);
2373
- if (scan.kind !== "failed") this.retain(source, scan.summary, revision);
2542
+ complete(prefix, context = "utility", snippets = false) {
2543
+ const key = `${context}\0${prefix}\0${snippets}`;
2544
+ if (!this.#completions.has(key)) this.#completions.set(key, this.#query.completeCandidate(prefix, context, snippets));
2545
+ return this.#completions.get(key);
2374
2546
  }
2375
2547
  /**
2376
- * Creates a source's checker inputs once, loading any required framework declarations.
2548
+ * Caches a short declaration or rule summary for selected completion CSS.
2377
2549
  *
2378
- * @param record - Retained source and scan results to update.
2379
- * @returns Shared checker inputs. Later import updates also update this object.
2380
- * @throws If the framework checker environment cannot be prepared.
2550
+ * @param css - Generated CSS to summarize, including optional preview annotations.
2551
+ * @returns A summary of at most 160 Unicode code points, or undefined when the CSS has
2552
+ * no declarations or descriptive rule wrappers.
2381
2553
  */
2382
- #checkerSource(record) {
2383
- return record.checker ??= {
2384
- ...record.source,
2385
- ...checkerEnvironment(record.source),
2386
- probes: record.summary.typeProbes,
2387
- checkerSpans: record.summary.checkerSpans,
2388
- checkerBindings: record.summary.checkerBindings,
2389
- resolutions: record.resolutions
2390
- };
2554
+ detail(css) {
2555
+ if (!this.#details.has(css)) this.#details.set(css, completionDetail(css) ?? void 0);
2556
+ return this.#details.get(css);
2391
2557
  }
2392
2558
  /**
2393
- * Replaces import links and clears cached answers when a target or range changes.
2559
+ * Resolves a color utility's concrete color against this query's theme.
2394
2560
  *
2395
- * @param record - Retained source whose links are being replaced.
2396
- * @param resolutions - Resolved targets with original UTF-8 byte ranges.
2561
+ * @param candidate - Full decoded ordinary utility candidate, including variants and modifiers.
2562
+ * @returns sRGB red, green, blue, and effective alpha components in 0..1, or undefined when
2563
+ * the candidate is not a color utility or has no unambiguous concrete color.
2564
+ * @throws If a matching utility definition has a malformed requirement.
2397
2565
  */
2398
- #setResolutions(record, resolutions) {
2399
- if (record.resolutions.length === resolutions.length && record.resolutions.every((item, index) => item.id === resolutions[index].id && item.start === resolutions[index].start && item.end === resolutions[index].end)) return;
2400
- record.resolutions = resolutions;
2401
- if (record.checker) record.checker.resolutions = resolutions;
2402
- this.#changed();
2566
+ color(candidate) {
2567
+ return this.#query.candidateColor(candidate) ?? void 0;
2403
2568
  }
2404
2569
  /**
2405
- * Clears import answers and marks checker inputs for installation on the next query.
2570
+ * Resolves a color utility's concrete colors in both color schemes against this query's theme.
2571
+ *
2572
+ * @param candidate - Full decoded ordinary utility candidate, including variants and modifiers.
2573
+ * @returns One color without a scheme, a light color followed by a dark color when
2574
+ * `light-dark()` selects different colors, or an empty array when the candidate is not a color
2575
+ * utility or has no unambiguous concrete color in either scheme.
2576
+ * @throws If a matching utility definition has a malformed requirement.
2406
2577
  */
2407
- #changed() {
2408
- this.#resolutions = void 0;
2409
- this.#generation++;
2578
+ colors(candidate) {
2579
+ return this.#query.candidateColors(candidate);
2410
2580
  }
2411
2581
  };
2412
2582
  /**
2413
- * Normalizes a resolver ID for map lookups.
2583
+ * Splits at delimiters outside brackets, parentheses, single or double quotes, and escapes.
2584
+ * The operation preserves source spelling and does not validate nesting syntax.
2414
2585
  *
2415
- * @param id - Resolver ID, with either slash style for Windows paths.
2416
- * @returns Forward slashes and, for absolute Windows paths, lowercase text.
2586
+ * @param text - Candidate text whose backslashes escape the following UTF-16 code unit.
2587
+ * @param delimiter - One UTF-16 code unit, such as `:` or `/`, that is not a bracket,
2588
+ * parenthesis, quote, or backslash.
2589
+ * @returns Segments in their original order, including empty segments. Nothing is trimmed
2590
+ * or unescaped, and an empty input returns one empty segment.
2417
2591
  */
2418
- function sourceKey(id) {
2419
- const normalized = id.replaceAll("\\", "/");
2420
- return /^[a-z]:\//i.test(normalized) ? normalized.toLowerCase() : normalized;
2592
+ function segments(text, delimiter) {
2593
+ const result = [];
2594
+ let start = 0;
2595
+ let depth = 0;
2596
+ let quote = "";
2597
+ let escaped = false;
2598
+ for (let index = 0; index < text.length; index++) {
2599
+ const character = text[index];
2600
+ if (escaped) {
2601
+ escaped = false;
2602
+ continue;
2603
+ }
2604
+ if (character === "\\") {
2605
+ escaped = true;
2606
+ continue;
2607
+ }
2608
+ if (quote) {
2609
+ if (character === quote) quote = "";
2610
+ continue;
2611
+ }
2612
+ if (character === "'" || character === "\"") quote = character;
2613
+ else if (character === "[" || character === "(") depth++;
2614
+ else if (character === "]" || character === ")") depth--;
2615
+ else if (character === delimiter && depth === 0) {
2616
+ result.push(text.slice(start, index));
2617
+ start = index + 1;
2618
+ }
2619
+ }
2620
+ result.push(text.slice(start));
2621
+ return result;
2421
2622
  }
2422
2623
  /**
2423
- * Compares supplied file contents without depending on map order.
2624
+ * Describes an added marker class and the definitions that make it a marker.
2424
2625
  *
2425
- * @param a - First map of filenames to text. Omission means no files.
2426
- * @param b - Second map, interpreted in the same way.
2427
- * @returns Whether both maps contain the same filenames and text.
2626
+ * @param marker - Marker class returned by {@link CandidateQueries.marker}.
2627
+ * @returns Markdown with the class name first, followed by one line for each kind of origin.
2428
2628
  */
2429
- function sameFiles(a, b) {
2430
- return (a?.size ?? 0) === (b?.size ?? 0) && [...a ?? []].every(([id, text]) => b?.get(id) === text);
2629
+ function markerDocumentation(marker) {
2630
+ const code = (text) => {
2631
+ const ticks = "`".repeat(Math.max(0, ...[...text.matchAll(/`+/g)].map((match) => match[0].length)) + 1);
2632
+ return `${ticks}${text.startsWith("`") || text.endsWith("`") ? ` ${text} ` : text}${ticks}`;
2633
+ };
2634
+ const definitions = marker.origins.flatMap((origin) => origin.kind === "utility" || origin.kind === "variant" ? [`the ${code(origin.name)} ${origin.kind}`] : []);
2635
+ const kinds = new Set(marker.origins.map((origin) => origin.kind));
2636
+ return [
2637
+ `Adds the marker class ${code(marker.class)} to the element as written.`,
2638
+ kinds.has("declared") ? "A `@stillwind-marker` statement declares this class." : void 0,
2639
+ definitions.length ? `Selectors in ${list(definitions)} select this class.` : void 0,
2640
+ kinds.has("source") ? "Selectors in plugin CSS select this class." : void 0
2641
+ ].filter(Boolean).join("\n\n");
2642
+ }
2643
+ /**
2644
+ * Joins phrases into an English list.
2645
+ *
2646
+ * @param items - At least one phrase, in display order.
2647
+ * @returns The phrases separated by commas, with "and" before the last one.
2648
+ */
2649
+ function list(items) {
2650
+ return items.length < 3 ? items.join(" and ") : `${items.slice(0, -1).join(", ")}, and ${items.at(-1)}`;
2651
+ }
2652
+ // src/editor/design-system.ts
2653
+ /**
2654
+ * Tests whether a target contains a wildcard outside brackets and parentheses.
2655
+ *
2656
+ * @param target - Decoded target text.
2657
+ * @returns Whether the target is a pattern.
2658
+ */
2659
+ function isPattern(target) {
2660
+ return segments(target, "*").length > 1;
2661
+ }
2662
+ /**
2663
+ * Compiles a target whose `*` matches any text, including `/` and `:`.
2664
+ *
2665
+ * @param target - Decoded pattern.
2666
+ * @returns An anchored expression.
2667
+ */
2668
+ function patternExpression(target) {
2669
+ const parts = segments(target, "*").map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
2670
+ return new RegExp(`^${parts.join(".*")}$`, "s");
2671
+ }
2672
+ /**
2673
+ * Answers a theme request.
2674
+ *
2675
+ * @param context - Loaded design system.
2676
+ * @param request - Theme request.
2677
+ * @returns Tokens that match, or every token for an empty target list, and unmatched targets.
2678
+ */
2679
+ function theme(context, request) {
2680
+ const tokens = context.query.themeTokens().map(({ name, value, fallback, inline }) => ({
2681
+ name,
2682
+ value,
2683
+ source: fallback ? "default" : "project",
2684
+ inline
2685
+ })).filter(({ source }) => !request.source || source === request.source);
2686
+ const targets = request.targets.map((target) => ({
2687
+ target,
2688
+ expression: patternExpression(`--${target.replace(/^--/, "")}`)
2689
+ }));
2690
+ return {
2691
+ tokens: targets.length ? tokens.filter(({ name }) => targets.some(({ expression }) => expression.test(name))) : tokens,
2692
+ candidates: [],
2693
+ unmatched: targets.filter(({ expression }) => !tokens.some(({ name }) => expression.test(name))).map(({ target }) => target)
2694
+ };
2695
+ }
2696
+ /**
2697
+ * Describes one candidate.
2698
+ *
2699
+ * @param query - Query that contains the definitions of the plugin candidates in the request.
2700
+ * @param candidates - Preview cache over that query.
2701
+ * @param annotations - Preview comment settings.
2702
+ * @param name - Decoded candidate, or a variant name without its trailing colon.
2703
+ * @param kind - Selects utility or variant resolution.
2704
+ * @returns The candidate, with a suggestion when it is invalid.
2705
+ * @throws If a matching utility definition is malformed.
2706
+ */
2707
+ function describe(query, candidates, annotations, name, kind) {
2708
+ const css = kind === "variants" ? candidates.variant(name, "utility") : candidates.preview(name);
2709
+ const marker = kind === "utilities" ? candidates.marker(name) : null;
2710
+ if (css || marker) return {
2711
+ name,
2712
+ kind: kind === "variants" ? "variant" : marker ? "marker" : "utility",
2713
+ valid: true,
2714
+ css: css ? query.formatCss(css, annotations) : ""
2715
+ };
2716
+ const suggestion = kind === "variants" ? query.suggestCandidate(`${name}:flex`)?.replace(/:flex$/, "") : query.suggestCandidate(name);
2717
+ return {
2718
+ name,
2719
+ kind: kind === "variants" ? "variant" : "utility",
2720
+ valid: false,
2721
+ css: "",
2722
+ ...suggestion ? { suggestion } : {}
2723
+ };
2724
+ }
2725
+ /**
2726
+ * Returns the canonical spelling of a valid candidate under the lint options of the project.
2727
+ *
2728
+ * @param query - Query that contains the definitions of the plugin candidates in the request.
2729
+ * @param name - Decoded candidate, or a variant name without its trailing colon.
2730
+ * @param kind - Selects utility or variant spelling.
2731
+ * @returns The spelling, or undefined when `name` has no different canonical spelling.
2732
+ * @throws If a matching utility definition is malformed.
2733
+ */
2734
+ function canonicalSpelling(query, name, kind) {
2735
+ return kind === "variants" ? query.canonicalCandidate(`${name}:flex`)?.replace(/:flex$/, "") : query.canonicalCandidate(name) ?? void 0;
2736
+ }
2737
+ /**
2738
+ * Answers a utility or variant request.
2739
+ *
2740
+ * @param context - Loaded design system.
2741
+ * @param request - Candidate request. An empty target list means every listed name.
2742
+ * @returns Exact candidates, then the names that match patterns. Patterns read the completion
2743
+ * catalog, so they omit numeric and arbitrary values that exact candidates accept.
2744
+ * @throws If a plugin fails or a matching utility definition is malformed.
2745
+ */
2746
+ async function candidates(context, request) {
2747
+ const { kind } = request;
2748
+ const catalog = new CandidateQueries(context.query);
2749
+ const targets = request.targets.length ? request.targets : ["*"];
2750
+ const exact = targets.filter((target) => !isPattern(target));
2751
+ const patterns = [];
2752
+ for (const target of targets.filter(isPattern)) {
2753
+ const expression = patternExpression(target);
2754
+ const prefix = segments(target, "*")[0];
2755
+ const names = [...catalog.complete(prefix).map(({ label }) => label), ...await context.plugins?.catalog(prefix) ?? []].flatMap((label) => {
2756
+ const variant = label.endsWith(":");
2757
+ const name = variant ? label.slice(0, -1) : label;
2758
+ return variant === (kind === "variants") && !name.endsWith("-") && expression.test(name) ? [name] : [];
2759
+ });
2760
+ patterns.push({
2761
+ target,
2762
+ names: [...new Set(names)].sort()
2763
+ });
2764
+ }
2765
+ const dynamic = [...exact, ...patterns.flatMap(({ names }) => names)].map((name) => kind === "variants" ? `${name}:` : name).filter((text) => context.query.dynamicCandidates(text).length > 0);
2766
+ const query = context.plugins && dynamic.length ? await context.plugins.query(dynamic.join(" ")) : context.query;
2767
+ const queries = query === context.query ? catalog : new CandidateQueries(query);
2768
+ const seen = new Set(exact);
2769
+ const listed = [];
2770
+ const unmatched = [];
2771
+ for (const { target, names } of patterns) {
2772
+ let matched = false;
2773
+ for (const name of names) {
2774
+ if (seen.has(name)) {
2775
+ matched = true;
2776
+ continue;
2777
+ }
2778
+ const candidate = describe(query, queries, context.annotations, name, kind);
2779
+ if (candidate.valid) {
2780
+ matched = true;
2781
+ seen.add(name);
2782
+ listed.push(candidate);
2783
+ }
2784
+ }
2785
+ if (!matched) unmatched.push(target);
2786
+ }
2787
+ return {
2788
+ tokens: [],
2789
+ candidates: [...exact.map((name) => {
2790
+ const candidate = describe(query, queries, context.annotations, name, kind);
2791
+ const canonical = candidate.valid ? canonicalSpelling(query, name, kind) : void 0;
2792
+ return canonical ? {
2793
+ ...candidate,
2794
+ canonical
2795
+ } : candidate;
2796
+ }), ...listed],
2797
+ unmatched
2798
+ };
2799
+ }
2800
+ /**
2801
+ * Answers a question about a loaded design system.
2802
+ *
2803
+ * @param context - Loaded design system.
2804
+ * @param request - Theme, utility, or variant request.
2805
+ * @returns The answer. Invalid names and unmatched targets are data.
2806
+ * @throws If a plugin fails or a matching utility definition is malformed.
2807
+ */
2808
+ function queryDesignSystem(context, request) {
2809
+ return request.kind === "theme" ? Promise.resolve(theme(context, request)) : candidates(context, request);
2431
2810
  }
2432
2811
  // src/editor/request.ts
2433
2812
  /**
@@ -2749,16 +3128,16 @@ function sortRuns(values, compare) {
2749
3128
  /**
2750
3129
  * Serializes a declaration identity as a stable checker string-literal key.
2751
3130
  *
2752
- * @param identity - Native declaration identity with original UTF-8 offsets.
2753
- * @returns `stillwind-identity/v1:` followed by base64url JSON of kind, module ID, range, and
2754
- * binding name in a fixed field order.
3131
+ * @param identity - Native declaration identity with its enclosing path and ordinal.
3132
+ * @returns `stillwind-identity/v2:` followed by base64url JSON of kind, module ID, path, ordinal,
3133
+ * and binding name in a fixed field order.
2755
3134
  */
2756
3135
  function identityKey(identity) {
2757
- return `stillwind-identity/v1:${base64url(JSON.stringify({
3136
+ return `stillwind-identity/v2:${base64url(JSON.stringify({
2758
3137
  kind: identity.kind,
2759
3138
  moduleId: identity.moduleId,
2760
- start: identity.start,
2761
- end: identity.end,
3139
+ path: identity.path,
3140
+ ordinal: identity.ordinal,
2762
3141
  bindingName: identity.bindingName
2763
3142
  }))}`;
2764
3143
  }
@@ -3062,6 +3441,7 @@ function projectionPoints(source) {
3062
3441
  }
3063
3442
  /**
3064
3443
  * Encodes identity JSON as an unpadded base64url key.
3444
+ *
3065
3445
  * @param text - Serialized identity text encoded as UTF-8 before base64 conversion.
3066
3446
  * @returns Base64 with URL-safe characters and no trailing padding.
3067
3447
  */
@@ -3070,6 +3450,7 @@ function base64url(text) {
3070
3450
  }
3071
3451
  /**
3072
3452
  * Finds the next token start after whitespace and comments.
3453
+ *
3073
3454
  * @param text - Checker call text to scan.
3074
3455
  * @param offset - UTF-16 position at which scanning starts.
3075
3456
  * @returns UTF-16 start of the next token, or text.length at end of input.
@@ -3975,6 +4356,7 @@ function cssColor(color) {
3975
4356
  // src/editor/completion.ts
3976
4357
  /**
3977
4358
  * Converts one empty arbitrary-value placeholder into an LSP snippet.
4359
+ *
3978
4360
  * @param candidate - Decoded replacement text, including enclosing variants.
3979
4361
  * @param source - Encodes decoded text for its source string. CSS uses the unchanged text.
3980
4362
  * @returns A snippet with its first tab stop inside `[]`, or undefined without a placeholder.
@@ -3989,6 +4371,7 @@ function completionSnippet(candidate, source = (text) => text) {
3989
4371
  }
3990
4372
  /**
3991
4373
  * Converts the start of a modifiable marker's modifier into an LSP snippet.
4374
+ *
3992
4375
  * @param label - Decoded marker name followed by `/`.
3993
4376
  * @param source - Encodes decoded text for its source string.
3994
4377
  * @returns A snippet that inserts `label` and selects a `name` placeholder after it.
@@ -4665,7 +5048,9 @@ async function queryPluginPaths(id, text, request, options) {
4665
5048
  return result;
4666
5049
  }
4667
5050
  // src/project/stylesheet-editor.ts
4668
- /** Answers semantic CSS queries and lint fixes from one original buffer and captured design system. */
5051
+ /**
5052
+ * Answers semantic CSS queries and lint fixes from one original buffer and captured design system.
5053
+ */
4669
5054
  var StylesheetEditor = class {
4670
5055
  /** Resolver identity of the stylesheet. */
4671
5056
  #id;
@@ -4696,6 +5081,7 @@ var StylesheetEditor = class {
4696
5081
  /**
4697
5082
  * Captures original text, lint reports, and query settings for one stylesheet revision.
4698
5083
  * Callers must load the original CSS graph before using sorting or lint fixes.
5084
+ *
4699
5085
  * @param id - Resolver identity of the stylesheet.
4700
5086
  * @param text - Complete stylesheet text that the reports were computed from.
4701
5087
  * @param reports - Reports whose primary location is this stylesheet. Reports and edits are copied.
@@ -4871,6 +5257,7 @@ var StylesheetEditor = class {
4871
5257
  }
4872
5258
  /**
4873
5259
  * Pins completion resolution to the discovery and snippet settings used for its labels.
5260
+ *
4874
5261
  * @param registryDirectives - Whether the request includes registry metadata.
4875
5262
  * @param snippets - Whether the client supports arbitrary variant snippets.
4876
5263
  * @returns A fingerprint of the captured snapshot and normalized editor settings.
@@ -4884,6 +5271,7 @@ var StylesheetEditor = class {
4884
5271
  }
4885
5272
  /**
4886
5273
  * Returns the plugin suggestions for the candidate before a cursor.
5274
+ *
4887
5275
  * @param offset - UTF-16 character boundary within the captured text.
4888
5276
  * @returns The finite catalog and the suggestions that {@link StylesheetEditor.prepare} loaded
4889
5277
  * for the candidate's input, without duplicates.
@@ -4894,6 +5282,7 @@ var StylesheetEditor = class {
4894
5282
  }
4895
5283
  /**
4896
5284
  * Converts a cursor in the original buffer to the native query's byte coordinates.
5285
+ *
4897
5286
  * @param offset - UTF-16 character boundary within the captured text.
4898
5287
  * @returns The length in UTF-8 bytes of the text before the cursor.
4899
5288
  */
@@ -4902,6 +5291,7 @@ var StylesheetEditor = class {
4902
5291
  }
4903
5292
  /**
4904
5293
  * Converts a native range boundary back to the original buffer's coordinates.
5294
+ *
4905
5295
  * @param offset - UTF-8 character boundary within the captured bytes, returned by the native query.
4906
5296
  * @returns The UTF-16 offset at that boundary.
4907
5297
  */
@@ -4910,6 +5300,7 @@ var StylesheetEditor = class {
4910
5300
  }
4911
5301
  /**
4912
5302
  * Queries and formats a hover against original text or a completed copy of that text.
5303
+ *
4913
5304
  * @param text - CSS buffer to query, including any synthetic completion replacement.
4914
5305
  * @param offset - UTF-16 character boundary within `text`.
4915
5306
  * @returns CSS and documentation at UTF-16 boundaries in `text`, or undefined for unresolved input.
@@ -4975,6 +5366,6 @@ function compilerOptions(config) {
4975
5366
  rootFontSize: resolved.rootFontSize
4976
5367
  };
4977
5368
  }
4978
- export { compileWithPlugins as A, compileModule as C, fileSourceKind as D, cleanModuleId as E, prepareSourcePlugins as M, TypeFactsError as O, analyzeModule as S, CompilationFailure as T, loadEditorCssGraph as _, pluginDirectory as a, cssBannerPrefix as b, CheckerSource as c, CompilationProject as d, sourceKey as f, loadCssGraph as g, lintsStylesheet as h, completePluginPaths as i, pluginLoader as j, attachPlugins as k, checkerId as l, isStylesheet as m, cssEntrypoint as n, queryPluginPaths as o, queryDesignSystem as p, StylesheetEditor as r, EditorSnapshot as s, compilerOptions as t, withRequestedProbes as u, PluginRuntime as v, warnRejectedNames as w, finalizeCss as x, defaultPluginExport as y };
5369
+ export { fileSourceKind as A, CompilationFailure as C, ResolutionMismatchError as D, CompilationProject as E, prepareSourcePlugins as F, attachPlugins as M, compileWithPlugins as N, sourceKey as O, pluginLoader as P, warnRejectedNames as S, tracePhase as T, defaultPluginExport as _, pluginDirectory as a, analyzeModule as b, CheckerSource as c, queryDesignSystem as d, isStylesheet as f, PluginRuntime as g, loadEditorCssGraph as h, completePluginPaths as i, TypeFactsError as j, cleanModuleId as k, checkerId as l, loadCssGraph as m, cssEntrypoint as n, queryPluginPaths as o, lintsStylesheet as p, StylesheetEditor as r, EditorSnapshot as s, compilerOptions as t, withRequestedProbes as u, cssBannerPrefix as v, startPhase as w, compileModule as x, finalizeCss as y };
4979
5370
 
4980
- //# sourceMappingURL=options-PMjJ1c8W.js.map
5371
+ //# sourceMappingURL=options-CHkqG1Gc.js.map