@stencil/unplugin 5.0.0-beta.2 → 5.0.0-beta.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,113 +1,10 @@
1
- import { existsSync, readFileSync, readdirSync } from "node:fs";
2
- import { dirname, extname, join, resolve } from "node:path";
1
+ import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
2
+ import { dirname, extname, join, normalize, resolve } from "node:path";
3
3
  import { createFilter } from "@rollup/pluginutils";
4
- import { cmpMetaToDocsComponent, generateManifest, getScopeId, scopeCss, transpile, transpileSync } from "@stencil/core/compiler";
4
+ import { buildHydrateCss, cmpMetaToDocsComponent, foldBuildFlags, generateComponentTypesFile, generateManifest, getScopeId, parseCssOnlyComponents, scopeCss, transpile, transpileSync, ts, validateHydrated } from "@stencil/core/compiler";
5
5
  import { createUnplugin } from "unplugin";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import { isPackageExists } from "local-pkg";
8
- import ts from "typescript";
9
- //#region src/config.ts
10
- /**
11
- * Stencil config auto-detection for @stencil/unplugin.
12
- *
13
- * Searches for a `stencil.config.ts` (or `.js` variant) in the project root,
14
- * loads it via jiti (so TypeScript is handled without a separate compile step),
15
- * and extracts the subset of flags that are meaningful at transpile time.
16
- *
17
- * `stencilConfigToOverrides` converts that subset to a `BuildOverrides` object
18
- * ready to pass to `transpileSync`.
19
- */
20
- const STENCIL_CONFIG_KEYS = /* @__PURE__ */ new Set([
21
- "namespace",
22
- "srcDir",
23
- "outputTargets",
24
- "plugins",
25
- "signalBacking",
26
- "compat"
27
- ]);
28
- const looksLikeConfig = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && Object.keys(v).some((k) => STENCIL_CONFIG_KEYS.has(k));
29
- const CONFIG_CANDIDATES = [
30
- "stencil.config.ts",
31
- "stencil.config.mts",
32
- "stencil.config.js",
33
- "stencil.config.mjs"
34
- ];
35
- /**
36
- * Attempt to load the project's `stencil.config.ts` and return the
37
- * transpile-relevant fields. Returns `null` if no config file is found or
38
- * if loading fails for any reason.
39
- * @param cwd - project root to search in (usually `process.cwd()`)
40
- * @returns a subset of the Stencil config, or `null` if none is found
41
- */
42
- async function loadStencilConfig(cwd) {
43
- for (const filename of CONFIG_CANDIDATES) {
44
- const configPath = join(cwd, filename);
45
- if (!existsSync(configPath)) continue;
46
- try {
47
- const { createJiti } = await import("jiti");
48
- const mod = await createJiti(import.meta.url).import(configPath);
49
- const raw = mod["config"] ?? (looksLikeConfig(mod["default"]) ? mod["default"] : null);
50
- if (!raw || typeof raw !== "object") return null;
51
- return extractSubset(raw);
52
- } catch {
53
- return null;
54
- }
55
- }
56
- return null;
57
- }
58
- function extractSubset(c) {
59
- const result = {};
60
- if (c["signalBacking"] === true) result.signalBacking = true;
61
- const compat = c["compat"];
62
- if (compat && typeof compat === "object") {
63
- const co = compat;
64
- const ldp = co["lightDomPatches"];
65
- const lifecycleDOMEvents = co["lifecycleDOMEvents"];
66
- const initializeNextTick = co["initializeNextTick"];
67
- if (ldp !== void 0 || lifecycleDOMEvents !== void 0 || initializeNextTick !== void 0) {
68
- result.compat = {};
69
- if (typeof ldp === "boolean") result.compat.lightDomPatches = ldp;
70
- else if (ldp && typeof ldp === "object") result.compat.lightDomPatches = ldp;
71
- if (lifecycleDOMEvents === true) result.compat.lifecycleDOMEvents = true;
72
- if (initializeNextTick === true) result.compat.initializeNextTick = true;
73
- }
74
- }
75
- return result;
76
- }
77
- /**
78
- * Convert a {@link StencilConfigSubset} to a {@link BuildOverrides} object.
79
- * The caller is responsible for merging this with any explicit
80
- * `transpileOptions.buildOverrides` (which should take precedence).
81
- * @param config - the Stencil config subset to convert
82
- * @returns a `BuildOverrides` object suitable for passing to `transpileSync`
83
- */
84
- function stencilConfigToOverrides(config) {
85
- const o = {};
86
- if (config.signalBacking) {
87
- o.signalBacking = true;
88
- o.vdomSignals = true;
89
- }
90
- const compat = config.compat;
91
- if (!compat) return o;
92
- if (compat.lifecycleDOMEvents) o.lifecycleDOMEvents = true;
93
- if (compat.initializeNextTick) o.initializeNextTick = true;
94
- const ldp = compat.lightDomPatches;
95
- if (ldp === false) {
96
- o.lightDomPatches = false;
97
- o.slotChildNodes = false;
98
- o.slotCloneNode = false;
99
- o.slotDomMutations = false;
100
- o.slotTextContent = false;
101
- } else if (typeof ldp === "object") {
102
- o.lightDomPatches = true;
103
- o.slotChildNodes = !!ldp.childNodes;
104
- o.slotCloneNode = !!ldp.cloneNode;
105
- o.slotDomMutations = !!ldp.domMutations;
106
- o.slotTextContent = !!ldp.textContent;
107
- }
108
- return o;
109
- }
110
- //#endregion
111
8
  //#region src/css.ts
112
9
  /**
113
10
  * CSS pipeline for Stencil component stylesheets.
@@ -218,17 +115,47 @@ async function runLightningCss(css, filePath, minify) {
218
115
  }).code.toString();
219
116
  }
220
117
  /**
221
- * Loads a Stencil CSS virtual module.
118
+ * Runs a `.css`/`.scss`/`.sass`/`.less` file through Stencil's preprocessor chain:
119
+ * 1. Preprocessor: Sass/SCSS (`sass`) or Less (`less`) if installed
120
+ * 2. PostCSS with `postcss.config.*` if `postcss` + `postcss-load-config` are installed
121
+ * 3. lightningcss if installed — syntax lowering, vendor prefixes, minification in prod
122
+ * Each step is skipped silently if the relevant peer dep is not installed.
222
123
  *
223
- * Processing order:
224
- * 1. Read raw file
225
- * 2. Preprocessor: Sass/SCSS (`sass`) or Less (`less`) if installed
226
- * 3. PostCSS with `postcss.config.*` if `postcss` + `postcss-load-config` are installed
227
- * 4. lightningcss if installed — syntax lowering, vendor prefixes, minification in prod
228
- * 5. Scoped selector rewrite for `encapsulation: 'scoped'`
124
+ * Shared by `loadStencilCss` (per-component `?tag=` styles) and `global-css.ts`
125
+ * (including the files that feed `@import "stencil-component-globals"`/`"stencil-css-components"`)
229
126
  *
230
- * Each step is skipped silently if the relevant peer dep is not installed.
231
- * Returns `export default "css string"` so bundlers treat the import as a JS module.
127
+ * @param filePath - absolute path to the source file, with its real extension
128
+ * @param isDev - `true` in dev mode (disables minification)
129
+ * @returns the processed CSS and any extra files it depends on (e.g. Sass `@use`/`@import`), or
130
+ * `null` if the file doesn't exist
131
+ */
132
+ async function processCssFile(filePath, isDev) {
133
+ if (!existsSync(filePath)) return null;
134
+ const ext = extname(filePath).slice(1);
135
+ let css = readFileSync(filePath, "utf-8");
136
+ let deps = [];
137
+ if (PKG.sass && (ext === "scss" || ext === "sass")) {
138
+ const r = await compileSass(css, filePath, ext === "sass");
139
+ css = r.css;
140
+ deps = r.deps;
141
+ } else if (PKG.less && ext === "less") {
142
+ const r = await compileLess(css, filePath);
143
+ css = r.css;
144
+ deps = r.deps;
145
+ }
146
+ if (PKG.postcss) css = await runPostCss(css, filePath);
147
+ if (PKG.lightningcss) css = await runLightningCss(css, filePath, !isDev);
148
+ return {
149
+ css,
150
+ deps
151
+ };
152
+ }
153
+ /**
154
+ * Loads a Stencil CSS virtual module.
155
+ *
156
+ * Runs the file through {@link processCssFile}, then applies the scoped-selector rewrite for
157
+ * `encapsulation: 'scoped'`. Returns `export default "css string"` so bundlers treat the import
158
+ * as a JS module.
232
159
  * @param id - virtual module id produced by `resolveStencilCss`
233
160
  * @param isDev - `true` in dev mode (disables minification)
234
161
  * @returns ESM string export of the processed CSS, or `null` if not a Stencil CSS virtual module
@@ -242,135 +169,795 @@ async function loadStencilCss(id, isDev = true) {
242
169
  const params = new URLSearchParams(query);
243
170
  const tag = params.get("tag") ?? "";
244
171
  const encapsulation = params.get("encapsulation") ?? "none";
245
- const ext = decodeURIComponent(params.get("__ext") ?? "css");
246
- const filePath = `${stem}.${ext}`;
247
- if (!existsSync(filePath)) return {
172
+ const result = await processCssFile(`${stem}.${decodeURIComponent(params.get("__ext") ?? "css")}`, isDev);
173
+ if (!result) return {
248
174
  code: "export default () => \"\"",
249
175
  deps: []
250
176
  };
251
- let css = readFileSync(filePath, "utf-8");
252
- let deps = [];
253
- if (PKG.sass && (ext === "scss" || ext === "sass")) {
254
- const r = await compileSass(css, filePath, ext === "sass");
255
- css = r.css;
256
- deps = r.deps;
257
- } else if (PKG.less && ext === "less") {
258
- const r = await compileLess(css, filePath);
259
- css = r.css;
260
- deps = r.deps;
177
+ let { css } = result;
178
+ if (encapsulation === "scoped" && tag) css = scopeCss(css, getScopeId(tag), false);
179
+ return {
180
+ code: `export default () => ${JSON.stringify(css)};`,
181
+ deps: result.deps
182
+ };
183
+ }
184
+ /**
185
+ * Compiles a Sass/Less stylesheet to plain CSS for doc extraction. Unlike {@link processCssFile},
186
+ * this skips PostCSS and lightningcss - to leave JSDoc-style comments alone.
187
+ *
188
+ * @param filePath - absolute path to the source stylesheet
189
+ * @returns plain CSS text, or `null` if the file doesn't exist
190
+ */
191
+ async function compileCssForDocs(filePath) {
192
+ if (!existsSync(filePath)) return null;
193
+ const ext = extname(filePath).slice(1);
194
+ const css = readFileSync(filePath, "utf-8");
195
+ if (PKG.sass && (ext === "scss" || ext === "sass")) return (await compileSass(css, filePath, ext === "sass")).css;
196
+ if (PKG.less && ext === "less") return (await compileLess(css, filePath)).css;
197
+ return css;
198
+ }
199
+ /**
200
+ * Populates `cmp.styleDocs` from `cmp.styles` - the CSS custom-property docs a bundler plugin
201
+ * needs to assemble a custom-elements-manifest entry for a component's stylesheet(s).
202
+ *
203
+ * @param cmp - component metadata from `transpile`/`transpileSync`, mutated in place
204
+ * @param componentPath - absolute path to the component's `.tsx`/`.ts` file, used to build a
205
+ * synthetic `file` for `transpileSync`
206
+ */
207
+ async function collectStyleDocsForComponent(cmp, componentPath) {
208
+ const cssBase = componentPath.replace(/\.\w+$/, ".css");
209
+ for (const style of cmp.styles ?? []) {
210
+ const cssTexts = [];
211
+ if (style.styleStr) cssTexts.push(style.styleStr);
212
+ for (const external of style.externalStyles ?? []) {
213
+ if (!external.absolutePath) continue;
214
+ const css = await compileCssForDocs(external.absolutePath);
215
+ if (css) cssTexts.push(css);
216
+ }
217
+ for (const css of cssTexts) {
218
+ const params = new URLSearchParams({
219
+ tag: cmp.tagName,
220
+ mode: style.modeName,
221
+ encapsulation: cmp.encapsulation ?? "none"
222
+ });
223
+ const result = transpileSync(css, {
224
+ file: `${cssBase}?${params}`,
225
+ docs: true
226
+ });
227
+ if (result.styleDocs?.length) {
228
+ cmp.styleDocs ??= [];
229
+ cmp.styleDocs.push(...result.styleDocs);
230
+ }
231
+ }
232
+ }
233
+ }
234
+ //#endregion
235
+ //#region src/resolve-types.ts
236
+ /**
237
+ * Resolves imported type references in CEM docs components.
238
+ *
239
+ * `transpileSync` uses a single-file TypeScript host, so imported types (e.g.
240
+ * `ButtonVariant` from `'../types'`) can't be followed — `complexType.resolved`
241
+ * ends up as `"any"`. This module creates a minimal ts.Program per referenced
242
+ * types file (cached) and substitutes the actual expanded type text back into
243
+ * the component's doc data before it enters the registry.
244
+ */
245
+ const TYPE_FORMAT_FLAGS = ts.TypeFormatFlags.NoTruncation | ts.TypeFormatFlags.InTypeAlias | ts.TypeFormatFlags.InElementType;
246
+ const typesFileCache = /* @__PURE__ */ new Map();
247
+ function resolveTypesFilePath(specifier, fromDir) {
248
+ const base = resolve(fromDir, specifier);
249
+ if (existsSync(base)) return base;
250
+ for (const ext of [
251
+ ".ts",
252
+ ".tsx",
253
+ ".d.ts"
254
+ ]) {
255
+ const candidate = base + ext;
256
+ if (existsSync(candidate)) return candidate;
257
+ }
258
+ if (base.endsWith(".js")) {
259
+ const stem = base.slice(0, -3);
260
+ for (const ext of [".ts", ".tsx"]) {
261
+ const candidate = stem + ext;
262
+ if (existsSync(candidate)) return candidate;
263
+ }
264
+ }
265
+ }
266
+ function getTypesFileEntry(absPath) {
267
+ const cached = typesFileCache.get(absPath);
268
+ if (cached) return cached;
269
+ const options = {
270
+ ...ts.getDefaultCompilerOptions(),
271
+ noEmit: true,
272
+ module: ts.ModuleKind.ESNext,
273
+ moduleResolution: ts.ModuleResolutionKind.Bundler
274
+ };
275
+ const program = ts.createProgram([absPath], options);
276
+ const checker = program.getTypeChecker();
277
+ const sourceFile = program.getSourceFile(absPath);
278
+ const exportTypes = /* @__PURE__ */ new Map();
279
+ if (sourceFile) {
280
+ const moduleSymbol = checker.getSymbolAtLocation(sourceFile);
281
+ if (moduleSymbol) for (const symbol of checker.getExportsOfModule(moduleSymbol)) exportTypes.set(symbol.name, checker.getDeclaredTypeOfSymbol(symbol));
282
+ }
283
+ const entry = {
284
+ checker,
285
+ exportTypes
286
+ };
287
+ typesFileCache.set(absPath, entry);
288
+ return entry;
289
+ }
290
+ function expandTypeName(typeName, references, fromDir) {
291
+ const ref = references[typeName];
292
+ if (!ref || ref.location !== "import" || !ref.path) return void 0;
293
+ const absPath = resolveTypesFilePath(ref.path, fromDir);
294
+ if (!absPath) return void 0;
295
+ const { checker, exportTypes } = getTypesFileEntry(absPath);
296
+ const type = exportTypes.get(typeName);
297
+ if (!type) return void 0;
298
+ return checker.typeToString(type, void 0, TYPE_FORMAT_FLAGS);
299
+ }
300
+ const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
301
+ function patchType(original, references, fromDir) {
302
+ if (!references) return original;
303
+ let result = original;
304
+ for (const typeName of Object.keys(references)) {
305
+ const expanded = expandTypeName(typeName, references, fromDir);
306
+ if (!expanded || expanded === typeName) continue;
307
+ result = result.replace(new RegExp(`\\b${escapeRegExp(typeName)}\\b`, "g"), expanded.includes("|") || expanded.includes("&") ? `(${expanded})` : expanded);
308
+ }
309
+ return result;
310
+ }
311
+ const hasReferences = (references) => !!references && Object.keys(references).length > 0;
312
+ /**
313
+ * Patches `prop.type` and `event.detail` in-place for any imported/inherited
314
+ * types that weren't fully resolved by Stencil's compiler.
315
+ *
316
+ * Under-resolved types don't always show up as the literal string `"any"` -
317
+ * a prop inherited from a same-project base class (merged via a single-file
318
+ * mini `ts.Program`, which can't follow cross-file imports) can resolve to
319
+ * the type's own unexpanded name instead (e.g. `"Validator"`), since that's
320
+ * what a TypeScript checker falls back to for a type it can't bind. Either
321
+ * way, a `location: 'import'` reference on the prop means there's something
322
+ * worth trying to expand here.
323
+ * @param component The CEM docs component to patch
324
+ * @param componentAbsPath The absolute path to the component's source file (used to resolve relative imports)
325
+ */
326
+ function resolveImportedTypes(component, componentAbsPath) {
327
+ const dir = dirname(componentAbsPath);
328
+ for (const prop of component.props) {
329
+ if (!prop.complexType || !hasReferences(prop.complexType.references)) continue;
330
+ const patched = patchType(prop.complexType.original, prop.complexType.references, dir);
331
+ if (patched !== prop.complexType.original) prop.type = patched;
332
+ }
333
+ for (const event of component.events) {
334
+ if (!event.complexType || !hasReferences(event.complexType.references)) continue;
335
+ const patched = patchType(event.complexType.original, event.complexType.references, dir);
336
+ if (patched !== event.complexType.original) event.detail = patched;
337
+ }
338
+ }
339
+ //#endregion
340
+ //#region src/project-scan.ts
341
+ /**
342
+ * The project-wide component scan behind the docs/CEM and the virtual global-stylesheet imports.
343
+ *
344
+ * The registries are module-level on purpose: `getStencilCEM()` is public API called from outside
345
+ * any plugin instance (e.g. a Storybook preset running in Node.js).
346
+ */
347
+ const docsRegistry = /* @__PURE__ */ new Map();
348
+ const componentGlobalStyles = [];
349
+ const cssOnlyComponentFiles = /* @__PURE__ */ new Set();
350
+ const cssOnlyTagsByFile = /* @__PURE__ */ new Map();
351
+ const componentMetaRegistry = /* @__PURE__ */ new Map();
352
+ const cssOnlyMetaRegistry = /* @__PURE__ */ new Map();
353
+ const tagsBySourceFile = /* @__PURE__ */ new Map();
354
+ /**
355
+ * A snapshot of the whole docs registry's content, used to detect whether a CSS-only
356
+ * component's docs changed after a re-scan. A `.css` file's tag(s) aren't known until after parsing
357
+ * - and it may define more than one; compares the whole registry rather than one entry.
358
+ * Cheap in practice: only runs on file save
359
+ *
360
+ * @returns a string that changes whenever any registry entry's content does
361
+ */
362
+ const getRegistrySnapshot = () => JSON.stringify([...docsRegistry.entries()].sort(([a], [b]) => a.localeCompare(b)));
363
+ /**
364
+ * Returns the current CEM. Only populated when `docs: true` is set.
365
+ * @returns the current CEM, or an empty CEM if `docs: true` was not set.
366
+ */
367
+ function getStencilCEM() {
368
+ return generateManifest({ components: [...docsRegistry.values()] });
369
+ }
370
+ const COMPONENT_DECORATOR_RE = /(@Component|@Prop|@State|@Event|@Method|@Watch|@Listen)\s*[(\s]/;
371
+ const isTsSourceFile = (abs) => (abs.endsWith(".tsx") || abs.endsWith(".ts")) && !abs.endsWith(".d.ts");
372
+ const isCssFile = (abs) => abs.endsWith(".css");
373
+ /**
374
+ * Recursively collect file paths matching `matches` under `dir`, pruning
375
+ * `node_modules` and hidden directories (`.git`, `.vite`, etc.) as it goes.
376
+ *
377
+ * `readdirSync(dir, { recursive: true })` can't prune during traversal - it
378
+ * walks everything first and only lets the caller filter the flat result
379
+ * afterward, which is disastrous under a symlink-heavy `node_modules` (e.g.
380
+ * pnpm's `.pnpm` store, which flattens every dependency in the workspace) -
381
+ * it can take minutes just to list, blocking `buildStart` the whole time.
382
+ *
383
+ * @param dir the directory to walk
384
+ * @param matches predicate applied to each file's absolute path
385
+ * @param out accumulator array of absolute file paths, mutated in place
386
+ */
387
+ function collectFiles(dir, matches, out) {
388
+ let entries;
389
+ try {
390
+ entries = readdirSync(dir, { withFileTypes: true });
391
+ } catch {
392
+ return;
393
+ }
394
+ for (const entry of entries) {
395
+ if (entry.name === "node_modules" || entry.name.startsWith(".")) continue;
396
+ const abs = join(dir, entry.name);
397
+ if (entry.isDirectory()) collectFiles(abs, matches, out);
398
+ else if (entry.isFile() && matches(abs)) out.push(abs);
399
+ }
400
+ }
401
+ /**
402
+ * Parse a single `.css` file for CSS-only components (pure-CSS custom-element definitions
403
+ * marked with a `@component` JSDoc tag - see `@stencil/core/compiler`'s `parseCssOnlyComponents`)
404
+ * and register each one in the docs registry with `cssOnly: true` - replacing whatever the file
405
+ * registered before, so a component whose definition was removed (or whose file was deleted)
406
+ * stops being emitted.
407
+ * @param file absolute path to the `.css` file
408
+ */
409
+ async function scanCssOnlyDocsFile(file) {
410
+ const abs = normalize(file);
411
+ let code = "";
412
+ try {
413
+ code = readFileSync(abs, "utf-8");
414
+ } catch {}
415
+ const { components } = code.includes("@component") ? await parseCssOnlyComponents(abs, code) : { components: [] };
416
+ for (const tag of cssOnlyTagsByFile.get(abs) ?? []) {
417
+ docsRegistry.delete(tag);
418
+ cssOnlyMetaRegistry.delete(tag);
419
+ }
420
+ if (components.length > 0) {
421
+ cssOnlyComponentFiles.add(abs);
422
+ cssOnlyTagsByFile.set(abs, components.map((c) => c.tagName));
423
+ } else {
424
+ cssOnlyComponentFiles.delete(abs);
425
+ cssOnlyTagsByFile.delete(abs);
426
+ }
427
+ for (const item of components) {
428
+ docsRegistry.set(item.tagName, {
429
+ ...cmpMetaToDocsComponent(item, abs),
430
+ cssOnly: true
431
+ });
432
+ cssOnlyMetaRegistry.set(item.tagName, item);
433
+ }
434
+ }
435
+ /**
436
+ * @param file a stylesheet path, in either separator form
437
+ * @returns whether it currently defines CSS-only components
438
+ */
439
+ const isCssOnlyComponentFile = (file) => cssOnlyComponentFiles.has(normalize(file));
440
+ /**
441
+ * Re-scan a changed stylesheet that defines (or used to define) CSS-only components - that changes
442
+ * which ones exist, not just their CSS.
443
+ * @param file the changed file
444
+ */
445
+ async function rescanIfCssOnlyComponent(file) {
446
+ if (!isCssFile(file)) return;
447
+ const abs = normalize(file);
448
+ let code = "";
449
+ try {
450
+ code = readFileSync(abs, "utf-8");
451
+ } catch {}
452
+ if (code.includes("@component") || cssOnlyComponentFiles.has(abs)) await scanCssOnlyDocsFile(abs);
453
+ }
454
+ /**
455
+ * Scan a changed directory for `.css` files not yet known as CSS-only components - a watcher
456
+ * may report a file added to a watched directory as the directory itself.
457
+ * @param dir the changed path - ignored unless it's a directory
458
+ */
459
+ async function rescanNewCssOnlyComponents(dir) {
460
+ try {
461
+ if (!statSync(dir).isDirectory()) return;
462
+ } catch {
463
+ return;
464
+ }
465
+ const cssFiles = [];
466
+ collectFiles(dir, isCssFile, cssFiles);
467
+ await Promise.all(cssFiles.filter((f) => !cssOnlyComponentFiles.has(f)).map(scanCssOnlyDocsFile));
468
+ }
469
+ /**
470
+ * Re-derives one component's docs from its `.tsx` / `.ts` source and merges the result into the
471
+ * docs registry.
472
+ *
473
+ * @param tag the custom-element tag name to refresh
474
+ * @param filePath absolute path to the component's `.tsx`/`.ts` source
475
+ * @returns `true` if the registry entry's content actually changed
476
+ */
477
+ async function refreshComponentDocs(tag, filePath) {
478
+ const prevSnapshot = JSON.stringify(docsRegistry.get(tag));
479
+ try {
480
+ const code = readFileSync(filePath, "utf-8");
481
+ const result = await transpile(code, {
482
+ file: filePath,
483
+ componentExport: "customelement"
484
+ });
485
+ for (const item of result.data ?? []) {
486
+ if (!item.tagName) continue;
487
+ await collectStyleDocsForComponent(item, filePath);
488
+ const component = cmpMetaToDocsComponent(item, filePath);
489
+ resolveImportedTypes(component, filePath);
490
+ docsRegistry.set(item.tagName, component);
491
+ }
492
+ } catch {
493
+ return false;
494
+ }
495
+ return JSON.stringify(docsRegistry.get(tag)) !== prevSnapshot;
496
+ }
497
+ /**
498
+ * Re-derive a changed (or added, or deleted) `.tsx`/`.ts` file's compiler metadata - replacing
499
+ * whatever it defined before, so a removed or renamed component stops being typed.
500
+ * @param file absolute path to the source file
501
+ * @returns whether the file defines, or used to define, any component
502
+ */
503
+ async function refreshComponentMeta(file) {
504
+ const abs = normalize(file);
505
+ let code = "";
506
+ try {
507
+ code = readFileSync(abs, "utf-8");
508
+ } catch {}
509
+ const previous = tagsBySourceFile.get(abs) ?? [];
510
+ let items = [];
511
+ if (COMPONENT_DECORATOR_RE.test(code)) try {
512
+ items = ((await transpile(code, {
513
+ file: abs,
514
+ componentExport: "customelement"
515
+ })).data ?? []).filter((item) => item.tagName);
516
+ } catch {
517
+ return previous.length > 0;
518
+ }
519
+ for (const tag of previous) componentMetaRegistry.delete(tag);
520
+ for (const item of items) componentMetaRegistry.set(item.tagName, item);
521
+ if (items.length > 0) tagsBySourceFile.set(abs, items.map((item) => item.tagName));
522
+ else tagsBySourceFile.delete(abs);
523
+ return previous.length > 0 || items.length > 0;
524
+ }
525
+ /**
526
+ * Scan the project for component source files (`.tsx`/`.ts`) and CSS-only components
527
+ * (`.css`), pre-populating the docs registry, `componentGlobalStyles`, and
528
+ * `cssOnlyComponentFiles` - the project-wide data the virtual global-stylesheet imports need
529
+ * (see `global-css.ts`), gathered eagerly so it doesn't depend on module-graph visitation order.
530
+ * @param filter A function to filter which `.tsx`/`.ts` files should be included - not applied
531
+ * to `.css` files, since the default `include` (`/\.tsx?$/`) would otherwise exclude all of them.
532
+ * @param collectStyleDocs Whether to also collect CSS custom-property docs for each component's
533
+ * stylesheet(s) - the extra parse cost only pays off when `options.docs` is set.
534
+ * @returns A promise that resolves when the scan is complete.
535
+ */
536
+ async function scanDocs(filter, collectStyleDocs) {
537
+ componentGlobalStyles.length = 0;
538
+ for (const tags of cssOnlyTagsByFile.values()) for (const tag of tags) docsRegistry.delete(tag);
539
+ cssOnlyTagsByFile.clear();
540
+ cssOnlyComponentFiles.clear();
541
+ componentMetaRegistry.clear();
542
+ cssOnlyMetaRegistry.clear();
543
+ tagsBySourceFile.clear();
544
+ const cwd = process.cwd();
545
+ const allFiles = [];
546
+ collectFiles(cwd, (abs) => isTsSourceFile(abs) || isCssFile(abs), allFiles);
547
+ const tsxFiles = allFiles.filter((abs) => isTsSourceFile(abs) && filter(abs));
548
+ const cssFiles = allFiles.filter(isCssFile);
549
+ await Promise.all([...tsxFiles.map(async (abs) => {
550
+ let code;
551
+ try {
552
+ code = readFileSync(abs, "utf-8");
553
+ } catch {
554
+ return;
555
+ }
556
+ if (!COMPONENT_DECORATOR_RE.test(code)) return;
557
+ const result = await transpile(code, {
558
+ file: abs,
559
+ componentExport: "customelement"
560
+ });
561
+ for (const item of result.data ?? []) {
562
+ if (!item.tagName) continue;
563
+ if (collectStyleDocs) await collectStyleDocsForComponent(item, abs);
564
+ const component = cmpMetaToDocsComponent(item, abs);
565
+ resolveImportedTypes(component, abs);
566
+ docsRegistry.set(item.tagName, component);
567
+ componentMetaRegistry.set(item.tagName, item);
568
+ tagsBySourceFile.set(normalize(abs), [...tagsBySourceFile.get(normalize(abs)) ?? [], item.tagName]);
569
+ if (item.globalStyles?.length) componentGlobalStyles.push(...item.globalStyles);
570
+ }
571
+ }), ...cssFiles.map(scanCssOnlyDocsFile)]);
572
+ }
573
+ //#endregion
574
+ //#region src/component-types.ts
575
+ /**
576
+ * `components.d.ts` - the typings `stencil build` writes to `srcDir`, generated here from the
577
+ * project scan with core's own generator, so a project whose dev loop never runs the Stencil
578
+ * compiler (Storybook, a Vite app authoring components from source) still gets them, kept current
579
+ * as sources change. Same generator, same inputs, same order: if `stencil build --watch` runs
580
+ * alongside, both write identical content.
581
+ */
582
+ const byTagName = (a, b) => a.tagName.localeCompare(b.tagName);
583
+ /**
584
+ * Write `<srcDir>/components.d.ts` from the current registries, unless its content is unchanged -
585
+ * so an editor's TS server, or a `stencil build --watch`, isn't disturbed for nothing.
586
+ * @param config `srcDir` (absolute) plus the other fields that affect the output
587
+ * @returns whether the file was (re)written
588
+ */
589
+ function writeComponentTypes(config) {
590
+ const filePath = join(config.srcDir, "components.d.ts");
591
+ const content = generateComponentTypesFile([...[...componentMetaRegistry.values()].sort(byTagName), ...[...cssOnlyMetaRegistry.values()].sort(byTagName)], config);
592
+ let existing;
593
+ try {
594
+ existing = readFileSync(filePath, "utf-8");
595
+ } catch {}
596
+ if (existing === content) return false;
597
+ writeFileSync(filePath, content);
598
+ return true;
599
+ }
600
+ //#endregion
601
+ //#region src/config.ts
602
+ /**
603
+ * Stencil config auto-detection for @stencil/unplugin.
604
+ *
605
+ * Searches for a `stencil.config.ts` (or `.js` variant) in the project root,
606
+ * loads it via jiti (so TypeScript is handled without a separate compile step),
607
+ * and extracts the subset of flags that are meaningful at transpile time.
608
+ *
609
+ * `stencilConfigToOverrides` converts that subset to a `BuildOverrides` object
610
+ * ready to pass to `transpileSync`.
611
+ */
612
+ const STENCIL_CONFIG_KEYS = /* @__PURE__ */ new Set([
613
+ "namespace",
614
+ "srcDir",
615
+ "outputTargets",
616
+ "plugins",
617
+ "signalBacking",
618
+ "compat",
619
+ "srcDir"
620
+ ]);
621
+ const looksLikeConfig = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && Object.keys(v).some((k) => STENCIL_CONFIG_KEYS.has(k));
622
+ const CONFIG_CANDIDATES = [
623
+ "stencil.config.ts",
624
+ "stencil.config.mts",
625
+ "stencil.config.js",
626
+ "stencil.config.mjs"
627
+ ];
628
+ /**
629
+ * Attempt to load the project's `stencil.config.ts` and return the
630
+ * transpile-relevant fields. Returns `null` if no config file is found or
631
+ * if loading fails for any reason.
632
+ * @param cwd - project root to search in (usually `process.cwd()`)
633
+ * @returns a subset of the Stencil config, or `null` if none is found
634
+ */
635
+ async function loadStencilConfig(cwd) {
636
+ for (const filename of CONFIG_CANDIDATES) {
637
+ const configPath = join(cwd, filename);
638
+ if (!existsSync(configPath)) continue;
639
+ try {
640
+ const { createJiti } = await import("jiti");
641
+ const mod = await createJiti(import.meta.url).import(configPath);
642
+ const raw = mod["config"] ?? (looksLikeConfig(mod["default"]) ? mod["default"] : null);
643
+ if (!raw || typeof raw !== "object") return null;
644
+ return extractSubset(raw);
645
+ } catch {
646
+ return null;
647
+ }
648
+ }
649
+ return null;
650
+ }
651
+ function extractSubset(c) {
652
+ const result = {};
653
+ if (c["signalBacking"] === true) result.signalBacking = true;
654
+ if (typeof c["srcDir"] === "string") result.srcDir = c["srcDir"];
655
+ if ("hydratedFlag" in c) result.hydratedFlag = c["hydratedFlag"];
656
+ const compat = c["compat"];
657
+ if (compat && typeof compat === "object") {
658
+ const co = compat;
659
+ const ldp = co["lightDomPatches"];
660
+ const lifecycleDOMEvents = co["lifecycleDOMEvents"];
661
+ const initializeNextTick = co["initializeNextTick"];
662
+ if (ldp !== void 0 || lifecycleDOMEvents !== void 0 || initializeNextTick !== void 0) {
663
+ result.compat = {};
664
+ if (typeof ldp === "boolean") result.compat.lightDomPatches = ldp;
665
+ else if (ldp && typeof ldp === "object") result.compat.lightDomPatches = ldp;
666
+ if (lifecycleDOMEvents === true) result.compat.lifecycleDOMEvents = true;
667
+ if (initializeNextTick === true) result.compat.initializeNextTick = true;
668
+ }
669
+ }
670
+ return result;
671
+ }
672
+ /**
673
+ * Convert a {@link StencilConfigSubset} to a {@link BuildOverrides} object.
674
+ * The caller is responsible for merging this with any explicit
675
+ * `transpileOptions.buildOverrides` (which should take precedence).
676
+ * @param config - the Stencil config subset to convert
677
+ * @returns a `BuildOverrides` object suitable for passing to `transpileSync`
678
+ */
679
+ function stencilConfigToOverrides(config) {
680
+ const o = {};
681
+ if (config.signalBacking) {
682
+ o.signalBacking = true;
683
+ o.vdomSignals = true;
684
+ }
685
+ const compat = config.compat;
686
+ if (!compat) return o;
687
+ if (compat.lifecycleDOMEvents) o.lifecycleDOMEvents = true;
688
+ if (compat.initializeNextTick) o.initializeNextTick = true;
689
+ const ldp = compat.lightDomPatches;
690
+ if (ldp === false) {
691
+ o.lightDomPatches = false;
692
+ o.slotChildNodes = false;
693
+ o.slotCloneNode = false;
694
+ o.slotDomMutations = false;
695
+ o.slotTextContent = false;
696
+ } else if (typeof ldp === "object") {
697
+ o.lightDomPatches = true;
698
+ o.slotChildNodes = !!ldp.childNodes;
699
+ o.slotCloneNode = !!ldp.cloneNode;
700
+ o.slotDomMutations = !!ldp.domMutations;
701
+ o.slotTextContent = !!ldp.textContent;
261
702
  }
262
- if (PKG.postcss) css = await runPostCss(css, filePath);
263
- if (PKG.lightningcss) css = await runLightningCss(css, filePath, !isDev);
264
- if (encapsulation === "scoped" && tag) css = scopeCss(css, getScopeId(tag), false);
265
- return {
266
- code: `export default () => ${JSON.stringify(css)};`,
267
- deps
268
- };
703
+ return o;
269
704
  }
270
705
  //#endregion
271
- //#region src/resolve-types.ts
706
+ //#region src/global-css.ts
272
707
  /**
273
- * Resolves imported type references in CEM docs components.
708
+ * Stencil's three virtual global-stylesheet imports - `@import "stencil-hydrate"`,
709
+ * `"stencil-component-globals"` and `"stencil-css-components"` - as real stylesheets.
274
710
  *
275
- * `transpileSync` uses a single-file TypeScript host, so imported types (e.g.
276
- * `ButtonVariant` from `'../types'`) can't be followed — `complexType.resolved`
277
- * ends up as `"any"`. This module creates a minimal ts.Program per referenced
278
- * types file (cached) and substitutes the actual expanded type text back into
279
- * the component's doc data before it enters the registry.
711
+ * Their CSS, gathered by the project-wide scan (see `scanDocs` in `plugin.ts`), is written to
712
+ * `<dir>/<name>.css` and each specifier resolves to that file, so the bundler handles it like any
713
+ * other stylesheet: wherever it's imported from (partials, Sass, Less) and with whatever
714
+ * `@import` modifiers. Vite doesn't consult plugins when resolving CSS `@import`, so there it's
715
+ * reached through an alias ({@link virtualGlobalStylesheetAlias}); other bundlers go through
716
+ * `resolveId`.
280
717
  */
281
- const TYPE_FORMAT_FLAGS = ts.TypeFormatFlags.NoTruncation | ts.TypeFormatFlags.InTypeAlias | ts.TypeFormatFlags.InElementType;
282
- const typesFileCache = /* @__PURE__ */ new Map();
283
- function resolveTypesFilePath(specifier, fromDir) {
284
- const base = resolve(fromDir, specifier);
285
- if (existsSync(base)) return base;
286
- for (const ext of [
287
- ".ts",
288
- ".tsx",
289
- ".d.ts"
290
- ]) {
291
- const candidate = base + ext;
292
- if (existsSync(candidate)) return candidate;
718
+ const VIRTUAL_GLOBAL_IMPORTS = [
719
+ "stencil-hydrate",
720
+ "stencil-component-globals",
721
+ "stencil-css-components"
722
+ ];
723
+ const VIRTUAL_GLOBAL_ID_RE = new RegExp(`^(${VIRTUAL_GLOBAL_IMPORTS.join("|")})$`);
724
+ /** Matches a mention of any virtual global-stylesheet import name. */
725
+ const VIRTUAL_GLOBAL_IMPORT_RE = new RegExp(`\\b(?:${VIRTUAL_GLOBAL_IMPORTS.join("|")})\\b`);
726
+ const VIRTUAL_GLOBAL_SUFFIX_RE = new RegExp(`(?:^|[\\\\/])(${VIRTUAL_GLOBAL_IMPORTS.join("|")})$`);
727
+ /**
728
+ * The virtual import a specifier refers to - either exactly, or with a directory prefix, which
729
+ * callers should only accept when no such file exists (see {@link VIRTUAL_GLOBAL_SUFFIX_RE}).
730
+ * @param id a module specifier
731
+ * @returns the virtual import's name, if the specifier ends in one
732
+ */
733
+ const getVirtualGlobalImportName = (id) => VIRTUAL_GLOBAL_SUFFIX_RE.exec(id)?.[1];
734
+ /**
735
+ * @param dir the directory {@link writeVirtualGlobalStylesheets} writes to
736
+ * @param name a virtual global-stylesheet import
737
+ * @returns the path of its generated stylesheet
738
+ */
739
+ const virtualGlobalStylesheetPath = (dir, name) => join(dir, `${name}.css`);
740
+ /**
741
+ * A Vite alias sending each virtual import to its generated stylesheet in `dir`.
742
+ * @param dir the directory {@link writeVirtualGlobalStylesheets} writes to
743
+ * @returns the alias entry
744
+ */
745
+ const virtualGlobalStylesheetAlias = (dir) => ({
746
+ find: VIRTUAL_GLOBAL_ID_RE,
747
+ replacement: virtualGlobalStylesheetPath(dir, "$1")
748
+ });
749
+ /**
750
+ * A webpack-style alias map (`name$` = exact match) sending each virtual import to its generated
751
+ * stylesheet in `dir` - for bundlers whose CSS `@import` resolution skips plugins (rspack).
752
+ * @param dir the directory {@link writeVirtualGlobalStylesheets} writes to
753
+ * @returns the alias map
754
+ */
755
+ const virtualGlobalStylesheetAliasMap = (dir) => Object.fromEntries(VIRTUAL_GLOBAL_IMPORTS.map((name) => [`${name}$`, virtualGlobalStylesheetPath(dir, name)]));
756
+ /**
757
+ * Tags `stencil-hydrate` hides until hydrated. CSS-only components never hydrate, so including
758
+ * them would hide them for good.
759
+ * @param components every component in the docs registry
760
+ * @returns the real (JS-backed) components' tag names
761
+ */
762
+ const getHydrateTagNames = (components) => new Set([...components].filter((c) => !c.cssOnly).map((c) => c.tag));
763
+ const processedFileCache = /* @__PURE__ */ new Map();
764
+ const latestMtime = (filePaths) => {
765
+ let latest = 0;
766
+ for (const filePath of filePaths) try {
767
+ latest = Math.max(latest, statSync(filePath).mtimeMs);
768
+ } catch {
769
+ return NaN;
293
770
  }
294
- if (base.endsWith(".js")) {
295
- const stem = base.slice(0, -3);
296
- for (const ext of [".ts", ".tsx"]) {
297
- const candidate = stem + ext;
298
- if (existsSync(candidate)) return candidate;
771
+ return latest;
772
+ };
773
+ async function collectFileParts(filePaths, isDev) {
774
+ const parts = [];
775
+ const deps = [];
776
+ for (const filePath of filePaths) {
777
+ deps.push(filePath);
778
+ let processed = processedFileCache.get(filePath);
779
+ if (!processed || processed.mtimeMs !== latestMtime([filePath, ...processed.deps])) {
780
+ const result = await processCssFile(filePath, isDev);
781
+ if (!result) continue;
782
+ processed = {
783
+ ...result,
784
+ mtimeMs: latestMtime([filePath, ...result.deps])
785
+ };
786
+ processedFileCache.set(filePath, processed);
299
787
  }
788
+ parts.push(processed.css);
789
+ deps.push(...processed.deps);
300
790
  }
791
+ return {
792
+ css: parts.join("\n"),
793
+ deps
794
+ };
301
795
  }
302
- function getTypesFileEntry(absPath) {
303
- const cached = typesFileCache.get(absPath);
304
- if (cached) return cached;
305
- const options = {
306
- ...ts.getDefaultCompilerOptions(),
307
- noEmit: true,
308
- module: ts.ModuleKind.ESNext,
309
- moduleResolution: ts.ModuleResolutionKind.Bundler
796
+ async function collectComponentGlobalStyles(entries, isDev) {
797
+ const inline = [];
798
+ const filePaths = [];
799
+ for (const gs of entries) if (gs.styleStr) inline.push(gs.styleStr);
800
+ else if (gs.absolutePath) filePaths.push(gs.absolutePath);
801
+ const { css: fileCss, deps } = await collectFileParts(filePaths, isDev);
802
+ return {
803
+ css: [...inline, fileCss].filter(Boolean).join("\n"),
804
+ deps
310
805
  };
311
- const program = ts.createProgram([absPath], options);
312
- const checker = program.getTypeChecker();
313
- const sourceFile = program.getSourceFile(absPath);
314
- const exportTypes = /* @__PURE__ */ new Map();
315
- if (sourceFile) {
316
- const moduleSymbol = checker.getSymbolAtLocation(sourceFile);
317
- if (moduleSymbol) for (const symbol of checker.getExportsOfModule(moduleSymbol)) exportTypes.set(symbol.name, checker.getDeclaredTypeOfSymbol(symbol));
806
+ }
807
+ /**
808
+ * Write each virtual import's CSS to `<dir>/<name>.css` - all three, even when empty, so they
809
+ * always resolve. Files whose content is unchanged are left alone, so they don't trigger HMR.
810
+ * @param dir the directory to write to
811
+ * @param data project-wide data collected by `scanDocs`
812
+ * @param isDev `true` in dev mode (disables minification in the ingredient preprocessing chain)
813
+ * @returns the paths of files that were (re)written, and every ingredient file the CSS came from
814
+ * (register these as watch files)
815
+ */
816
+ async function writeVirtualGlobalStylesheets(dir, data, isDev) {
817
+ const globals = await collectComponentGlobalStyles(data.componentGlobalStyles, isDev);
818
+ const cssOnly = await collectFileParts(data.cssOnlyComponentFiles, isDev);
819
+ const contents = {
820
+ "stencil-hydrate": buildHydrateCss(data.hydratedFlag, [...data.tagNames]),
821
+ "stencil-component-globals": globals.css,
822
+ "stencil-css-components": cssOnly.css
823
+ };
824
+ mkdirSync(dir, { recursive: true });
825
+ const written = [];
826
+ for (const name of VIRTUAL_GLOBAL_IMPORTS) {
827
+ const filePath = virtualGlobalStylesheetPath(dir, name);
828
+ let existing;
829
+ try {
830
+ existing = readFileSync(filePath, "utf-8");
831
+ } catch {}
832
+ if (existing !== contents[name]) {
833
+ writeFileSync(filePath, contents[name]);
834
+ written.push(filePath);
835
+ }
318
836
  }
319
- const entry = {
320
- checker,
321
- exportTypes
837
+ return {
838
+ written,
839
+ deps: [...globals.deps, ...cssOnly.deps]
322
840
  };
323
- typesFileCache.set(absPath, entry);
324
- return entry;
325
- }
326
- function expandTypeName(typeName, references, fromDir) {
327
- const ref = references[typeName];
328
- if (!ref || ref.location !== "import" || !ref.path) return void 0;
329
- const absPath = resolveTypesFilePath(ref.path, fromDir);
330
- if (!absPath) return void 0;
331
- const { checker, exportTypes } = getTypesFileEntry(absPath);
332
- const type = exportTypes.get(typeName);
333
- if (!type) return void 0;
334
- return checker.typeToString(type, void 0, TYPE_FORMAT_FLAGS);
335
841
  }
336
- const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
337
- function patchType(original, references, fromDir) {
338
- if (!references) return original;
339
- let result = original;
340
- for (const typeName of Object.keys(references)) {
341
- const expanded = expandTypeName(typeName, references, fromDir);
342
- if (!expanded || expanded === typeName) continue;
343
- result = result.replace(new RegExp(`\\b${escapeRegExp(typeName)}\\b`, "g"), expanded.includes("|") || expanded.includes("&") ? `(${expanded})` : expanded);
842
+ const STYLE_FILE_RE = /\.(css|scss|sass|less|styl|stylus|pcss)$/;
843
+ const mentionsVirtualGlobalImport = (abs) => {
844
+ try {
845
+ return VIRTUAL_GLOBAL_IMPORT_RE.test(readFileSync(abs, "utf-8"));
846
+ } catch {
847
+ return false;
344
848
  }
345
- return result;
849
+ };
850
+ /**
851
+ * Cheap text check of every stylesheet under `root` for a virtual global-stylesheet import -
852
+ * gates the full project scan the generated stylesheets need.
853
+ * @param root the project root
854
+ * @returns whether any stylesheet mentions one
855
+ */
856
+ function projectUsesVirtualGlobalImports(root) {
857
+ const styleFiles = [];
858
+ collectFiles(root, (abs) => STYLE_FILE_RE.test(abs), styleFiles);
859
+ return styleFiles.some(mentionsVirtualGlobalImport);
346
860
  }
347
- const hasReferences = (references) => !!references && Object.keys(references).length > 0;
348
861
  /**
349
- * Patches `prop.type` and `event.detail` in-place for any imported/inherited
350
- * types that weren't fully resolved by Stencil's compiler.
351
- *
352
- * Under-resolved types don't always show up as the literal string `"any"` -
353
- * a prop inherited from a same-project base class (merged via a single-file
354
- * mini `ts.Program`, which can't follow cross-file imports) can resolve to
355
- * the type's own unexpanded name instead (e.g. `"Validator"`), since that's
356
- * what a TypeScript checker falls back to for a type it can't bind. Either
357
- * way, a `location: 'import'` reference on the prop means there's something
358
- * worth trying to expand here.
359
- * @param component The CEM docs component to patch
360
- * @param componentAbsPath The absolute path to the component's source file (used to resolve relative imports)
862
+ * One plugin instance's generated virtual global stylesheets: where they live, and generating
863
+ * them on first use - so projects that never use them don't pay for the project scan - then
864
+ * regenerating them as sources change.
865
+ * @param prepare loads whatever the stylesheets are built from (config, project scan)
866
+ * @param isDev whether this is a dev build (unminified, and a separate output dir)
867
+ * @returns the stylesheets' controls, one per plugin hook that needs them
361
868
  */
362
- function resolveImportedTypes(component, componentAbsPath) {
363
- const dir = dirname(componentAbsPath);
364
- for (const prop of component.props) {
365
- if (!prop.complexType || !hasReferences(prop.complexType.references)) continue;
366
- const patched = patchType(prop.complexType.original, prop.complexType.references, dir);
367
- if (patched !== prop.complexType.original) prop.type = patched;
368
- }
369
- for (const event of component.events) {
370
- if (!event.complexType || !hasReferences(event.complexType.references)) continue;
371
- const patched = patchType(event.complexType.original, event.complexType.references, dir);
372
- if (patched !== event.complexType.original) event.detail = patched;
373
- }
869
+ function createVirtualGlobalCss(prepare, isDev) {
870
+ let dir = "";
871
+ let written = null;
872
+ let deps = [];
873
+ const write = async () => {
874
+ const result = await writeVirtualGlobalStylesheets(dir, await prepare(), isDev());
875
+ deps = result.deps;
876
+ return result;
877
+ };
878
+ const ensure = () => written ??= write();
879
+ const rewrite = async () => {
880
+ await written;
881
+ written = write();
882
+ return written;
883
+ };
884
+ const refresh = () => written ? rewrite() : ensure();
885
+ const useDefaultDir = (root) => {
886
+ dir ||= resolve(root, "node_modules", ".stencil", "virtual-css", isDev() ? "serve" : "build");
887
+ };
888
+ const isPath = (id) => !!dir && dirname(id) === dir;
889
+ return {
890
+ get dir() {
891
+ return dir;
892
+ },
893
+ /** @returns whether they've been generated yet, i.e. something uses them */
894
+ get started() {
895
+ return !!written;
896
+ },
897
+ /** @returns the ingredient files the last generation drew from */
898
+ get deps() {
899
+ return deps;
900
+ },
901
+ setDir(value) {
902
+ dir = value;
903
+ },
904
+ /** Use the default dir under `root`, unless one's already been set. */
905
+ useDefaultDir,
906
+ isPath,
907
+ refresh,
908
+ /**
909
+ * @param id a module specifier
910
+ * @param importer the importing file
911
+ * @returns the generated stylesheet it refers to, if it's a virtual import. A directory-prefixed
912
+ * name (as Less writes `(css)` imports in a partial) only counts when no such file exists.
913
+ */
914
+ async resolveId(id, importer) {
915
+ if (isPath(id)) {
916
+ await ensure();
917
+ return id;
918
+ }
919
+ const name = getVirtualGlobalImportName(id);
920
+ if (!name || name !== id && importer && existsSync(resolve(dirname(importer), id))) return;
921
+ await ensure();
922
+ return virtualGlobalStylesheetPath(dir, name);
923
+ },
924
+ /**
925
+ * Regenerated on every load, so a watch-mode rebuild sees ingredient changes.
926
+ * @param id a generated stylesheet's path
927
+ * @returns its CSS, and the ingredient files to register as watch files
928
+ */
929
+ async load(id) {
930
+ await rewrite();
931
+ return {
932
+ code: readFileSync(id, "utf-8"),
933
+ deps
934
+ };
935
+ },
936
+ /**
937
+ * For bundlers that read the generated files straight from disk before compiling (webpack,
938
+ * rspack) - (re)write them before every compile, once some stylesheet uses them.
939
+ * @param root the project root
940
+ */
941
+ async forCompile(root) {
942
+ if (!written && !projectUsesVirtualGlobalImports(root)) return;
943
+ useDefaultDir(root);
944
+ await refresh();
945
+ },
946
+ /**
947
+ * Vite HMR: generate them once a stylesheet first mentions one, then regenerate on every
948
+ * relevant change.
949
+ * @param file the changed file
950
+ * @returns the generated stylesheets whose content changed
951
+ */
952
+ async hotUpdate(file) {
953
+ if (!written) {
954
+ if (STYLE_FILE_RE.test(file) && mentionsVirtualGlobalImport(file)) await ensure();
955
+ return [];
956
+ }
957
+ if (!/\.(css|tsx?)$/.test(file)) return [];
958
+ return (await rewrite()).written;
959
+ }
960
+ };
374
961
  }
375
962
  //#endregion
376
963
  //#region src/transform.ts
@@ -474,7 +1061,7 @@ function resolveSpecifier(specifier, importer) {
474
1061
  * @param configOverrides - pass stencil config option overrides to the transpiler
475
1062
  * @returns transformed output, or `null` if the file is not a Stencil file
476
1063
  */
477
- function transformStencil(code, id, options, dev = false, framework = "", onBaseClass, configOverrides) {
1064
+ async function transformStencil(code, id, options, dev = false, framework = "", onBaseClass, configOverrides) {
478
1065
  if (!id.endsWith(".tsx") && !id.endsWith(".ts")) return null;
479
1066
  if (id.endsWith(".d.ts")) return null;
480
1067
  if (!/(@Component|@Prop|@State|@Event|@Method|@Watch|@Listen)\s*[(\s]/.test(code)) return null;
@@ -521,6 +1108,7 @@ function transformStencil(code, id, options, dev = false, framework = "", onBase
521
1108
  const namedExport = `\nexport{${className}};`;
522
1109
  out = dev ? result.code + namedExport + buildHmrSnippet(tagName, className, framework) : result.code + namedExport;
523
1110
  }
1111
+ if (options.docs) await collectStyleDocsForComponent(result.data[0], id);
524
1112
  const docsComponent = cmpMetaToDocsComponent(result.data[0], id);
525
1113
  return {
526
1114
  code: out,
@@ -553,7 +1141,7 @@ function transpileBaseClass(rawCode, absPath, options) {
553
1141
  }
554
1142
  function buildHmrSnippet(tagName, className, framework) {
555
1143
  const tag = JSON.stringify(tagName);
556
- if (framework === "webpack" || framework === "rspack" || framework === "bun") return `\n${className}.__stencil_module__ = import.meta.url;\nvar _sHot = ${framework === "bun" ? "import.meta.hot" : "(typeof module !== 'undefined' && module.hot) || import.meta.webpackHot"};\nif (_sHot) {\n if (_sHot.data && _sHot.data.stencilHmr) {\n var _sCtor = customElements.get(${tag});\n if (_sCtor) Object.getOwnPropertyNames(${className}.prototype).forEach(function(k) {\n if (k !== 'constructor') Object.defineProperty(_sCtor.prototype, k, Object.getOwnPropertyDescriptor(${className}.prototype, k));\n });\n document.querySelectorAll(${tag}).forEach(function(el) { el.connectedCallback && el.connectedCallback(); });\n }\n _sHot.dispose(function(data) { data.stencilHmr = true; });\n _sHot.accept();\n}`;
1144
+ if (framework === "webpack" || framework === "rspack" || framework === "bun") return `\n${className}.__stencil_module__ = import.meta.url;\nvar _sHot = ${framework === "bun" ? "import.meta.hot" : "(typeof module !== 'undefined' && module.hot) || import.meta.webpackHot"};\nif (_sHot) {\n if (_sHot.data && _sHot.data.stencilHmr) {\n var _sCtor = customElements.get(${tag});\n if (_sCtor && _sCtor['s-hmr-apply']) _sCtor['s-hmr-apply'](${className});\n }\n _sHot.dispose(function(data) { data.stencilHmr = true; });\n _sHot.accept();\n}`;
557
1145
  return `\n${className}.__stencil_module__ = import.meta.url;\nif (import.meta.hot && !import.meta.url.includes('s-hmr=')) {\n import.meta.hot.accept(() => {});\n import.meta.hot.on('stencil:hmr', function({ tagName }) {\n if (tagName === ${tag}) {\n var v = Date.now().toString(36);\n document.querySelectorAll(${tag}).forEach(function(el) { el['s-hmr'] && el['s-hmr'](v); });\n }\n });\n}`;
558
1146
  }
559
1147
  function makeResolver(onBaseClass) {
@@ -573,7 +1161,7 @@ function makeResolver(onBaseClass) {
573
1161
  /**
574
1162
  * Unplugin factory for @stencil/unplugin.
575
1163
  *
576
- * Wires together four concerns into a single plugin that works across Vite,
1164
+ * Wires together 6 concerns into a single plugin that works across Vite,
577
1165
  * Rollup, webpack, rspack, and bun:
578
1166
  *
579
1167
  * 1. **Component transform** - `transform` drives `transpileSync` on every
@@ -602,83 +1190,34 @@ function makeResolver(onBaseClass) {
602
1190
  * redirects every bare `@stencil/core` import to `@stencil/core/testing` via
603
1191
  * `resolveId`, so the whole test file - not just compiler output - resolves
604
1192
  * to a single platform instance.
605
- */
606
- const STENCIL_DOCS_ID = "@stencil/unplugin/docs";
607
- const VIRTUAL_DOCS_PREFIX = "\0stencil-docs:";
608
- const docsRegistry = /* @__PURE__ */ new Map();
609
- /**
610
- * Returns the current CEM. Only populated when `docs: true` is set.
611
- * @returns the current CEM, or an empty CEM if `docs: true` was not set.
612
- */
613
- function getStencilCEM() {
614
- return generateManifest({ components: [...docsRegistry.values()] });
615
- }
616
- /**
617
- * Recursively collect `.tsx`/`.ts` file paths under `dir`, pruning
618
- * `node_modules` and hidden directories (`.git`, `.vite`, etc.) as it goes.
619
1193
  *
620
- * `readdirSync(dir, { recursive: true })` can't prune during traversal - it
621
- * walks everything first and only lets the caller filter the flat result
622
- * afterward, which is disastrous under a symlink-heavy `node_modules` (e.g.
623
- * pnpm's `.pnpm` store, which flattens every dependency in the workspace) -
624
- * it can take minutes just to list, blocking `buildStart` the whole time.
1194
+ * 6. **Virtual global-stylesheet imports** - `@import "stencil-component-globals"`/
1195
+ * `"stencil-hydrate"`/`"stencil-css-components"` resolve to generated stylesheets (see
1196
+ * `global-css.ts`) via `resolveId`, or under Vite - which doesn't consult plugins for CSS
1197
+ * `@import` - via an alias. The bundler then treats them like any other CSS. `load` registers
1198
+ * their ingredient files (e.g. a component's `globalStyleUrl`) for watch mode;
1199
+ * `handleHotUpdate` regenerates them for Vite HMR.
625
1200
  *
626
- * @param dir the directory to walk
627
- * @param out accumulator array of absolute file paths, mutated in place
628
- */
629
- function collectSourceFiles(dir, out) {
630
- let entries;
631
- try {
632
- entries = readdirSync(dir, { withFileTypes: true });
633
- } catch {
634
- return;
635
- }
636
- for (const entry of entries) {
637
- if (entry.name === "node_modules" || entry.name.startsWith(".")) continue;
638
- const abs = join(dir, entry.name);
639
- if (entry.isDirectory()) collectSourceFiles(abs, out);
640
- else if (entry.isFile() && (abs.endsWith(".tsx") || abs.endsWith(".ts")) && !abs.endsWith(".d.ts")) out.push(abs);
641
- }
642
- }
643
- /**
644
- * Scan the project for component source files and pre-populate the docs registry.
645
- * @param filter A function to filter which files should be included.
646
- * @returns A promise that resolves when the scan is complete.
1201
+ * 7. **`components.d.ts`** - with `types: true`, written to `srcDir` from the project scan by
1202
+ * core's own generator (see `component-types.ts`), and rewritten as component sources change.
647
1203
  */
648
- async function scanDocs(filter) {
649
- const cwd = process.cwd();
650
- const allFiles = [];
651
- collectSourceFiles(cwd, allFiles);
652
- const files = allFiles.filter((abs) => filter(abs));
653
- await Promise.all(files.map(async (abs) => {
654
- let code;
655
- try {
656
- code = readFileSync(abs, "utf-8");
657
- } catch {
658
- return;
659
- }
660
- if (!/(@Component|@Prop|@State|@Event|@Method|@Watch|@Listen)\s*[(\s]/.test(code)) return;
661
- const result = await transpile(code, {
662
- file: abs,
663
- componentExport: "customelement"
664
- });
665
- for (const item of result.data ?? []) {
666
- if (!item.tagName) continue;
667
- const component = cmpMetaToDocsComponent(item, abs);
668
- resolveImportedTypes(component, abs);
669
- docsRegistry.set(item.tagName, component);
670
- }
671
- }));
672
- }
1204
+ const STENCIL_DOCS_ID = "@stencil/unplugin/docs";
1205
+ const VIRTUAL_DOCS_PREFIX = "\0stencil-docs:";
673
1206
  const VIRTUAL_BASE_PREFIX = "\0stencil-base:";
674
1207
  const SIGNALS_IMPORT_RE = /from\s+['"]@stencil\/core\/signals['"]/;
1208
+ const getModuleById = (server, id) => server.moduleGraph.getModuleById?.(id) ?? server.moduleGraph.idToModuleMap?.get(id);
1209
+ const invalidate = (server, mod) => server.moduleGraph.invalidateModule(mod, /* @__PURE__ */ new Set(), Date.now(), true);
1210
+ const toViteFilePath = (filePath) => filePath.replace(/\\/g, "/");
1211
+ const PLUGIN_NAME = "@stencil/unplugin";
675
1212
  const unpluginStencil = createUnplugin((options = {}, meta) => {
676
1213
  const { framework } = meta;
677
1214
  const filter = createFilter(options.include ?? [/\.tsx?$/], options.exclude ?? ["node_modules/**"]);
678
1215
  let isDev = options.dev ?? false;
1216
+ let foldFlags = !isDev && options.mode !== "spec-page";
679
1217
  let projectRoot = process.cwd();
680
1218
  let configOverrides = {};
681
1219
  const fileToTagName = /* @__PURE__ */ new Map();
1220
+ const tagToFile = /* @__PURE__ */ new Map();
682
1221
  const cssFileToTagNames = /* @__PURE__ */ new Map();
683
1222
  const cssRealToVirtualIds = /* @__PURE__ */ new Map();
684
1223
  function trackCssFile(realPath, tag, virtualId) {
@@ -692,22 +1231,177 @@ const unpluginStencil = createUnplugin((options = {}, meta) => {
692
1231
  if (baseClassRegistry.has(absPath)) return;
693
1232
  baseClassRegistry.set(absPath, transpileBaseClass(rawCode, absPath, options));
694
1233
  }
1234
+ let hydratedFlag = null;
1235
+ let typesConfig = null;
1236
+ let projectScanPromise = null;
1237
+ function ensureProjectScanned() {
1238
+ if (!projectScanPromise) projectScanPromise = scanDocs(filter, options.docs === true);
1239
+ return projectScanPromise;
1240
+ }
1241
+ async function loadConfig() {
1242
+ const detected = await loadStencilConfig(projectRoot);
1243
+ const merged = detected ? {
1244
+ ...detected,
1245
+ ...options.stencilConfig,
1246
+ compat: {
1247
+ ...detected.compat,
1248
+ ...options.stencilConfig?.compat
1249
+ }
1250
+ } : options.stencilConfig ?? {};
1251
+ configOverrides = stencilConfigToOverrides(merged);
1252
+ hydratedFlag = validateHydrated({ hydratedFlag: merged.hydratedFlag });
1253
+ typesConfig = {
1254
+ srcDir: resolve(projectRoot, merged.srcDir ?? "src"),
1255
+ signalBacking: !!merged.signalBacking
1256
+ };
1257
+ }
1258
+ let stencilConfigLoaded = null;
1259
+ const virtualCss = createVirtualGlobalCss(async () => {
1260
+ stencilConfigLoaded ??= loadConfig();
1261
+ await Promise.all([stencilConfigLoaded, ensureProjectScanned()]);
1262
+ return {
1263
+ componentGlobalStyles,
1264
+ cssOnlyComponentFiles,
1265
+ tagNames: getHydrateTagNames(docsRegistry.values()),
1266
+ hydratedFlag
1267
+ };
1268
+ }, () => isDev);
1269
+ /**
1270
+ * webpack/rspack: they read the generated stylesheets straight from disk (`load` never runs for
1271
+ * them), so this (re)writes them before every compile and makes their modules depend on the
1272
+ * ingredient files - otherwise an ingredient edit neither triggers a watch-mode rebuild nor
1273
+ * invalidates the cached stylesheet module. `src/` too, so a newly added CSS-only component
1274
+ * does - not the whole project root, where build output would trigger rebuilds in a loop.
1275
+ * @param compiler the webpack/rspack compiler
1276
+ */
1277
+ function watchVirtualCssForCompiles(compiler) {
1278
+ compiler.hooks.watchRun.tapPromise(PLUGIN_NAME, async ({ modifiedFiles, removedFiles }) => {
1279
+ if (!virtualCss.started) return;
1280
+ for (const file of [...modifiedFiles ?? [], ...removedFiles ?? []]) {
1281
+ await rescanIfCssOnlyComponent(file);
1282
+ await rescanNewCssOnlyComponents(file);
1283
+ }
1284
+ });
1285
+ compiler.hooks.beforeCompile.tapPromise(PLUGIN_NAME, () => virtualCss.forCompile(projectRoot));
1286
+ compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {
1287
+ const addIngredients = (resource, loaderContext) => {
1288
+ if (!resource || !virtualCss.isPath(resource)) return;
1289
+ for (const dep of virtualCss.deps) loaderContext.addDependency(dep);
1290
+ const srcDir = resolve(projectRoot, "src");
1291
+ if (existsSync(srcDir)) loaderContext.addContextDependency(srcDir);
1292
+ };
1293
+ const hooks = compiler.webpack.NormalModule.getCompilationHooks(compilation);
1294
+ if (hooks.beforeLoaders) hooks.beforeLoaders.tap(PLUGIN_NAME, (_loaders, module, ctx) => addIngredients(module.resource, ctx));
1295
+ else hooks.loader?.tap(PLUGIN_NAME, (ctx) => addIngredients(ctx.resourcePath, ctx));
1296
+ });
1297
+ }
1298
+ /**
1299
+ * `options.types`: bring the registries up to date with a changed file - a component source,
1300
+ * or a stylesheet that defines (or used to define) CSS-only components - then rewrite
1301
+ * `components.d.ts` if its content changed.
1302
+ * @param file the changed, added or deleted file
1303
+ */
1304
+ async function updateComponentTypes(file) {
1305
+ if (!options.types || !typesConfig) return;
1306
+ if (/\.tsx?$/.test(file) && !file.endsWith(".d.ts") && filter(file)) await refreshComponentMeta(file);
1307
+ else {
1308
+ await rescanIfCssOnlyComponent(file);
1309
+ await rescanNewCssOnlyComponents(file);
1310
+ }
1311
+ writeComponentTypes(typesConfig);
1312
+ }
1313
+ /**
1314
+ * Vite HMR: tell the client its docs changed, invalidating the docs virtual module.
1315
+ * @param server the dev server
1316
+ */
1317
+ function notifyDocsChanged(server) {
1318
+ const docsVirtualMod = getModuleById(server, VIRTUAL_DOCS_PREFIX);
1319
+ if (docsVirtualMod) invalidate(server, docsVirtualMod);
1320
+ server.ws.send({
1321
+ type: "custom",
1322
+ event: "stencil:docs-update"
1323
+ });
1324
+ }
1325
+ /**
1326
+ * Vite HMR, `docs` only: refresh docs affected by a changed stylesheet - a CSS-only
1327
+ * component's own file, or a regular component's linked `styleUrl`.
1328
+ * @param file the changed stylesheet
1329
+ * @param server the dev server
1330
+ */
1331
+ async function refreshDocsForStylesheet(file, server) {
1332
+ let code = "";
1333
+ try {
1334
+ code = readFileSync(file, "utf-8");
1335
+ } catch {}
1336
+ try {
1337
+ if (code.includes("@component") || isCssOnlyComponentFile(file)) {
1338
+ const prevSnapshot = JSON.stringify(getRegistrySnapshot());
1339
+ await scanCssOnlyDocsFile(file);
1340
+ if (JSON.stringify(getRegistrySnapshot()) !== prevSnapshot) notifyDocsChanged(server);
1341
+ } else {
1342
+ let anyChanged = false;
1343
+ for (const tag of cssFileToTagNames.get(file) ?? []) {
1344
+ const ownerFile = tagToFile.get(tag);
1345
+ if (ownerFile && await refreshComponentDocs(tag, ownerFile)) anyChanged = true;
1346
+ }
1347
+ if (anyChanged) notifyDocsChanged(server);
1348
+ }
1349
+ } catch {}
1350
+ }
1351
+ /**
1352
+ * Vite HMR: regenerate the virtual global stylesheets and hot-update whatever imports the ones
1353
+ * that changed. Vite doesn't watch them (under node_modules), so they're returned as HMR modules
1354
+ * - the documented pattern for hot-updating an untracked dependency.
1355
+ * @param file the changed file
1356
+ * @param server the dev server
1357
+ * @returns the modules to hot-update
1358
+ */
1359
+ async function hotUpdateVirtualCss(file, server) {
1360
+ if (virtualCss.started && !options.docs) await rescanIfCssOnlyComponent(file);
1361
+ const modules = [];
1362
+ for (const written of await virtualCss.hotUpdate(file)) for (const mod of server.moduleGraph.getModulesByFile?.(toViteFilePath(written)) ?? []) {
1363
+ invalidate(server, mod);
1364
+ modules.push(mod);
1365
+ }
1366
+ return modules;
1367
+ }
1368
+ /**
1369
+ * Vite HMR: send `stencil:hmr` for every component the changed file belongs to.
1370
+ * @param file the changed file
1371
+ * @param server the dev server
1372
+ * @returns whether the file belongs to any component
1373
+ */
1374
+ async function hotUpdateComponents(file, server) {
1375
+ const tsxTag = fileToTagName.get(file);
1376
+ const tagNames = new Set(cssFileToTagNames.get(file));
1377
+ if (tsxTag) tagNames.add(tsxTag);
1378
+ if (tagNames.size === 0) return false;
1379
+ for (const virtualId of cssRealToVirtualIds.get(file) ?? []) {
1380
+ const virtualMod = getModuleById(server, virtualId);
1381
+ if (virtualMod) invalidate(server, virtualMod);
1382
+ }
1383
+ if (options.docs && tsxTag && await refreshComponentDocs(tsxTag, file)) notifyDocsChanged(server);
1384
+ for (const tagName of tagNames) server.ws.send({
1385
+ type: "custom",
1386
+ event: "stencil:hmr",
1387
+ data: { tagName }
1388
+ });
1389
+ return true;
1390
+ }
695
1391
  return {
696
1392
  name: "@stencil/unplugin",
697
1393
  async buildStart() {
698
- const detected = await loadStencilConfig(projectRoot);
699
- configOverrides = stencilConfigToOverrides(detected ? {
700
- ...detected,
701
- ...options.stencilConfig,
702
- compat: {
703
- ...detected.compat,
704
- ...options.stencilConfig?.compat
705
- }
706
- } : options.stencilConfig ?? {});
707
- if (options.docs) await scanDocs(filter);
1394
+ stencilConfigLoaded = loadConfig();
1395
+ await stencilConfigLoaded;
1396
+ if (options.docs || options.types) await ensureProjectScanned();
1397
+ if (options.types && typesConfig) writeComponentTypes(typesConfig);
1398
+ virtualCss.useDefaultDir(projectRoot);
1399
+ if (framework === "vite") await virtualCss.forCompile(projectRoot);
708
1400
  },
709
1401
  async resolveId(id, importer) {
710
1402
  if (id === "@stencil/unplugin/docs") return VIRTUAL_DOCS_PREFIX;
1403
+ const virtualCssPath = await virtualCss.resolveId(id, importer);
1404
+ if (virtualCssPath) return virtualCssPath;
711
1405
  if (options.mode === "spec-page" && id === "@stencil/core") return this.resolve("@stencil/core/testing", importer, { skipSelf: true });
712
1406
  if (!importer) return null;
713
1407
  const css = resolveStencilCss(id, importer);
@@ -721,25 +1415,44 @@ const unpluginStencil = createUnplugin((options = {}, meta) => {
721
1415
  transformInclude(id) {
722
1416
  return filter(id.split("?")[0]);
723
1417
  },
724
- transform(code, id) {
1418
+ async transform(code, id, transformOpts) {
725
1419
  const cleanId = id.split("?")[0];
1420
+ const folded = foldFlags && !transformOpts?.ssr ? foldBuildFlags(code, cleanId, {
1421
+ isBrowser: true,
1422
+ isServer: false
1423
+ }) : null;
1424
+ if (folded !== null) code = folded;
726
1425
  if (!configOverrides.vdomSignals && SIGNALS_IMPORT_RE.test(code)) configOverrides = {
727
1426
  ...configOverrides,
728
1427
  vdomSignals: true
729
1428
  };
730
- const result = transformStencil(code, cleanId, options, isDev, framework, registerBaseClass, configOverrides);
731
- if (result?.tagName) fileToTagName.set(cleanId, result.tagName);
1429
+ const result = await transformStencil(code, cleanId, options, isDev, framework, registerBaseClass, configOverrides);
1430
+ if (result?.tagName) {
1431
+ fileToTagName.set(cleanId, result.tagName);
1432
+ tagToFile.set(result.tagName, cleanId);
1433
+ }
732
1434
  if (result?.docsComponent && options.docs) {
733
1435
  resolveImportedTypes(result.docsComponent, cleanId);
734
1436
  docsRegistry.set(result.docsComponent.tag, result.docsComponent);
735
1437
  }
736
- return result;
1438
+ return result ?? (folded !== null ? {
1439
+ code,
1440
+ map: null
1441
+ } : null);
737
1442
  },
738
1443
  loadInclude(id) {
739
- return id === VIRTUAL_DOCS_PREFIX || isStencilCss(id) || id.startsWith(VIRTUAL_BASE_PREFIX);
1444
+ return id === VIRTUAL_DOCS_PREFIX || isStencilCss(id) || id.startsWith(VIRTUAL_BASE_PREFIX) || virtualCss.isPath(id);
740
1445
  },
741
1446
  async load(id) {
742
1447
  if (id === VIRTUAL_DOCS_PREFIX) return `export default ${JSON.stringify(getStencilCEM())}`;
1448
+ if (virtualCss.isPath(id)) {
1449
+ const { code, deps } = await virtualCss.load(id);
1450
+ for (const dep of deps) this.addWatchFile(dep);
1451
+ return {
1452
+ code,
1453
+ map: null
1454
+ };
1455
+ }
743
1456
  if (id.startsWith(VIRTUAL_BASE_PREFIX)) {
744
1457
  const realPath = id.slice(14);
745
1458
  this.addWatchFile(realPath);
@@ -768,55 +1481,55 @@ const unpluginStencil = createUnplugin((options = {}, meta) => {
768
1481
  }
769
1482
  return null;
770
1483
  },
1484
+ async watchChange(id) {
1485
+ if (![
1486
+ "vite",
1487
+ "webpack",
1488
+ "rspack"
1489
+ ].includes(framework) && virtualCss.started) await rescanIfCssOnlyComponent(id);
1490
+ if (framework !== "vite") await updateComponentTypes(id);
1491
+ },
1492
+ webpack(compiler) {
1493
+ watchVirtualCssForCompiles(compiler);
1494
+ },
1495
+ rspack(compiler) {
1496
+ virtualCss.useDefaultDir(compiler.options.context ?? projectRoot);
1497
+ const alias = compiler.options.resolve.alias;
1498
+ compiler.options.resolve.alias = {
1499
+ ...alias && !Array.isArray(alias) ? alias : {},
1500
+ ...virtualGlobalStylesheetAliasMap(virtualCss.dir)
1501
+ };
1502
+ watchVirtualCssForCompiles(compiler);
1503
+ },
771
1504
  vite: {
772
1505
  enforce: "pre",
1506
+ config(userConfig, env) {
1507
+ virtualCss.setDir(resolve(userConfig.root ?? process.cwd(), "node_modules", ".stencil", "virtual-css", env.command));
1508
+ return { resolve: { alias: [virtualGlobalStylesheetAlias(virtualCss.dir)] } };
1509
+ },
773
1510
  configResolved(config) {
774
1511
  isDev = options.dev ?? config.command === "serve";
1512
+ foldFlags = config.command === "build" && options.mode !== "spec-page";
775
1513
  projectRoot = config.root;
776
1514
  },
777
- async handleHotUpdate({ file, server }) {
778
- const tsxTag = fileToTagName.get(file);
779
- const cssTagNames = cssFileToTagNames.get(file);
780
- const tagNames = new Set(cssTagNames);
781
- if (tsxTag) tagNames.add(tsxTag);
782
- if (tagNames.size === 0) return;
783
- const virtualIds = cssRealToVirtualIds.get(file);
784
- if (virtualIds) for (const virtualId of virtualIds) {
785
- const virtualMod = server.moduleGraph.getModuleById?.(virtualId) ?? server.moduleGraph.idToModuleMap?.get(virtualId);
786
- if (virtualMod) server.moduleGraph.invalidateModule(virtualMod, /* @__PURE__ */ new Set(), Date.now(), true);
787
- }
788
- if (options.docs && tsxTag) {
789
- let cemChanged = false;
790
- try {
791
- const prevSnapshot = JSON.stringify(docsRegistry.get(tsxTag));
792
- const code = readFileSync(file, "utf-8");
793
- const result = await transpile(code, {
794
- file,
795
- componentExport: "customelement"
796
- });
797
- for (const item of result.data ?? []) {
798
- if (!item.tagName) continue;
799
- const component = cmpMetaToDocsComponent(item, file);
800
- resolveImportedTypes(component, file);
801
- docsRegistry.set(item.tagName, component);
802
- }
803
- cemChanged = JSON.stringify(docsRegistry.get(tsxTag)) !== prevSnapshot;
804
- } catch {}
805
- if (cemChanged) {
806
- const docsVirtualMod = server.moduleGraph.getModuleById?.(VIRTUAL_DOCS_PREFIX) ?? server.moduleGraph.idToModuleMap?.get(VIRTUAL_DOCS_PREFIX);
807
- if (docsVirtualMod) server.moduleGraph.invalidateModule(docsVirtualMod, /* @__PURE__ */ new Set(), Date.now(), true);
808
- server.ws.send({
809
- type: "custom",
810
- event: "stencil:docs-update"
811
- });
1515
+ configureServer(server) {
1516
+ const onAddedOrDeleted = async (file) => {
1517
+ if (file.endsWith(".css")) {
1518
+ if (options.docs) await refreshDocsForStylesheet(file, server);
1519
+ for (const mod of await hotUpdateVirtualCss(file, server)) await server.reloadModule(mod);
812
1520
  }
813
- }
814
- for (const tagName of tagNames) server.ws.send({
815
- type: "custom",
816
- event: "stencil:hmr",
817
- data: { tagName }
818
- });
819
- return [];
1521
+ await updateComponentTypes(file);
1522
+ };
1523
+ server.watcher.on("add", onAddedOrDeleted);
1524
+ server.watcher.on("unlink", onAddedOrDeleted);
1525
+ },
1526
+ async handleHotUpdate({ file, server }) {
1527
+ if (options.docs && file.endsWith(".css")) await refreshDocsForStylesheet(file, server);
1528
+ const hmrModules = await hotUpdateVirtualCss(file, server);
1529
+ const isComponentFile = await hotUpdateComponents(file, server);
1530
+ await updateComponentTypes(file);
1531
+ if (!isComponentFile && hmrModules.length === 0) return void 0;
1532
+ return hmrModules;
820
1533
  }
821
1534
  }
822
1535
  };