@stencil/unplugin 5.0.0-alpha.16

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/README.md ADDED
@@ -0,0 +1,161 @@
1
+ # @stencil/unplugin
2
+
3
+ Universal bundler plugin for Stencil components — supports Vite, Rollup, Webpack, esbuild, and Rspack.
4
+
5
+ Lets you import and use Stencil components directly in any bundler without a full Stencil build pipeline. Each `.tsx` component file is transpiled on-the-fly via `transpileSync` into a self-registering custom element.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install --save-dev @stencil/unplugin @stencil/core
11
+ ```
12
+
13
+ Optional CSS preprocessors (install only what you need — the plugin silently skips any that aren't present):
14
+
15
+ ```bash
16
+ npm install --save-dev sass # .scss / .sass
17
+ npm install --save-dev less # .less
18
+ npm install --save-dev postcss postcss-load-config # PostCSS via postcss.config.*
19
+ npm install --save-dev lightningcss # syntax lowering, vendor prefixes, minification
20
+ ```
21
+
22
+ ## Usage
23
+
24
+ ### Vite
25
+
26
+ ```ts
27
+ // vite.config.ts
28
+ import { defineConfig } from 'vite';
29
+ import { stencilVite } from '@stencil/unplugin';
30
+
31
+ export default defineConfig({
32
+ plugins: [stencilVite()],
33
+ });
34
+ ```
35
+
36
+ ### Rollup
37
+
38
+ ```ts
39
+ // rollup.config.js
40
+ import { stencilRollup } from '@stencil/unplugin';
41
+
42
+ export default {
43
+ plugins: [stencilRollup()],
44
+ };
45
+ ```
46
+
47
+ ### Webpack
48
+
49
+ ```js
50
+ // webpack.config.js
51
+ const { stencilWebpack } = require('@stencil/unplugin');
52
+
53
+ module.exports = {
54
+ plugins: [stencilWebpack()],
55
+ };
56
+ ```
57
+
58
+ ### esbuild
59
+
60
+ ```ts
61
+ import { build } from 'esbuild';
62
+ import { stencilEsbuild } from '@stencil/unplugin';
63
+
64
+ await build({
65
+ plugins: [stencilEsbuild()],
66
+ });
67
+ ```
68
+
69
+ ### Rspack
70
+
71
+ ```js
72
+ // rspack.config.js
73
+ const { stencilRspack } = require('@stencil/unplugin');
74
+
75
+ module.exports = {
76
+ plugins: [stencilRspack()],
77
+ };
78
+ ```
79
+
80
+ ## Options
81
+
82
+ All options are optional.
83
+
84
+ ```ts
85
+ stencilVite({
86
+ // Glob/regex patterns of files to transform. Default: [/\.tsx?$/]
87
+ include: ['src/**/*.tsx'],
88
+
89
+ // Glob patterns to exclude. Default: ['node_modules/**']
90
+ exclude: ['**/*.spec.tsx'],
91
+
92
+ // Enable HMR injection. Auto-detected as true in Vite dev mode (command === 'serve').
93
+ // For webpack/rspack, set true explicitly when running webpack-dev-server or @rspack/dev-server.
94
+ dev: true,
95
+
96
+ // Opt in to docs scanning — see "Docs / CEM" section below.
97
+ docs: true,
98
+
99
+ // Extra options forwarded to transpileSync for every transformed file.
100
+ // The plugin manages: file, resolveImport, styleImportData, componentExport — don't set those here.
101
+ transpileOptions: {
102
+ sourceMap: true,
103
+ },
104
+ });
105
+ ```
106
+
107
+ | Option | Default | Description |
108
+ |---|---|---|
109
+ | `include` | `[/\.tsx?$/]` | Files to consider for transformation |
110
+ | `exclude` | `['node_modules/**']` | Files to skip |
111
+ | `dev` | `false` (auto in Vite) | Inject HMR client code into component output |
112
+ | `docs` | `false` | Scan and accumulate component metadata for docs/CEM |
113
+ | `transpileOptions` | — | Passed through to `transpileSync` (see `TranspileOptions`) |
114
+
115
+ ## How it works
116
+
117
+ ### Component transform
118
+
119
+ Only files containing Stencil decorators (`@Component`, `@Prop`, `@State`, etc.) are transformed. Everything else passes through untouched.
120
+
121
+ Matching files are compiled with `componentExport: 'customelement'`, which means each component self-registers via `customElements.define` (if not already defined) when the module is imported — no separate registration step needed.
122
+
123
+ ### CSS pipeline
124
+
125
+ Stencil emits style imports with query parameters (e.g. `./my-comp.css?tag=my-comp&encapsulation=shadow`). The plugin intercepts these and runs them through the following pipeline (each step only runs if the peer dep is installed):
126
+
127
+ 1. **Sass / Less** — compile `.scss`, `.sass`, or `.less` to CSS
128
+ 2. **PostCSS** — process with `postcss.config.*` if found in the project
129
+ 3. **lightningcss** — syntax lowering, vendor prefixes; minification in production
130
+ 4. **Scoped rewrite** — scope-prefix selectors for `encapsulation: 'scoped'` components
131
+
132
+ ### HMR
133
+
134
+ - **Vite**: a `stencil:hmr` WebSocket event is sent when a component file changes. Existing instances in the page are patched in-place without a full reload.
135
+ - **Webpack / Rspack**: uses the `module.hot` re-execution pattern — new class prototype methods are patched onto live instances.
136
+ - Set `dev: true` explicitly for webpack/rspack dev servers; Vite auto-detects it.
137
+
138
+ ## Docs / Custom Elements Manifest
139
+
140
+ When `docs: true` is set, the plugin scans all component files at build start and accumulates `JsonDocsComponent` metadata as each file is transformed. The aggregate CEM is exposed as a virtual module:
141
+
142
+ ```ts
143
+ // In your app or Storybook preset:
144
+ import cem from '@stencil/unplugin/docs';
145
+
146
+ console.log(cem.modules); // Custom Elements Manifest
147
+ ```
148
+
149
+ You can also access the CEM programmatically at any point (e.g. from a Node.js build script):
150
+
151
+ ```ts
152
+ import { getStencilCEM, STENCIL_DOCS_ID } from '@stencil/unplugin';
153
+
154
+ // After the build/transform has run:
155
+ const manifest = getStencilCEM();
156
+
157
+ // STENCIL_DOCS_ID is the virtual module specifier: '@stencil/unplugin/docs'
158
+ console.log(STENCIL_DOCS_ID);
159
+ ```
160
+
161
+ `getStencilCEM()` returns an empty CEM if `docs: true` was not set on the plugin.
@@ -0,0 +1,7 @@
1
+ import { CustomElementsManifest } from "@stencil/core/compiler";
2
+
3
+ //#region src/docs.d.ts
4
+ declare const _default: CustomElementsManifest;
5
+ //#endregion
6
+ export { _default as default };
7
+ //# sourceMappingURL=docs.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"docs.d.mts","names":[],"sources":["../src/docs.ts"],"mappings":";;;cAIqE,QAAA,EAEhD,sBAAsB"}
package/dist/docs.mjs ADDED
@@ -0,0 +1,6 @@
1
+ //#region src/docs.ts
2
+ var docs_default = {};
3
+ //#endregion
4
+ export { docs_default as default };
5
+
6
+ //# sourceMappingURL=docs.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"docs.mjs","names":[],"sources":["../src/docs.ts"],"sourcesContent":["// Replaced at runtime by the @stencil/unplugin virtual module when the plugin\n// is active (e.g. vite resolveId intercepts '@stencil/unplugin/docs' > '\\0stencil-docs:').\n// This stub exists to provide types and a safe fallback for non-Vite contexts.\n\nimport type { CustomElementsManifest } from '@stencil/core/compiler';\n\nexport default {} as CustomElementsManifest;\n"],"mappings":";AAMA,IAAA,eAAe,CAAC"}
@@ -0,0 +1,74 @@
1
+ import { ConfigCompat, CustomElementsManifest, StencilConfig, TranspileOptions } from "@stencil/core/compiler";
2
+
3
+ //#region src/options.d.ts
4
+ type TranspileCompatKeys = 'lightDomPatches' | 'lifecycleDOMEvents' | 'initializeNextTick';
5
+ /**
6
+ * The subset of `stencil.config.ts` fields that affect transpilation.
7
+ * Derived from {@link StencilConfig} and {@link ConfigCompat} — no parallel docs to maintain.
8
+ *
9
+ * Auto-populated from the project's `stencil.config.ts`; values set here override the auto-detected ones.
10
+ */
11
+ type StencilConfigSubset = Pick<StencilConfig, 'signalBacking'> & {
12
+ compat?: Pick<ConfigCompat, TranspileCompatKeys>;
13
+ };
14
+ interface StencilPluginOptions {
15
+ /**
16
+ * Additional options forwarded to `transpileSync` for every `.tsx`/`.ts` file.
17
+ * `file`, `resolveImport`, `styleImportData`, and `componentExport` are
18
+ * managed by the plugin and should not be set here.
19
+ */
20
+ transpileOptions?: Omit<TranspileOptions, 'file' | 'resolveImport' | 'styleImportData' | 'componentExport'>;
21
+ /**
22
+ * Glob patterns (relative to the project root) for files to include.
23
+ * Defaults to `['**\/*.tsx']`.
24
+ */
25
+ include?: string[];
26
+ /**
27
+ * Glob patterns to exclude. Defaults to `['node_modules/**']`.
28
+ */
29
+ exclude?: string[];
30
+ /**
31
+ * Enable HMR client code injection. Automatically `true` in Vite dev mode
32
+ * (`command === 'serve'`). For webpack/rspack, set this explicitly when
33
+ * running with `webpack-dev-server` or `@rspack/dev-server`.
34
+ */
35
+ dev?: boolean;
36
+ /**
37
+ * When `true`, the plugin scans all component source files at build start and
38
+ * accumulates per-component `JsonDocsComponent` metadata. The aggregate is
39
+ * exposed via the `@stencil/unplugin/docs` virtual module and the
40
+ * `getStencilDocs()` helper.
41
+ *
42
+ * Off by default — opt in only when you need docs output (e.g. in a Storybook
43
+ * preset) to avoid paying the startup scan cost for non-docs builds.
44
+ */
45
+ docs?: boolean;
46
+ /**
47
+ * Stencil config flags that affect transpilation. The plugin automatically
48
+ * detects and reads `stencil.config.ts` from the project root — set this only
49
+ * to override specific values from the auto-detected config.
50
+ *
51
+ * Precedence (highest wins):
52
+ * `transpileOptions.buildOverrides` > `stencilConfig` > auto-detected config
53
+ */
54
+ stencilConfig?: StencilConfigSubset;
55
+ }
56
+ //#endregion
57
+ //#region src/plugin.d.ts
58
+ declare const STENCIL_DOCS_ID = "@stencil/unplugin/docs";
59
+ /**
60
+ * Returns the current CEM. Only populated when `docs: true` is set.
61
+ * @returns the current CEM, or an empty CEM if `docs: true` was not set.
62
+ */
63
+ declare function getStencilCEM(): CustomElementsManifest;
64
+ declare const unpluginStencil: import("unplugin").UnpluginInstance<StencilPluginOptions | undefined, boolean>;
65
+ //#endregion
66
+ //#region src/index.d.ts
67
+ declare const stencilVite: (options?: StencilPluginOptions | undefined) => import("unplugin").VitePlugin<any> | import("unplugin").VitePlugin<any>[];
68
+ declare const stencilRollup: (options?: StencilPluginOptions | undefined) => import("unplugin").RollupPlugin<any> | import("unplugin").RollupPlugin<any>[];
69
+ declare const stencilWebpack: (options?: StencilPluginOptions | undefined) => WebpackPluginInstance;
70
+ declare const stencilEsbuild: (options?: StencilPluginOptions | undefined) => import("unplugin").EsbuildPlugin;
71
+ declare const stencilRspack: (options?: StencilPluginOptions | undefined) => RspackPluginInstance;
72
+ //#endregion
73
+ export { STENCIL_DOCS_ID, type StencilPluginOptions, getStencilCEM, stencilEsbuild, stencilRollup, stencilRspack, stencilVite, stencilWebpack, unpluginStencil };
74
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/options.ts","../src/plugin.ts","../src/index.ts"],"mappings":";;;KAEK,mBAAA;;AAFuF;;;;AAEpE;KAQZ,mBAAA,GAAsB,IAAA,CAAK,aAAA;EACrC,MAAA,GAAS,IAAA,CAAK,YAAA,EAAc,mBAAA;AAAA;AAAA,UAGb,oBAAA;EAJiB;;;;;EAUhC,gBAAA,GAAmB,IAAA,CACjB,gBAAA;EAX8B;;;;EAmBhC,OAAA;EAlB4B;;AAAmB;EAuB/C,OAAA;EApBmC;;;;;EA2BnC,GAAA;EAqBmC;;;;;;;;;EAVnC,IAAA;EAUmC;AAAA;;;;ACjBrC;;;EDiBE,aAAA,GAAgB,mBAAA;AAAA;;;cCjBL,eAAA;AD7C+E;;;;AAAA,iBCwD5E,aAAA,CAAA,GAAiB,sBAAsB;AAAA,cAkD1C,eAAA,qBAAe,gBAAA,CAAA,oBAAA;;;cCrGf,WAAA,GAAW,OAAA,GAAuB,oBAAvB,oCAAA,UAAA,2BAAA,UAAA;AAAA,cACX,aAAA,GAAa,OAAA,GAAyB,oBAAzB,oCAAA,YAAA,2BAAA,YAAA;AAAA,cACb,cAAA,GAAc,OAAA,GAA0B,oBAAA,iBAA1B,qBAA0B;AAAA,cACxC,cAAA,GAAc,OAAA,GAA0B,oBAA1B,oCAAA,aAAA;AAAA,cACd,aAAA,GAAa,OAAA,GAAyB,oBAAA,iBAAzB,oBAAyB"}
package/dist/index.mjs ADDED
@@ -0,0 +1,773 @@
1
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
2
+ import { dirname, extname, join, resolve } from "node:path";
3
+ import { createFilter } from "@rollup/pluginutils";
4
+ import { cmpMetaToDocsComponent, generateManifest, getScopeId, scopeCss, transpile, transpileSync } from "@stencil/core/compiler";
5
+ import { createUnplugin } from "unplugin";
6
+ import { fileURLToPath } from "node:url";
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 = 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
+ //#region src/css.ts
112
+ /**
113
+ * CSS pipeline for Stencil component stylesheets.
114
+ *
115
+ * When the Stencil compiler emits a style import such as
116
+ * `./foo.css?tag=my-cmp&encapsulation=shadow`, `resolveStencilCss` rewrites it
117
+ * to a `\0stencil-css:` virtual module ID. The bundler then calls `load`, which
118
+ * reads the real file and runs it through any installed preprocessors in order:
119
+ * Sass/Less → PostCSS → lightningcss → scoped-selector rewrite (for scoped
120
+ * encapsulation). The result is returned as `export default () => "…css…"` so
121
+ * the bundler treats it as a normal JS module dependency.
122
+ *
123
+ * Each preprocessor step is silently skipped if the relevant peer dep is absent.
124
+ */
125
+ const STENCIL_CSS_RE = /\.(?:css|scss|sass|less|styl)\?[^/]*\btag=/;
126
+ const STENCIL_CSS_PREFIX = "\0stencil-css:";
127
+ const PKG = {
128
+ sass: isPackageExists("sass"),
129
+ less: isPackageExists("less"),
130
+ postcss: isPackageExists("postcss") && isPackageExists("postcss-load-config"),
131
+ lightningcss: isPackageExists("lightningcss")
132
+ };
133
+ /**
134
+ * Rewrites a Stencil CSS import to a `\0stencil-css:` virtual module ID.
135
+ * The file extension is stored dotless as `__ext` so Vite's `CSS_LANGS_RE`
136
+ * never matches the virtual ID and tries to own the module itself.
137
+ * @param specifier - the raw import specifier from the component source
138
+ * @param importer - absolute path of the importing file
139
+ * @returns virtual module ID, or `null` for non-Stencil CSS imports
140
+ */
141
+ function resolveStencilCss(specifier, importer) {
142
+ if (!STENCIL_CSS_RE.test(specifier)) return null;
143
+ const [base, query] = specifier.split("?");
144
+ const absBase = resolve(dirname(importer), base);
145
+ const ext = extname(absBase);
146
+ return `${STENCIL_CSS_PREFIX}${absBase.slice(0, absBase.length - ext.length)}?${query}&__ext=${encodeURIComponent(ext.slice(1))}`;
147
+ }
148
+ function isStencilCss(id) {
149
+ return id.startsWith(STENCIL_CSS_PREFIX);
150
+ }
151
+ /**
152
+ * Extracts the real CSS file path from a `\0stencil-css:` virtual module ID.
153
+ * @param id - virtual module ID produced by `resolveStencilCss`
154
+ * @returns absolute file path, or `null` if not a Stencil CSS virtual module
155
+ */
156
+ function getRealCssPath(id) {
157
+ if (!id.startsWith(STENCIL_CSS_PREFIX)) return null;
158
+ const withoutPrefix = id.slice(13);
159
+ const qIdx = withoutPrefix.indexOf("?");
160
+ const stem = qIdx === -1 ? withoutPrefix : withoutPrefix.slice(0, qIdx);
161
+ const query = qIdx === -1 ? "" : withoutPrefix.slice(qIdx + 1);
162
+ return `${stem}.${decodeURIComponent(new URLSearchParams(query).get("__ext") ?? "css")}`;
163
+ }
164
+ async function compileSass(source, filePath, indented) {
165
+ const sass = await import("sass");
166
+ const mainUrl = `file://${filePath}`;
167
+ const result = sass.compileString(source, {
168
+ url: new URL(mainUrl),
169
+ syntax: indented ? "indented" : "scss"
170
+ });
171
+ const deps = result.loadedUrls.filter((u) => u.protocol === "file:" && u.href !== mainUrl).map((u) => fileURLToPath(u));
172
+ return {
173
+ css: result.css,
174
+ deps
175
+ };
176
+ }
177
+ async function compileLess(source, filePath) {
178
+ const result = await (await import("less")).default.render(source, {
179
+ filename: filePath,
180
+ paths: [dirname(filePath)]
181
+ });
182
+ return {
183
+ css: result.css,
184
+ deps: result.imports ?? []
185
+ };
186
+ }
187
+ const postcssConfigCache = /* @__PURE__ */ new Map();
188
+ async function runPostCss(css, filePath) {
189
+ const dir = dirname(filePath);
190
+ let config = postcssConfigCache.get(dir);
191
+ if (config === void 0) {
192
+ try {
193
+ const { default: loadConfig } = await import("postcss-load-config");
194
+ const loaded = await loadConfig({}, dir);
195
+ config = {
196
+ plugins: loaded.plugins,
197
+ options: loaded.options
198
+ };
199
+ } catch {
200
+ config = null;
201
+ }
202
+ postcssConfigCache.set(dir, config);
203
+ }
204
+ if (!config?.plugins.length) return css;
205
+ const { default: postcss } = await import("postcss");
206
+ return (await postcss(config.plugins).process(css, {
207
+ ...config.options,
208
+ from: filePath
209
+ })).css;
210
+ }
211
+ async function runLightningCss(css, filePath, minify) {
212
+ const { transform } = await import("lightningcss");
213
+ return transform({
214
+ filename: filePath,
215
+ code: Buffer.from(css),
216
+ minify
217
+ }).code.toString();
218
+ }
219
+ /**
220
+ * Loads a Stencil CSS virtual module.
221
+ *
222
+ * Processing order:
223
+ * 1. Read raw file
224
+ * 2. Preprocessor: Sass/SCSS (`sass`) or Less (`less`) if installed
225
+ * 3. PostCSS with `postcss.config.*` if `postcss` + `postcss-load-config` are installed
226
+ * 4. lightningcss if installed — syntax lowering, vendor prefixes, minification in prod
227
+ * 5. Scoped selector rewrite for `encapsulation: 'scoped'`
228
+ *
229
+ * Each step is skipped silently if the relevant peer dep is not installed.
230
+ * Returns `export default "css string"` so bundlers treat the import as a JS module.
231
+ * @param id - virtual module id produced by `resolveStencilCss`
232
+ * @param isDev - `true` in dev mode (disables minification)
233
+ * @returns ESM string export of the processed CSS, or `null` if not a Stencil CSS virtual module
234
+ */
235
+ async function loadStencilCss(id, isDev = true) {
236
+ if (!id.startsWith(STENCIL_CSS_PREFIX)) return null;
237
+ const withoutPrefix = id.slice(13);
238
+ const qIdx = withoutPrefix.indexOf("?");
239
+ const stem = qIdx === -1 ? withoutPrefix : withoutPrefix.slice(0, qIdx);
240
+ const query = qIdx === -1 ? "" : withoutPrefix.slice(qIdx + 1);
241
+ const params = new URLSearchParams(query);
242
+ const tag = params.get("tag") ?? "";
243
+ const encapsulation = params.get("encapsulation") ?? "none";
244
+ const ext = decodeURIComponent(params.get("__ext") ?? "css");
245
+ const filePath = `${stem}.${ext}`;
246
+ if (!existsSync(filePath)) return {
247
+ code: "export default () => \"\"",
248
+ deps: []
249
+ };
250
+ let css = readFileSync(filePath, "utf-8");
251
+ let deps = [];
252
+ if (PKG.sass && (ext === "scss" || ext === "sass")) {
253
+ const r = await compileSass(css, filePath, ext === "sass");
254
+ css = r.css;
255
+ deps = r.deps;
256
+ } else if (PKG.less && ext === "less") {
257
+ const r = await compileLess(css, filePath);
258
+ css = r.css;
259
+ deps = r.deps;
260
+ }
261
+ if (PKG.postcss) css = await runPostCss(css, filePath);
262
+ if (PKG.lightningcss) css = await runLightningCss(css, filePath, !isDev);
263
+ if (encapsulation === "scoped" && tag) css = scopeCss(css, getScopeId(tag), false);
264
+ return {
265
+ code: `export default () => ${JSON.stringify(css)};`,
266
+ deps
267
+ };
268
+ }
269
+ //#endregion
270
+ //#region src/resolve-types.ts
271
+ /**
272
+ * Resolves imported type references in CEM docs components.
273
+ *
274
+ * `transpileSync` uses a single-file TypeScript host, so imported types (e.g.
275
+ * `ButtonVariant` from `'../types'`) can't be followed — `complexType.resolved`
276
+ * ends up as `"any"`. This module creates a minimal ts.Program per referenced
277
+ * types file (cached) and substitutes the actual expanded type text back into
278
+ * the component's doc data before it enters the registry.
279
+ */
280
+ const TYPE_FORMAT_FLAGS = ts.TypeFormatFlags.NoTruncation | ts.TypeFormatFlags.InTypeAlias | ts.TypeFormatFlags.InElementType;
281
+ const typesFileCache = /* @__PURE__ */ new Map();
282
+ function resolveTypesFilePath(specifier, fromDir) {
283
+ const base = resolve(fromDir, specifier);
284
+ if (existsSync(base)) return base;
285
+ for (const ext of [
286
+ ".ts",
287
+ ".tsx",
288
+ ".d.ts"
289
+ ]) {
290
+ const candidate = base + ext;
291
+ if (existsSync(candidate)) return candidate;
292
+ }
293
+ }
294
+ function getTypesFileEntry(absPath) {
295
+ const cached = typesFileCache.get(absPath);
296
+ if (cached) return cached;
297
+ const options = {
298
+ ...ts.getDefaultCompilerOptions(),
299
+ noEmit: true,
300
+ module: ts.ModuleKind.ESNext,
301
+ moduleResolution: ts.ModuleResolutionKind.Bundler
302
+ };
303
+ const program = ts.createProgram([absPath], options);
304
+ const checker = program.getTypeChecker();
305
+ const sourceFile = program.getSourceFile(absPath);
306
+ const exportTypes = /* @__PURE__ */ new Map();
307
+ if (sourceFile) {
308
+ const moduleSymbol = checker.getSymbolAtLocation(sourceFile);
309
+ if (moduleSymbol) for (const symbol of checker.getExportsOfModule(moduleSymbol)) exportTypes.set(symbol.name, checker.getDeclaredTypeOfSymbol(symbol));
310
+ }
311
+ const entry = {
312
+ checker,
313
+ exportTypes
314
+ };
315
+ typesFileCache.set(absPath, entry);
316
+ return entry;
317
+ }
318
+ function expandTypeName(typeName, references, fromDir) {
319
+ const ref = references[typeName];
320
+ if (!ref || ref.location !== "import" || !ref.path) return void 0;
321
+ const absPath = resolveTypesFilePath(ref.path, fromDir);
322
+ if (!absPath) return void 0;
323
+ const { checker, exportTypes } = getTypesFileEntry(absPath);
324
+ const type = exportTypes.get(typeName);
325
+ if (!type) return void 0;
326
+ return checker.typeToString(type, void 0, TYPE_FORMAT_FLAGS);
327
+ }
328
+ const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
329
+ function patchType(original, references, fromDir) {
330
+ if (!references) return original;
331
+ let result = original;
332
+ for (const typeName of Object.keys(references)) {
333
+ const expanded = expandTypeName(typeName, references, fromDir);
334
+ if (!expanded || expanded === typeName) continue;
335
+ result = result.replace(new RegExp(`\\b${escapeRegExp(typeName)}\\b`, "g"), expanded.includes("|") || expanded.includes("&") ? `(${expanded})` : expanded);
336
+ }
337
+ return result;
338
+ }
339
+ /**
340
+ * Patches `prop.type` and `event.detail` in-place for any imported types that
341
+ * resolved to `"any"` in single-file transpile mode.
342
+ * @param component The CEM docs component to patch
343
+ * @param componentAbsPath The absolute path to the component's source file (used to resolve relative imports)
344
+ */
345
+ function resolveImportedTypes(component, componentAbsPath) {
346
+ const dir = dirname(componentAbsPath);
347
+ for (const prop of component.props) {
348
+ if (prop.type !== "any" || !prop.complexType?.references) continue;
349
+ const patched = patchType(prop.complexType.original, prop.complexType.references, dir);
350
+ if (patched !== prop.complexType.original) prop.type = patched;
351
+ }
352
+ for (const event of component.events) {
353
+ if (event.detail !== "any" || !event.complexType?.references) continue;
354
+ const patched = patchType(event.complexType.original, event.complexType.references, dir);
355
+ if (patched !== event.complexType.original) event.detail = patched;
356
+ }
357
+ }
358
+ //#endregion
359
+ //#region src/transform.ts
360
+ /**
361
+ * Component transpilation and base-class discovery.
362
+ *
363
+ * `transformStencil` is the main entry point: it calls `transpileSync` with
364
+ * `componentExport: 'customelement'` so each component self-registers when
365
+ * imported. Two code paths come out:
366
+ *
367
+ * - **Component** (`@Component` present): full customelement output with
368
+ * `defineCustomElement`, optional HMR snippet appended in dev mode.
369
+ * - **Decorated base class** (`@Prop`/`@State`/etc. but no `@Component`):
370
+ * returned as-is — the compiler's `isStencilBaseClass` check already injects
371
+ * `extends HTMLElement` via `updateNativeBaseClass`.
372
+ *
373
+ * `makeResolver` supplies the `resolveImport` callback that `transpileSync`
374
+ * uses during metadata collection. It serves two purposes at once: returning
375
+ * raw source so the compiler can merge inherited props/states into the
376
+ * component's metadata, and calling `onBaseClass` so the plugin can
377
+ * pre-transform and cache the file before the bundler's resolveId hook fires.
378
+ */
379
+ const SOURCE_EXTS = [
380
+ ".tsx",
381
+ ".ts",
382
+ ".js"
383
+ ];
384
+ const JSX_EMIT = {
385
+ react: 2,
386
+ "react-jsx": 4,
387
+ "react-jsxdev": 5,
388
+ preserve: 1,
389
+ "react-native": 3
390
+ };
391
+ let cachedTsConfigJsx;
392
+ function readJsxOptsFromTsConfig(cwd) {
393
+ if (cachedTsConfigJsx !== void 0) return cachedTsConfigJsx;
394
+ const tsconfigPath = join(cwd, "tsconfig.json");
395
+ if (!existsSync(tsconfigPath)) return cachedTsConfigJsx = {};
396
+ try {
397
+ const stripped = readFileSync(tsconfigPath, "utf-8").replace(/\/\/[^\n]*/g, "").replace(/\/\*[\s\S]*?\*\//g, "");
398
+ const co = JSON.parse(stripped)?.compilerOptions ?? {};
399
+ const jsxStr = co.jsx?.toLowerCase();
400
+ if (jsxStr && jsxStr in JSX_EMIT) return cachedTsConfigJsx = {
401
+ jsx: JSX_EMIT[jsxStr],
402
+ jsxImportSource: co.jsxImportSource
403
+ };
404
+ } catch {}
405
+ return cachedTsConfigJsx = {};
406
+ }
407
+ const IMPORTS_H_RE = /import\s+\{[^}]*\bh\b[^}]*\}\s+from\s+['"]@stencil\/core['"]/;
408
+ function resolveJsxOpts(code, cwd) {
409
+ const fromTsConfig = readJsxOptsFromTsConfig(cwd);
410
+ if (fromTsConfig.jsx !== void 0) return fromTsConfig;
411
+ if (IMPORTS_H_RE.test(code)) return { jsx: JSX_EMIT["react"] };
412
+ return {
413
+ jsx: JSX_EMIT["react-jsx"],
414
+ jsxImportSource: "@stencil/core"
415
+ };
416
+ }
417
+ /**
418
+ * Resolve an import specifier to an absolute path, trying source extensions
419
+ * and the TypeScript ESM `.js` → `.ts`/`.tsx` remap.
420
+ * @param specifier - the import specifier (relative or extensionless)
421
+ * @param importer - absolute path of the importing file
422
+ * @returns absolute path to the resolved file, or `null` if nothing found on disk
423
+ */
424
+ function resolveSpecifier(specifier, importer) {
425
+ const base = resolve(dirname(importer), specifier);
426
+ const norm = (p) => p.replace(/\\/g, "/");
427
+ if (existsSync(base)) return norm(base);
428
+ for (const ext of SOURCE_EXTS) {
429
+ const candidate = base + ext;
430
+ if (existsSync(candidate)) return norm(candidate);
431
+ }
432
+ if (base.endsWith(".js")) {
433
+ const stem = base.slice(0, -3);
434
+ for (const ext of [".ts", ".tsx"]) {
435
+ const candidate = stem + ext;
436
+ if (existsSync(candidate)) return norm(candidate);
437
+ }
438
+ }
439
+ return null;
440
+ }
441
+ /**
442
+ * Transpile a `.tsx`/`.ts` file for use in a bundler.
443
+ *
444
+ * Returns `{ code, map, tagName }` for Stencil component or base-class files,
445
+ * `null` for everything else (plain TS utilities, non-TS files, etc.).
446
+ * `tagName` is empty string for base classes with no `@Component`.
447
+ *
448
+ * `onBaseClass` is called for every file the compiler resolves via
449
+ * `resolveImport` during metadata collection. The plugin uses this to
450
+ * pre-transform those files before the bundler's resolveId hook fires.
451
+ * @param code - source file contents
452
+ * @param id - absolute file path
453
+ * @param options - plugin options
454
+ * @param dev - `true` in dev/watch mode (enables HMR snippet)
455
+ * @param framework - active unplugin framework
456
+ * @param onBaseClass - called for each file in the inheritance chain with its abs path and raw source
457
+ * @param configOverrides - pass stencil config option overrides to the transpiler
458
+ * @returns transformed output, or `null` if the file is not a Stencil file
459
+ */
460
+ function transformStencil(code, id, options, dev = false, framework = "", onBaseClass, configOverrides) {
461
+ if (!id.endsWith(".tsx") && !id.endsWith(".ts")) return null;
462
+ if (id.endsWith(".d.ts")) return null;
463
+ if (!/(@Component|@Prop|@State|@Event|@Method|@Watch|@Listen)\s*[(\s]/.test(code)) return null;
464
+ const result = transpileSync(code, {
465
+ ...resolveJsxOpts(code, process.cwd()),
466
+ ...options.transpileOptions,
467
+ file: id,
468
+ componentExport: "customelement",
469
+ styleImportData: "queryparams",
470
+ resolveImport: makeResolver(onBaseClass),
471
+ buildOverrides: {
472
+ ...configOverrides,
473
+ ...options.transpileOptions?.buildOverrides,
474
+ ...dev ? {
475
+ hotModuleReplacement: true,
476
+ isDev: true
477
+ } : {}
478
+ }
479
+ });
480
+ if (result.diagnostics.some((d) => d.level === "error")) {
481
+ const msgs = result.diagnostics.filter((d) => d.level === "error").map((d) => d.messageText).join("\n");
482
+ throw new Error(`[@stencil/unplugin] transpile error in ${id}:\n${msgs}`);
483
+ }
484
+ if (!result.data?.length) {
485
+ if (!/@Component\s*[(\s]/.test(code)) return {
486
+ code: result.code,
487
+ map: result.map ?? null,
488
+ tagName: "",
489
+ docsComponent: null
490
+ };
491
+ return null;
492
+ }
493
+ const tagName = result.data[0].tagName;
494
+ const className = result.data[0].componentClassName;
495
+ const devExport = dev ? `\nexport{${className}};` : "";
496
+ const out = dev ? result.code + devExport + buildHmrSnippet(tagName, className, framework) : result.code;
497
+ const docsComponent = cmpMetaToDocsComponent(result.data[0], id);
498
+ return {
499
+ code: out,
500
+ map: result.map ?? null,
501
+ tagName,
502
+ docsComponent
503
+ };
504
+ }
505
+ /**
506
+ * Transpile a base-class file with `transformAsBaseClass: true` so the
507
+ * compiler injects `extends HTMLElement` into any class without an existing
508
+ * heritage clause, regardless of whether it carries Stencil decorators.
509
+ *
510
+ * The result is cached in `baseClassRegistry` (in plugin.ts) and served as a
511
+ * virtual module, ensuring the bundler always sees the injected version even
512
+ * for plain lifecycle-only classes that the `transform` hook would otherwise skip.
513
+ * @param rawCode - raw source of the base-class file
514
+ * @param absPath - absolute path to the file (used as `file` for source maps)
515
+ * @param options - plugin options forwarded to `transpileSync`
516
+ * @returns compiled JS output
517
+ */
518
+ function transpileBaseClass(rawCode, absPath, options) {
519
+ return transpileSync(rawCode, {
520
+ ...options.transpileOptions,
521
+ file: absPath,
522
+ componentExport: "customelement",
523
+ styleImportData: "queryparams",
524
+ transformAsBaseClass: true
525
+ }).code;
526
+ }
527
+ function buildHmrSnippet(tagName, className, framework) {
528
+ const tag = JSON.stringify(tagName);
529
+ 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}`;
530
+ 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}`;
531
+ }
532
+ function makeResolver(onBaseClass) {
533
+ return (specifier, currentImporter) => {
534
+ const absPath = resolveSpecifier(specifier, currentImporter);
535
+ if (!absPath) return null;
536
+ const code = readFileSync(absPath, "utf-8");
537
+ onBaseClass?.(absPath, code);
538
+ return {
539
+ code,
540
+ path: absPath
541
+ };
542
+ };
543
+ }
544
+ //#endregion
545
+ //#region src/plugin.ts
546
+ /**
547
+ * Unplugin factory for @stencil/unplugin.
548
+ *
549
+ * Wires together four concerns into a single plugin that works across Vite,
550
+ * Rollup, webpack, rspack, and bun:
551
+ *
552
+ * 1. **Component transform** — `transform` drives `transpileSync` on every
553
+ * `.tsx`/`.ts` file that carries Stencil decorators, producing
554
+ * `customelement` output (self-registering class + `defineCustomElement`).
555
+ *
556
+ * 2. **CSS virtual modules** — Stencil emits `./foo.css?tag=my-cmp&…`
557
+ * imports. `resolveId` rewrites these to `\0stencil-css:` virtual IDs;
558
+ * `load` reads the real file, runs it through any installed preprocessors,
559
+ * and returns `export default () => "…css…"`.
560
+ *
561
+ * 3. **Base-class inheritance** — when a component extends a class that does
562
+ * not itself extend `HTMLElement`, the custom-element registration breaks.
563
+ * The plugin intercepts every file the compiler resolves via `resolveImport`
564
+ * (during `transpileSync`), pre-transforms it with `transformAsBaseClass: true`
565
+ * so it gets `extends HTMLElement`, and caches the result. `resolveId` then
566
+ * redirects imports of those files to `\0stencil-base:` virtual modules so
567
+ * the bundler always sees the injected version — regardless of module-graph
568
+ * processing order.
569
+ *
570
+ * 4. **HMR** — Vite receives a custom `stencil:hmr` WebSocket event when a
571
+ * component file changes; other bundlers use the `module.hot` re-execution
572
+ * pattern. CSS changes are covered automatically by `addWatchFile`.
573
+ */
574
+ const STENCIL_DOCS_ID = "@stencil/unplugin/docs";
575
+ const VIRTUAL_DOCS_PREFIX = "\0stencil-docs:";
576
+ const docsRegistry = /* @__PURE__ */ new Map();
577
+ /**
578
+ * Returns the current CEM. Only populated when `docs: true` is set.
579
+ * @returns the current CEM, or an empty CEM if `docs: true` was not set.
580
+ */
581
+ function getStencilCEM() {
582
+ return generateManifest({ components: [...docsRegistry.values()] });
583
+ }
584
+ /**
585
+ * Scan the project for component source files and pre-populate the docs registry.
586
+ * @param filter A function to filter which files should be included.
587
+ * @returns A promise that resolves when the scan is complete.
588
+ */
589
+ async function scanDocs(filter) {
590
+ const cwd = process.cwd();
591
+ let entries;
592
+ try {
593
+ entries = readdirSync(cwd, {
594
+ recursive: true,
595
+ encoding: "utf-8"
596
+ });
597
+ } catch {
598
+ return;
599
+ }
600
+ const files = entries.filter((rel) => (rel.endsWith(".tsx") || rel.endsWith(".ts")) && !rel.endsWith(".d.ts")).map((rel) => join(cwd, rel)).filter((abs) => filter(abs));
601
+ await Promise.all(files.map(async (abs) => {
602
+ let code;
603
+ try {
604
+ code = readFileSync(abs, "utf-8");
605
+ } catch {
606
+ return;
607
+ }
608
+ if (!/(@Component|@Prop|@State|@Event|@Method|@Watch|@Listen)\s*[(\s]/.test(code)) return;
609
+ const result = await transpile(code, {
610
+ file: abs,
611
+ componentExport: "customelement"
612
+ });
613
+ for (const item of result.data ?? []) {
614
+ if (!item.tagName) continue;
615
+ const component = cmpMetaToDocsComponent(item, abs);
616
+ resolveImportedTypes(component, abs);
617
+ docsRegistry.set(item.tagName, component);
618
+ }
619
+ }));
620
+ }
621
+ const VIRTUAL_BASE_PREFIX = "\0stencil-base:";
622
+ const SIGNALS_IMPORT_RE = /from\s+['"]@stencil\/core\/signals['"]/;
623
+ const unpluginStencil = createUnplugin((options = {}, meta) => {
624
+ const { framework } = meta;
625
+ const filter = createFilter(options.include ?? [/\.tsx?$/], options.exclude ?? ["node_modules/**"]);
626
+ let isDev = options.dev ?? false;
627
+ let projectRoot = process.cwd();
628
+ let configOverrides = {};
629
+ const fileToTagName = /* @__PURE__ */ new Map();
630
+ const cssFileToTagName = /* @__PURE__ */ new Map();
631
+ const cssRealToVirtualId = /* @__PURE__ */ new Map();
632
+ const baseClassRegistry = /* @__PURE__ */ new Map();
633
+ function registerBaseClass(absPath, rawCode) {
634
+ if (baseClassRegistry.has(absPath)) return;
635
+ baseClassRegistry.set(absPath, transpileBaseClass(rawCode, absPath, options));
636
+ }
637
+ return {
638
+ name: "@stencil/unplugin",
639
+ async buildStart() {
640
+ const detected = await loadStencilConfig(projectRoot);
641
+ configOverrides = stencilConfigToOverrides(detected ? {
642
+ ...detected,
643
+ ...options.stencilConfig,
644
+ compat: {
645
+ ...detected.compat,
646
+ ...options.stencilConfig?.compat
647
+ }
648
+ } : options.stencilConfig ?? {});
649
+ if (options.docs) await scanDocs(filter);
650
+ },
651
+ resolveId(id, importer) {
652
+ if (id === "@stencil/unplugin/docs") return VIRTUAL_DOCS_PREFIX;
653
+ if (!importer) return null;
654
+ const css = resolveStencilCss(id, importer);
655
+ if (css) return css;
656
+ if (baseClassRegistry.size > 0) {
657
+ const abs = resolveSpecifier(id, importer.startsWith(VIRTUAL_BASE_PREFIX) ? importer.slice(14) : importer);
658
+ if (abs && baseClassRegistry.has(abs)) return VIRTUAL_BASE_PREFIX + abs;
659
+ }
660
+ return null;
661
+ },
662
+ transformInclude(id) {
663
+ return filter(id.split("?")[0]);
664
+ },
665
+ transform(code, id) {
666
+ const cleanId = id.split("?")[0];
667
+ if (!configOverrides.vdomSignals && SIGNALS_IMPORT_RE.test(code)) configOverrides = {
668
+ ...configOverrides,
669
+ vdomSignals: true
670
+ };
671
+ const result = transformStencil(code, cleanId, options, isDev, framework, registerBaseClass, configOverrides);
672
+ if (result?.tagName) fileToTagName.set(cleanId, result.tagName);
673
+ if (result?.docsComponent && options.docs) {
674
+ resolveImportedTypes(result.docsComponent, cleanId);
675
+ docsRegistry.set(result.docsComponent.tag, result.docsComponent);
676
+ }
677
+ return result;
678
+ },
679
+ loadInclude(id) {
680
+ return id === VIRTUAL_DOCS_PREFIX || isStencilCss(id) || id.startsWith(VIRTUAL_BASE_PREFIX);
681
+ },
682
+ async load(id) {
683
+ if (id === VIRTUAL_DOCS_PREFIX) return `export default ${JSON.stringify(getStencilCEM())}`;
684
+ if (id.startsWith(VIRTUAL_BASE_PREFIX)) {
685
+ const realPath = id.slice(14);
686
+ this.addWatchFile(realPath);
687
+ return {
688
+ code: baseClassRegistry.get(realPath) ?? "",
689
+ map: null
690
+ };
691
+ }
692
+ const realPath = getRealCssPath(id);
693
+ const qIdx = id.indexOf("?");
694
+ const tag = qIdx !== -1 ? new URLSearchParams(id.slice(qIdx + 1)).get("tag") : null;
695
+ if (realPath) {
696
+ this.addWatchFile(realPath);
697
+ if (tag) cssFileToTagName.set(realPath, tag);
698
+ cssRealToVirtualId.set(realPath, id);
699
+ }
700
+ const cssResult = await loadStencilCss(id, isDev);
701
+ if (cssResult) {
702
+ if (tag) for (const dep of cssResult.deps) {
703
+ this.addWatchFile(dep);
704
+ cssFileToTagName.set(dep, tag);
705
+ cssRealToVirtualId.set(dep, id);
706
+ }
707
+ return {
708
+ code: cssResult.code,
709
+ map: null
710
+ };
711
+ }
712
+ return null;
713
+ },
714
+ vite: {
715
+ enforce: "pre",
716
+ configResolved(config) {
717
+ isDev = options.dev ?? config.command === "serve";
718
+ projectRoot = config.root;
719
+ },
720
+ async handleHotUpdate({ file, server }) {
721
+ const tagName = fileToTagName.get(file) ?? cssFileToTagName.get(file);
722
+ if (!tagName) return;
723
+ const virtualId = cssRealToVirtualId.get(file);
724
+ if (virtualId) {
725
+ const virtualMod = server.moduleGraph.getModuleById?.(virtualId) ?? server.moduleGraph.idToModuleMap?.get(virtualId);
726
+ if (virtualMod) server.moduleGraph.invalidateModule(virtualMod, /* @__PURE__ */ new Set(), Date.now(), true);
727
+ }
728
+ if (options.docs && fileToTagName.has(file)) {
729
+ let cemChanged = false;
730
+ try {
731
+ const prevSnapshot = JSON.stringify(docsRegistry.get(tagName));
732
+ const result = await transpile(readFileSync(file, "utf-8"), {
733
+ file,
734
+ componentExport: "customelement"
735
+ });
736
+ for (const item of result.data ?? []) {
737
+ if (!item.tagName) continue;
738
+ const component = cmpMetaToDocsComponent(item, file);
739
+ resolveImportedTypes(component, file);
740
+ docsRegistry.set(item.tagName, component);
741
+ }
742
+ cemChanged = JSON.stringify(docsRegistry.get(tagName)) !== prevSnapshot;
743
+ } catch {}
744
+ if (cemChanged) {
745
+ const docsVirtualMod = server.moduleGraph.getModuleById?.(VIRTUAL_DOCS_PREFIX) ?? server.moduleGraph.idToModuleMap?.get(VIRTUAL_DOCS_PREFIX);
746
+ if (docsVirtualMod) server.moduleGraph.invalidateModule(docsVirtualMod, /* @__PURE__ */ new Set(), Date.now(), true);
747
+ server.ws.send({
748
+ type: "custom",
749
+ event: "stencil:docs-update"
750
+ });
751
+ }
752
+ }
753
+ server.ws.send({
754
+ type: "custom",
755
+ event: "stencil:hmr",
756
+ data: { tagName }
757
+ });
758
+ return [];
759
+ }
760
+ }
761
+ };
762
+ });
763
+ //#endregion
764
+ //#region src/index.ts
765
+ const stencilVite = unpluginStencil.vite;
766
+ const stencilRollup = unpluginStencil.rollup;
767
+ const stencilWebpack = unpluginStencil.webpack;
768
+ const stencilEsbuild = unpluginStencil.esbuild;
769
+ const stencilRspack = unpluginStencil.rspack;
770
+ //#endregion
771
+ export { STENCIL_DOCS_ID, getStencilCEM, stencilEsbuild, stencilRollup, stencilRspack, stencilVite, stencilWebpack, unpluginStencil };
772
+
773
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/config.ts","../src/css.ts","../src/resolve-types.ts","../src/transform.ts","../src/plugin.ts","../src/index.ts"],"sourcesContent":["/**\n * Stencil config auto-detection for @stencil/unplugin.\n *\n * Searches for a `stencil.config.ts` (or `.js` variant) in the project root,\n * loads it via jiti (so TypeScript is handled without a separate compile step),\n * and extracts the subset of flags that are meaningful at transpile time.\n *\n * `stencilConfigToOverrides` converts that subset to a `BuildOverrides` object\n * ready to pass to `transpileSync`.\n */\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { BuildOverrides, LightDomPatches } from '@stencil/core/compiler';\n\nimport type { StencilConfigSubset } from './options.js';\n\n// A real Stencil config always has at least one of these keys. Used to\n// distinguish an actual default-exported config from jiti's CJS interop\n// artefact where the module namespace itself lands on `mod.default`.\nconst STENCIL_CONFIG_KEYS = new Set([\n 'namespace',\n 'srcDir',\n 'outputTargets',\n 'plugins',\n 'signalBacking',\n 'compat',\n]);\n\nconst looksLikeConfig = (v: unknown): v is Record<string, unknown> =>\n v !== null &&\n typeof v === 'object' &&\n !Array.isArray(v) &&\n Object.keys(v as object).some((k) => STENCIL_CONFIG_KEYS.has(k));\n\nconst CONFIG_CANDIDATES = [\n 'stencil.config.ts',\n 'stencil.config.mts',\n 'stencil.config.js',\n 'stencil.config.mjs',\n];\n\n/**\n * Attempt to load the project's `stencil.config.ts` and return the\n * transpile-relevant fields. Returns `null` if no config file is found or\n * if loading fails for any reason.\n * @param cwd - project root to search in (usually `process.cwd()`)\n * @returns a subset of the Stencil config, or `null` if none is found\n */\nexport async function loadStencilConfig(cwd: string): Promise<StencilConfigSubset | null> {\n for (const filename of CONFIG_CANDIDATES) {\n const configPath = join(cwd, filename);\n if (!existsSync(configPath)) continue;\n try {\n const { createJiti } = await import('jiti');\n const jiti = createJiti(import.meta.url);\n const mod = (await jiti.import(configPath)) as Record<string, unknown>;\n // Named `config` export is the Stencil convention; fall back to a default\n // export only when it looks like a real config object (has at least one\n // known Stencil key) — otherwise jiti's CJS interop may surface the\n // module namespace object as `default`, which we must not treat as config.\n const raw = mod['config'] ?? (looksLikeConfig(mod['default']) ? mod['default'] : null);\n if (!raw || typeof raw !== 'object') return null;\n return extractSubset(raw as Record<string, unknown>);\n } catch {\n return null;\n }\n }\n return null;\n}\n\nfunction extractSubset(c: Record<string, unknown>): StencilConfigSubset {\n const result: StencilConfigSubset = {};\n if (c['signalBacking'] === true) result.signalBacking = true;\n const compat = c['compat'];\n if (compat && typeof compat === 'object') {\n const co = compat as Record<string, unknown>;\n const ldp = co['lightDomPatches'];\n const lifecycleDOMEvents = co['lifecycleDOMEvents'];\n const initializeNextTick = co['initializeNextTick'];\n if (ldp !== undefined || lifecycleDOMEvents !== undefined || initializeNextTick !== undefined) {\n result.compat = {};\n if (typeof ldp === 'boolean') result.compat.lightDomPatches = ldp;\n else if (ldp && typeof ldp === 'object')\n result.compat.lightDomPatches = ldp as LightDomPatches;\n if (lifecycleDOMEvents === true) result.compat.lifecycleDOMEvents = true;\n if (initializeNextTick === true) result.compat.initializeNextTick = true;\n }\n }\n return result;\n}\n\n/**\n * Convert a {@link StencilConfigSubset} to a {@link BuildOverrides} object.\n * The caller is responsible for merging this with any explicit\n * `transpileOptions.buildOverrides` (which should take precedence).\n * @param config - the Stencil config subset to convert\n * @returns a `BuildOverrides` object suitable for passing to `transpileSync`\n */\nexport function stencilConfigToOverrides(config: StencilConfigSubset): BuildOverrides {\n const o: BuildOverrides = {};\n if (config.signalBacking) {\n o.signalBacking = true;\n o.vdomSignals = true; // signalBacking implies vdomSignals\n }\n\n const compat = config.compat;\n if (!compat) return o;\n if (compat.lifecycleDOMEvents) o.lifecycleDOMEvents = true;\n if (compat.initializeNextTick) o.initializeNextTick = true;\n\n const ldp = compat.lightDomPatches;\n if (ldp === false) {\n // Explicitly disable — standalone runtime defaults all to true.\n o.lightDomPatches = false;\n o.slotChildNodes = false;\n o.slotCloneNode = false;\n o.slotDomMutations = false;\n o.slotTextContent = false;\n } else if (typeof ldp === 'object') {\n // Granular: enable only the named patches; disable the rest (defaults are all-true).\n o.lightDomPatches = true;\n o.slotChildNodes = !!ldp.childNodes;\n o.slotCloneNode = !!ldp.cloneNode;\n o.slotDomMutations = !!ldp.domMutations;\n o.slotTextContent = !!ldp.textContent;\n }\n // ldp === true or undefined: no-op — already the default in the standalone runtime.\n return o;\n}\n","/**\n * CSS pipeline for Stencil component stylesheets.\n *\n * When the Stencil compiler emits a style import such as\n * `./foo.css?tag=my-cmp&encapsulation=shadow`, `resolveStencilCss` rewrites it\n * to a `\\0stencil-css:` virtual module ID. The bundler then calls `load`, which\n * reads the real file and runs it through any installed preprocessors in order:\n * Sass/Less → PostCSS → lightningcss → scoped-selector rewrite (for scoped\n * encapsulation). The result is returned as `export default () => \"…css…\"` so\n * the bundler treats it as a normal JS module dependency.\n *\n * Each preprocessor step is silently skipped if the relevant peer dep is absent.\n */\nimport { existsSync, readFileSync } from 'node:fs';\nimport { dirname, extname, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { getScopeId, scopeCss } from '@stencil/core/compiler';\nimport { isPackageExists } from 'local-pkg';\n\n// Matches Stencil's emitted style imports: `./foo.css?tag=my-cmp&…`\nconst STENCIL_CSS_RE = /\\.(?:css|scss|sass|less|styl)\\?[^/]*\\btag=/;\nconst STENCIL_CSS_PREFIX = '\\0stencil-css:';\n\n// Evaluated once at startup — avoids repeated filesystem probes per CSS file.\nconst PKG = {\n sass: isPackageExists('sass'),\n less: isPackageExists('less'),\n postcss: isPackageExists('postcss') && isPackageExists('postcss-load-config'),\n lightningcss: isPackageExists('lightningcss'),\n};\n\n/**\n * Rewrites a Stencil CSS import to a `\\0stencil-css:` virtual module ID.\n * The file extension is stored dotless as `__ext` so Vite's `CSS_LANGS_RE`\n * never matches the virtual ID and tries to own the module itself.\n * @param specifier - the raw import specifier from the component source\n * @param importer - absolute path of the importing file\n * @returns virtual module ID, or `null` for non-Stencil CSS imports\n */\nexport function resolveStencilCss(specifier: string, importer: string): string | null {\n if (!STENCIL_CSS_RE.test(specifier)) return null;\n const [base, query] = specifier.split('?');\n const absBase = resolve(dirname(importer), base);\n const ext = extname(absBase);\n const stem = absBase.slice(0, absBase.length - ext.length);\n return `${STENCIL_CSS_PREFIX}${stem}?${query}&__ext=${encodeURIComponent(ext.slice(1))}`;\n}\n\nexport function isStencilCss(id: string): boolean {\n return id.startsWith(STENCIL_CSS_PREFIX);\n}\n\n/**\n * Extracts the real CSS file path from a `\\0stencil-css:` virtual module ID.\n * @param id - virtual module ID produced by `resolveStencilCss`\n * @returns absolute file path, or `null` if not a Stencil CSS virtual module\n */\nexport function getRealCssPath(id: string): string | null {\n if (!id.startsWith(STENCIL_CSS_PREFIX)) return null;\n const withoutPrefix = id.slice(STENCIL_CSS_PREFIX.length);\n const qIdx = withoutPrefix.indexOf('?');\n const stem = qIdx === -1 ? withoutPrefix : withoutPrefix.slice(0, qIdx);\n const query = qIdx === -1 ? '' : withoutPrefix.slice(qIdx + 1);\n const ext = decodeURIComponent(new URLSearchParams(query).get('__ext') ?? 'css');\n return `${stem}.${ext}`;\n}\n\nasync function compileSass(\n source: string,\n filePath: string,\n indented: boolean,\n): Promise<{ css: string; deps: string[] }> {\n const sass = await import('sass');\n const mainUrl = `file://${filePath}`;\n const result = sass.compileString(source, {\n url: new URL(mainUrl),\n syntax: indented ? 'indented' : 'scss',\n });\n const deps = result.loadedUrls\n .filter((u) => u.protocol === 'file:' && u.href !== mainUrl)\n .map((u) => fileURLToPath(u));\n return { css: result.css, deps };\n}\n\nasync function compileLess(\n source: string,\n filePath: string,\n): Promise<{ css: string; deps: string[] }> {\n const less = await import('less');\n const result = await less.default.render(source, {\n filename: filePath,\n paths: [dirname(filePath)],\n });\n return { css: result.css, deps: result.imports ?? [] };\n}\n\n// Cache PostCSS config per directory to avoid repeated filesystem lookups.\nconst postcssConfigCache = new Map<\n string,\n { plugins: unknown[]; options: Record<string, unknown> } | null\n>();\n\nasync function runPostCss(css: string, filePath: string): Promise<string> {\n const dir = dirname(filePath);\n let config = postcssConfigCache.get(dir);\n\n if (config === undefined) {\n try {\n const { default: loadConfig } = await import('postcss-load-config');\n const loaded = await loadConfig({}, dir);\n config = {\n plugins: loaded.plugins as unknown[],\n options: loaded.options as Record<string, unknown>,\n };\n } catch {\n config = null;\n }\n postcssConfigCache.set(dir, config);\n }\n\n if (!config?.plugins.length) return css;\n\n const { default: postcss } = await import('postcss');\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result = await postcss(config.plugins as any[]).process(css, {\n ...config.options,\n from: filePath,\n });\n return result.css;\n}\n\nasync function runLightningCss(css: string, filePath: string, minify: boolean): Promise<string> {\n const { transform } = await import('lightningcss');\n const result = transform({\n filename: filePath,\n code: Buffer.from(css),\n minify,\n });\n return result.code.toString();\n}\n\n/**\n * Loads a Stencil CSS virtual module.\n *\n * Processing order:\n * 1. Read raw file\n * 2. Preprocessor: Sass/SCSS (`sass`) or Less (`less`) if installed\n * 3. PostCSS with `postcss.config.*` if `postcss` + `postcss-load-config` are installed\n * 4. lightningcss if installed — syntax lowering, vendor prefixes, minification in prod\n * 5. Scoped selector rewrite for `encapsulation: 'scoped'`\n *\n * Each step is skipped silently if the relevant peer dep is not installed.\n * Returns `export default \"css string\"` so bundlers treat the import as a JS module.\n * @param id - virtual module id produced by `resolveStencilCss`\n * @param isDev - `true` in dev mode (disables minification)\n * @returns ESM string export of the processed CSS, or `null` if not a Stencil CSS virtual module\n */\nexport async function loadStencilCss(\n id: string,\n isDev = true,\n): Promise<{ code: string; deps: string[] } | null> {\n if (!id.startsWith(STENCIL_CSS_PREFIX)) return null;\n\n const withoutPrefix = id.slice(STENCIL_CSS_PREFIX.length);\n const qIdx = withoutPrefix.indexOf('?');\n const stem = qIdx === -1 ? withoutPrefix : withoutPrefix.slice(0, qIdx);\n const query = qIdx === -1 ? '' : withoutPrefix.slice(qIdx + 1);\n const params = new URLSearchParams(query);\n const tag = params.get('tag') ?? '';\n const encapsulation = params.get('encapsulation') ?? 'none';\n const ext = decodeURIComponent(params.get('__ext') ?? 'css');\n const filePath = `${stem}.${ext}`;\n\n if (!existsSync(filePath)) return { code: 'export default () => \"\"', deps: [] };\n\n let css = readFileSync(filePath, 'utf-8');\n let deps: string[] = [];\n\n if (PKG.sass && (ext === 'scss' || ext === 'sass')) {\n const r = await compileSass(css, filePath, ext === 'sass');\n css = r.css;\n deps = r.deps;\n } else if (PKG.less && ext === 'less') {\n const r = await compileLess(css, filePath);\n css = r.css;\n deps = r.deps;\n }\n\n if (PKG.postcss) css = await runPostCss(css, filePath);\n if (PKG.lightningcss) css = await runLightningCss(css, filePath, !isDev);\n\n if (encapsulation === 'scoped' && tag) {\n css = scopeCss(css, getScopeId(tag), false);\n }\n\n return { code: `export default () => ${JSON.stringify(css)};`, deps };\n}\n","/**\n * Resolves imported type references in CEM docs components.\n *\n * `transpileSync` uses a single-file TypeScript host, so imported types (e.g.\n * `ButtonVariant` from `'../types'`) can't be followed — `complexType.resolved`\n * ends up as `\"any\"`. This module creates a minimal ts.Program per referenced\n * types file (cached) and substitutes the actual expanded type text back into\n * the component's doc data before it enters the registry.\n */\nimport { existsSync } from 'node:fs';\nimport { dirname, resolve } from 'node:path';\nimport ts from 'typescript';\nimport type { ComponentCompilerTypeReferences, JsonDocsComponent } from '@stencil/core/compiler';\n\nconst TYPE_FORMAT_FLAGS =\n ts.TypeFormatFlags.NoTruncation |\n ts.TypeFormatFlags.InTypeAlias |\n ts.TypeFormatFlags.InElementType;\n\ninterface TypesFileEntry {\n checker: ts.TypeChecker;\n exportTypes: Map<string, ts.Type>;\n}\n\nconst typesFileCache = new Map<string, TypesFileEntry>();\n\nfunction resolveTypesFilePath(specifier: string, fromDir: string): string | undefined {\n const base = resolve(fromDir, specifier);\n if (existsSync(base)) return base;\n for (const ext of ['.ts', '.tsx', '.d.ts']) {\n const candidate = base + ext;\n if (existsSync(candidate)) return candidate;\n }\n return undefined;\n}\n\nfunction getTypesFileEntry(absPath: string): TypesFileEntry {\n const cached = typesFileCache.get(absPath);\n if (cached) return cached;\n\n const options: ts.CompilerOptions = {\n ...ts.getDefaultCompilerOptions(),\n noEmit: true,\n module: ts.ModuleKind.ESNext,\n moduleResolution: ts.ModuleResolutionKind.Bundler,\n };\n const program = ts.createProgram([absPath], options);\n const checker = program.getTypeChecker();\n const sourceFile = program.getSourceFile(absPath);\n const exportTypes = new Map<string, ts.Type>();\n\n if (sourceFile) {\n const moduleSymbol = checker.getSymbolAtLocation(sourceFile);\n if (moduleSymbol) {\n for (const symbol of checker.getExportsOfModule(moduleSymbol)) {\n exportTypes.set(symbol.name, checker.getDeclaredTypeOfSymbol(symbol));\n }\n }\n }\n\n const entry: TypesFileEntry = { checker, exportTypes };\n typesFileCache.set(absPath, entry);\n return entry;\n}\n\nfunction expandTypeName(\n typeName: string,\n references: ComponentCompilerTypeReferences,\n fromDir: string,\n): string | undefined {\n const ref = references[typeName];\n if (!ref || ref.location !== 'import' || !ref.path) return undefined;\n\n const absPath = resolveTypesFilePath(ref.path, fromDir);\n if (!absPath) return undefined;\n\n const { checker, exportTypes } = getTypesFileEntry(absPath);\n const type = exportTypes.get(typeName);\n if (!type) return undefined;\n\n return checker.typeToString(type, undefined, TYPE_FORMAT_FLAGS);\n}\n\nconst escapeRegExp = (s: string) => s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\nfunction patchType(\n original: string,\n references: ComponentCompilerTypeReferences | undefined,\n fromDir: string,\n): string {\n if (!references) return original;\n let result = original;\n for (const typeName of Object.keys(references)) {\n const expanded = expandTypeName(typeName, references, fromDir);\n if (!expanded || expanded === typeName) continue;\n // Wrap in parens when substituting into a potentially larger expression\n // e.g. `ButtonVariant | undefined` → `('sm' | 'md') | undefined`\n result = result.replace(\n new RegExp(`\\\\b${escapeRegExp(typeName)}\\\\b`, 'g'),\n expanded.includes('|') || expanded.includes('&') ? `(${expanded})` : expanded,\n );\n }\n return result;\n}\n\n/**\n * Patches `prop.type` and `event.detail` in-place for any imported types that\n * resolved to `\"any\"` in single-file transpile mode.\n * @param component The CEM docs component to patch\n * @param componentAbsPath The absolute path to the component's source file (used to resolve relative imports)\n */\nexport function resolveImportedTypes(component: JsonDocsComponent, componentAbsPath: string): void {\n const dir = dirname(componentAbsPath);\n\n for (const prop of component.props) {\n if (prop.type !== 'any' || !prop.complexType?.references) continue;\n const patched = patchType(prop.complexType.original, prop.complexType.references, dir);\n if (patched !== prop.complexType.original) prop.type = patched;\n }\n\n for (const event of component.events) {\n if (event.detail !== 'any' || !event.complexType?.references) continue;\n const patched = patchType(event.complexType.original, event.complexType.references, dir);\n if (patched !== event.complexType.original) event.detail = patched;\n }\n}\n","/**\n * Component transpilation and base-class discovery.\n *\n * `transformStencil` is the main entry point: it calls `transpileSync` with\n * `componentExport: 'customelement'` so each component self-registers when\n * imported. Two code paths come out:\n *\n * - **Component** (`@Component` present): full customelement output with\n * `defineCustomElement`, optional HMR snippet appended in dev mode.\n * - **Decorated base class** (`@Prop`/`@State`/etc. but no `@Component`):\n * returned as-is — the compiler's `isStencilBaseClass` check already injects\n * `extends HTMLElement` via `updateNativeBaseClass`.\n *\n * `makeResolver` supplies the `resolveImport` callback that `transpileSync`\n * uses during metadata collection. It serves two purposes at once: returning\n * raw source so the compiler can merge inherited props/states into the\n * component's metadata, and calling `onBaseClass` so the plugin can\n * pre-transform and cache the file before the bundler's resolveId hook fires.\n */\nimport { existsSync, readFileSync } from 'node:fs';\nimport { dirname, join, resolve } from 'node:path';\nimport { cmpMetaToDocsComponent, transpileSync } from '@stencil/core/compiler';\nimport type { BuildOverrides, JsonDocsComponent } from '@stencil/core/compiler';\nimport type { SupportedFramework } from 'unplugin';\n\nimport type { StencilPluginOptions } from './options.js';\n\nconst SOURCE_EXTS = ['.tsx', '.ts', '.js'];\n\n// TypeScript JsxEmit enum values — stable across TS versions.\nconst JSX_EMIT: Record<string, number> = {\n react: 2,\n 'react-jsx': 4,\n 'react-jsxdev': 5,\n preserve: 1,\n 'react-native': 3,\n};\n\ntype JsxOpts = { jsx?: number; jsxImportSource?: string };\n\nlet cachedTsConfigJsx: JsxOpts | undefined;\n\nfunction readJsxOptsFromTsConfig(cwd: string): JsxOpts {\n if (cachedTsConfigJsx !== undefined) return cachedTsConfigJsx;\n const tsconfigPath = join(cwd, 'tsconfig.json');\n if (!existsSync(tsconfigPath)) return (cachedTsConfigJsx = {});\n try {\n const raw = readFileSync(tsconfigPath, 'utf-8');\n const stripped = raw.replace(/\\/\\/[^\\n]*/g, '').replace(/\\/\\*[\\s\\S]*?\\*\\//g, '');\n const tsconfig = JSON.parse(stripped);\n const co = tsconfig?.compilerOptions ?? {};\n const jsxStr: string | undefined = co.jsx?.toLowerCase();\n if (jsxStr && jsxStr in JSX_EMIT) {\n return (cachedTsConfigJsx = {\n jsx: JSX_EMIT[jsxStr],\n jsxImportSource: co.jsxImportSource,\n });\n }\n } catch {\n // ignore unreadable / malformed tsconfig\n }\n return (cachedTsConfigJsx = {});\n}\n\n// Detects classic JSX mode: `import { …, h, … } from '@stencil/core'`\nconst IMPORTS_H_RE = /import\\s+\\{[^}]*\\bh\\b[^}]*\\}\\s+from\\s+['\"]@stencil\\/core['\"]/;\n\n/* Resolve jsx/jsxImportSource for transpileSync.\n * Priority: tsconfig.json > source heuristic (h import → classic; otherwise automatic runtime). */\nfunction resolveJsxOpts(code: string, cwd: string): JsxOpts {\n const fromTsConfig = readJsxOptsFromTsConfig(cwd);\n if (fromTsConfig.jsx !== undefined) return fromTsConfig;\n if (IMPORTS_H_RE.test(code)) {\n return { jsx: JSX_EMIT['react'] }; // jsxFactory: 'h' auto-applied by transpile-module\n }\n return { jsx: JSX_EMIT['react-jsx'], jsxImportSource: '@stencil/core' };\n}\n\n/**\n * Resolve an import specifier to an absolute path, trying source extensions\n * and the TypeScript ESM `.js` → `.ts`/`.tsx` remap.\n * @param specifier - the import specifier (relative or extensionless)\n * @param importer - absolute path of the importing file\n * @returns absolute path to the resolved file, or `null` if nothing found on disk\n */\nexport function resolveSpecifier(specifier: string, importer: string): string | null {\n const base = resolve(dirname(importer), specifier);\n // Vite normalizes module IDs to forward slashes; we must match that so\n // virtual-module keys stay consistent on Windows.\n const norm = (p: string) => p.replace(/\\\\/g, '/');\n\n if (existsSync(base)) return norm(base);\n\n for (const ext of SOURCE_EXTS) {\n const candidate = base + ext;\n if (existsSync(candidate)) return norm(candidate);\n }\n\n // TypeScript ESM: `./foo.js` may physically be `./foo.ts` or `./foo.tsx`\n if (base.endsWith('.js')) {\n const stem = base.slice(0, -3);\n for (const ext of ['.ts', '.tsx']) {\n const candidate = stem + ext;\n if (existsSync(candidate)) return norm(candidate);\n }\n }\n\n return null;\n}\n\n/**\n * Transpile a `.tsx`/`.ts` file for use in a bundler.\n *\n * Returns `{ code, map, tagName }` for Stencil component or base-class files,\n * `null` for everything else (plain TS utilities, non-TS files, etc.).\n * `tagName` is empty string for base classes with no `@Component`.\n *\n * `onBaseClass` is called for every file the compiler resolves via\n * `resolveImport` during metadata collection. The plugin uses this to\n * pre-transform those files before the bundler's resolveId hook fires.\n * @param code - source file contents\n * @param id - absolute file path\n * @param options - plugin options\n * @param dev - `true` in dev/watch mode (enables HMR snippet)\n * @param framework - active unplugin framework\n * @param onBaseClass - called for each file in the inheritance chain with its abs path and raw source\n * @param configOverrides - pass stencil config option overrides to the transpiler\n * @returns transformed output, or `null` if the file is not a Stencil file\n */\nexport function transformStencil(\n code: string,\n id: string,\n options: StencilPluginOptions,\n dev = false,\n framework: SupportedFramework | '' = '',\n onBaseClass?: (absPath: string, rawCode: string) => void,\n configOverrides?: BuildOverrides,\n): {\n code: string;\n map: string | null;\n tagName: string;\n docsComponent: JsonDocsComponent | null;\n} | null {\n if (!id.endsWith('.tsx') && !id.endsWith('.ts')) return null;\n if (id.endsWith('.d.ts')) return null;\n\n // Cheap regex guard — avoids paying transpileSync cost for plain TS files.\n if (!/(@Component|@Prop|@State|@Event|@Method|@Watch|@Listen)\\s*[(\\s]/.test(code)) return null;\n\n const jsxOpts = resolveJsxOpts(code, process.cwd());\n const result = transpileSync(code, {\n ...jsxOpts,\n ...options.transpileOptions,\n file: id,\n componentExport: 'customelement',\n styleImportData: 'queryparams',\n resolveImport: makeResolver(onBaseClass),\n buildOverrides: {\n ...configOverrides,\n ...options.transpileOptions?.buildOverrides,\n ...(dev ? { hotModuleReplacement: true, isDev: true } : {}),\n },\n });\n\n if (result.diagnostics.some((d) => d.level === 'error')) {\n const msgs = result.diagnostics\n .filter((d) => d.level === 'error')\n .map((d) => d.messageText)\n .join('\\n');\n throw new Error(`[@stencil/unplugin] transpile error in ${id}:\\n${msgs}`);\n }\n\n if (!result.data?.length) {\n // No @Component — this is a base class or mixin factory. Return the\n // compiled output; for decorated classes the compiler's isStencilBaseClass\n // check already injected `extends HTMLElement`. Plain classes without\n // decorators are handled via the baseClassRegistry virtual-module path.\n if (!/@Component\\s*[(\\s]/.test(code)) {\n return { code: result.code, map: result.map ?? null, tagName: '', docsComponent: null };\n }\n return null;\n }\n\n const tagName = result.data[0].tagName;\n const className = result.data[0].componentClassName;\n\n // In dev mode, re-export the class so hmrStandalone can find it in the\n // re-imported module (customelement mode strips the export keyword).\n const devExport = dev ? `\\nexport{${className}};` : '';\n const out = dev\n ? result.code + devExport + buildHmrSnippet(tagName, className, framework)\n : result.code;\n\n const docsComponent = cmpMetaToDocsComponent(result.data[0], id);\n\n return { code: out, map: result.map ?? null, tagName, docsComponent };\n}\n\n/**\n * Transpile a base-class file with `transformAsBaseClass: true` so the\n * compiler injects `extends HTMLElement` into any class without an existing\n * heritage clause, regardless of whether it carries Stencil decorators.\n *\n * The result is cached in `baseClassRegistry` (in plugin.ts) and served as a\n * virtual module, ensuring the bundler always sees the injected version even\n * for plain lifecycle-only classes that the `transform` hook would otherwise skip.\n * @param rawCode - raw source of the base-class file\n * @param absPath - absolute path to the file (used as `file` for source maps)\n * @param options - plugin options forwarded to `transpileSync`\n * @returns compiled JS output\n */\nexport function transpileBaseClass(\n rawCode: string,\n absPath: string,\n options: StencilPluginOptions,\n): string {\n const result = transpileSync(rawCode, {\n ...options.transpileOptions,\n file: absPath,\n componentExport: 'customelement',\n styleImportData: 'queryparams',\n transformAsBaseClass: true,\n });\n return result.code;\n}\n\n/* Builds the HMR client snippet appended to component output in dev mode.\n *\n * Two strategies depending on bundler:\n * - Vite / Farm: server sends a `stencil:hmr` WebSocket event via\n * `handleHotUpdate`; the client calls `el['s-hmr'](version)` which triggers\n * a cache-busted re-import and forced re-render.\n * - webpack / rspack / bun: use the `module.hot` re-execution pattern —\n * `dispose` marks the reload with a flag, `accept` re-runs the module, and\n * the new prototype is patched onto existing instances in-place. */\nfunction buildHmrSnippet(\n tagName: string,\n className: string,\n framework: SupportedFramework | '',\n): string {\n const tag = JSON.stringify(tagName);\n\n if (framework === 'webpack' || framework === 'rspack' || framework === 'bun') {\n const hotExpr =\n framework === 'bun'\n ? 'import.meta.hot'\n : \"(typeof module !== 'undefined' && module.hot) || import.meta.webpackHot\";\n\n return (\n `\\n${className}.__stencil_module__ = import.meta.url;` +\n `\\nvar _sHot = ${hotExpr};` +\n `\\nif (_sHot) {` +\n `\\n if (_sHot.data && _sHot.data.stencilHmr) {` +\n `\\n var _sCtor = customElements.get(${tag});` +\n `\\n if (_sCtor) Object.getOwnPropertyNames(${className}.prototype).forEach(function(k) {` +\n `\\n if (k !== 'constructor') Object.defineProperty(_sCtor.prototype, k, Object.getOwnPropertyDescriptor(${className}.prototype, k));` +\n `\\n });` +\n `\\n document.querySelectorAll(${tag}).forEach(function(el) { el.connectedCallback && el.connectedCallback(); });` +\n `\\n }` +\n `\\n _sHot.dispose(function(data) { data.stencilHmr = true; });` +\n `\\n _sHot.accept();` +\n `\\n}`\n );\n }\n\n // Vite and Farm both implement the Vite HMR API.\n // The s-hmr guard prevents ?s-hmr= re-imports from stacking up additional listeners.\n return (\n `\\n${className}.__stencil_module__ = import.meta.url;` +\n `\\nif (import.meta.hot && !import.meta.url.includes('s-hmr=')) {` +\n `\\n import.meta.hot.accept(() => {});` +\n `\\n import.meta.hot.on('stencil:hmr', function({ tagName }) {` +\n `\\n if (tagName === ${tag}) {` +\n `\\n var v = Date.now().toString(36);` +\n `\\n document.querySelectorAll(${tag}).forEach(function(el) { el['s-hmr'] && el['s-hmr'](v); });` +\n `\\n }` +\n `\\n });` +\n `\\n}`\n );\n}\n\n/* Builds the `resolveImport` callback for `transpileSync`.\n *\n * The compiler calls this for every import it encounters while walking the\n * inheritance chain during metadata collection. The callback returns the raw\n * source so the compiler can merge inherited props/states/events into the\n * component's metadata. As a side-effect it calls `onBaseClass` with the same\n * raw source, giving the plugin a chance to pre-transform and cache the file\n * before the bundler's resolveId hook fires for it. */\nfunction makeResolver(onBaseClass?: (absPath: string, rawCode: string) => void) {\n return (specifier: string, currentImporter: string): { code: string; path: string } | null => {\n const absPath = resolveSpecifier(specifier, currentImporter);\n if (!absPath) return null;\n\n const code = readFileSync(absPath, 'utf-8');\n onBaseClass?.(absPath, code);\n return { code, path: absPath };\n };\n}\n","/**\n * Unplugin factory for @stencil/unplugin.\n *\n * Wires together four concerns into a single plugin that works across Vite,\n * Rollup, webpack, rspack, and bun:\n *\n * 1. **Component transform** — `transform` drives `transpileSync` on every\n * `.tsx`/`.ts` file that carries Stencil decorators, producing\n * `customelement` output (self-registering class + `defineCustomElement`).\n *\n * 2. **CSS virtual modules** — Stencil emits `./foo.css?tag=my-cmp&…`\n * imports. `resolveId` rewrites these to `\\0stencil-css:` virtual IDs;\n * `load` reads the real file, runs it through any installed preprocessors,\n * and returns `export default () => \"…css…\"`.\n *\n * 3. **Base-class inheritance** — when a component extends a class that does\n * not itself extend `HTMLElement`, the custom-element registration breaks.\n * The plugin intercepts every file the compiler resolves via `resolveImport`\n * (during `transpileSync`), pre-transforms it with `transformAsBaseClass: true`\n * so it gets `extends HTMLElement`, and caches the result. `resolveId` then\n * redirects imports of those files to `\\0stencil-base:` virtual modules so\n * the bundler always sees the injected version — regardless of module-graph\n * processing order.\n *\n * 4. **HMR** — Vite receives a custom `stencil:hmr` WebSocket event when a\n * component file changes; other bundlers use the `module.hot` re-execution\n * pattern. CSS changes are covered automatically by `addWatchFile`.\n */\nimport { readdirSync, readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { createFilter } from '@rollup/pluginutils';\nimport { transpile, cmpMetaToDocsComponent, generateManifest } from '@stencil/core/compiler';\nimport { createUnplugin } from 'unplugin';\nimport type {\n BuildOverrides,\n CustomElementsManifest,\n JsonDocsComponent,\n} from '@stencil/core/compiler';\n\nimport { loadStencilConfig, stencilConfigToOverrides } from './config.js';\nimport { getRealCssPath, isStencilCss, loadStencilCss, resolveStencilCss } from './css.js';\nimport { resolveImportedTypes } from './resolve-types.js';\nimport { resolveSpecifier, transformStencil, transpileBaseClass } from './transform.js';\nimport type { StencilPluginOptions } from './options.js';\n\nexport const STENCIL_DOCS_ID = '@stencil/unplugin/docs';\nconst VIRTUAL_DOCS_PREFIX = '\\0stencil-docs:';\n\n// Module-level registry so getStencilDocs() is callable from outside the plugin\n// (e.g. from a Storybook preset running in Node.js).\nconst docsRegistry = new Map<string, JsonDocsComponent>();\n\n/**\n * Returns the current CEM. Only populated when `docs: true` is set.\n * @returns the current CEM, or an empty CEM if `docs: true` was not set.\n */\nexport function getStencilCEM(): CustomElementsManifest {\n return generateManifest({ components: [...docsRegistry.values()] });\n}\n\n/**\n * Scan the project for component source files and pre-populate the docs registry.\n * @param filter A function to filter which files should be included.\n * @returns A promise that resolves when the scan is complete.\n */\nasync function scanDocs(filter: (id: string) => boolean): Promise<void> {\n const cwd = process.cwd();\n let entries: string[];\n try {\n entries = readdirSync(cwd, { recursive: true, encoding: 'utf-8' }) as string[];\n } catch {\n return;\n }\n\n const files = entries\n .filter((rel) => (rel.endsWith('.tsx') || rel.endsWith('.ts')) && !rel.endsWith('.d.ts'))\n .map((rel) => join(cwd, rel))\n .filter((abs) => filter(abs));\n\n await Promise.all(\n files.map(async (abs) => {\n let code: string;\n try {\n code = readFileSync(abs, 'utf-8');\n } catch {\n return;\n }\n if (!/(@Component|@Prop|@State|@Event|@Method|@Watch|@Listen)\\s*[(\\s]/.test(code)) return;\n const result = await transpile(code, { file: abs, componentExport: 'customelement' });\n for (const item of result.data ?? []) {\n if (!item.tagName) continue;\n const component = cmpMetaToDocsComponent(item, abs);\n resolveImportedTypes(component, abs);\n docsRegistry.set(item.tagName, component);\n }\n }),\n );\n}\n\n// Null-byte prefix marks a virtual module — Rollup/Vite convention that\n// prevents the ID from being treated as a real filesystem path.\nconst VIRTUAL_BASE_PREFIX = '\\0stencil-base:';\n\n// Mirrors the compiler's hasSignalsImport check in static-to-meta/import.ts.\nconst SIGNALS_IMPORT_RE = /from\\s+['\"]@stencil\\/core\\/signals['\"]/;\n\nexport const unpluginStencil = createUnplugin(\n (options: StencilPluginOptions | undefined = {}, meta) => {\n const { framework } = meta;\n const filter = createFilter(\n options.include ?? [/\\.tsx?$/],\n options.exclude ?? ['node_modules/**'],\n );\n\n // Vite auto-detects dev mode via configResolved; other bundlers use options.dev.\n let isDev = options.dev ?? false;\n\n // For Vite, configResolved sets this to config.root (more accurate than process.cwd()).\n // For other bundlers, process.cwd() is the fallback.\n let projectRoot = process.cwd();\n\n // Merged BUILD overrides from auto-detected stencil.config + explicit stencilConfig.\n // Populated in buildStart; explicit transpileOptions.buildOverrides takes precedence\n // over this in transformStencil.\n let configOverrides: BuildOverrides = {};\n\n // Tracks which source file owns which custom-element tag name, used by the\n // Vite HMR handler to send targeted `stencil:hmr` events.\n const fileToTagName = new Map<string, string>();\n\n // Maps CSS dependency paths (including Sass @use/@import) → tag name so\n // changes to imported partials also trigger HMR for the component.\n const cssFileToTagName = new Map<string, string>();\n\n // Maps real CSS file path → virtual CSS module ID (\\0stencil-css:...) so\n // handleHotUpdate can locate and invalidate the right module in the graph.\n const cssRealToVirtualId = new Map<string, string>();\n\n // absPath → HTMLElement-injected JS. Populated during `transform` when\n // `transpileSync`'s resolveImport callback discovers a base-class file.\n // Rollup guarantees that resolveId for imports in a module's *output* fires\n // after the transform that produced them — so by the time the bundler asks\n // to resolve a base-class import, this map is already populated.\n const baseClassRegistry = new Map<string, string>();\n\n function registerBaseClass(absPath: string, rawCode: string) {\n if (baseClassRegistry.has(absPath)) return; // already processed this build\n baseClassRegistry.set(absPath, transpileBaseClass(rawCode, absPath, options));\n }\n\n return {\n name: '@stencil/unplugin',\n\n async buildStart() {\n const detected = await loadStencilConfig(projectRoot);\n // Merge: auto-detected config is the base; explicit stencilConfig overrides field-by-field.\n const merged = detected\n ? {\n ...detected,\n ...options.stencilConfig,\n compat: { ...detected.compat, ...options.stencilConfig?.compat },\n }\n : (options.stencilConfig ?? {});\n configOverrides = stencilConfigToOverrides(merged);\n if (options.docs) await scanDocs(filter);\n },\n\n resolveId(id, importer) {\n if (id === STENCIL_DOCS_ID) return VIRTUAL_DOCS_PREFIX;\n if (!importer) return null;\n\n const css = resolveStencilCss(id, importer);\n if (css) return css;\n\n if (baseClassRegistry.size > 0) {\n // Imports inside a virtual base-class module use the virtual ID as\n // importer — strip the prefix so resolveSpecifier works against the\n // real path on disk. This matters for multi-level inheritance chains.\n\n const realImporter = importer.startsWith(VIRTUAL_BASE_PREFIX)\n ? importer.slice(VIRTUAL_BASE_PREFIX.length)\n : importer;\n\n const abs = resolveSpecifier(id, realImporter);\n if (abs && baseClassRegistry.has(abs)) {\n return VIRTUAL_BASE_PREFIX + abs;\n }\n }\n\n return null;\n },\n\n transformInclude(id) {\n return filter(id.split('?')[0]);\n },\n\n transform(code, id) {\n const cleanId = id.split('?')[0];\n if (!configOverrides.vdomSignals && SIGNALS_IMPORT_RE.test(code)) {\n configOverrides = { ...configOverrides, vdomSignals: true };\n }\n const result = transformStencil(\n code,\n cleanId,\n options,\n isDev,\n framework,\n registerBaseClass,\n configOverrides,\n );\n if (result?.tagName) fileToTagName.set(cleanId, result.tagName);\n if (result?.docsComponent && options.docs) {\n resolveImportedTypes(result.docsComponent, cleanId);\n docsRegistry.set(result.docsComponent.tag, result.docsComponent);\n }\n return result;\n },\n\n loadInclude(id) {\n return id === VIRTUAL_DOCS_PREFIX || isStencilCss(id) || id.startsWith(VIRTUAL_BASE_PREFIX);\n },\n\n async load(id) {\n if (id === VIRTUAL_DOCS_PREFIX) {\n return `export default ${JSON.stringify(getStencilCEM())}`;\n }\n if (id.startsWith(VIRTUAL_BASE_PREFIX)) {\n const realPath = id.slice(VIRTUAL_BASE_PREFIX.length);\n this.addWatchFile(realPath); // re-invalidate this virtual module when the source changes\n return { code: baseClassRegistry.get(realPath) ?? '', map: null };\n }\n const realPath = getRealCssPath(id);\n const qIdx = id.indexOf('?');\n const tag = qIdx !== -1 ? new URLSearchParams(id.slice(qIdx + 1)).get('tag') : null;\n if (realPath) {\n this.addWatchFile(realPath);\n if (tag) cssFileToTagName.set(realPath, tag);\n cssRealToVirtualId.set(realPath, id);\n }\n const cssResult = await loadStencilCss(id, isDev);\n if (cssResult) {\n if (tag) {\n for (const dep of cssResult.deps) {\n this.addWatchFile(dep);\n cssFileToTagName.set(dep, tag);\n cssRealToVirtualId.set(dep, id);\n }\n }\n return { code: cssResult.code, map: null };\n }\n return null;\n },\n\n vite: {\n // Must run before Vite/rolldown's built-in TSX transform, which would\n // otherwise claim the file and emit react/jsx-dev-runtime imports.\n enforce: 'pre' as const,\n\n configResolved(config: { command: string; root: string }) {\n isDev = options.dev ?? config.command === 'serve';\n projectRoot = config.root;\n },\n\n async handleHotUpdate({\n file,\n server,\n }: {\n file: string;\n server: {\n ws: { send: (msg: unknown) => void };\n moduleGraph: {\n invalidateModule(\n mod: unknown,\n seen?: Set<unknown>,\n timestamp?: number,\n isHmr?: boolean,\n ): void;\n getModuleById?(id: string): unknown;\n idToModuleMap?: Map<string, unknown>;\n };\n };\n }) {\n const tagName = fileToTagName.get(file) ?? cssFileToTagName.get(file);\n if (!tagName) return;\n // Invalidate the virtual CSS module (\\0stencil-css:...) so Vite\n // rewrites its import URL with ?t=timestamp when serving the\n // re-fetched TSX — prevents the browser's ESM cache serving stale CSS.\n const virtualId = cssRealToVirtualId.get(file);\n if (virtualId) {\n const virtualMod =\n server.moduleGraph.getModuleById?.(virtualId) ??\n server.moduleGraph.idToModuleMap?.get(virtualId);\n if (virtualMod)\n server.moduleGraph.invalidateModule(virtualMod, new Set(), Date.now(), true);\n }\n // Update the docs registry and notify the client only when the CEM\n // actually changed (new/renamed prop, type update, JSDoc edit, etc.).\n // Pure implementation changes leave the CEM identical and fall through\n // to normal stencil:hmr so HMR is not disrupted.\n if (options.docs && fileToTagName.has(file)) {\n let cemChanged = false;\n try {\n const prevSnapshot = JSON.stringify(docsRegistry.get(tagName));\n const code = readFileSync(file, 'utf-8');\n const result = await transpile(code, { file, componentExport: 'customelement' });\n for (const item of result.data ?? []) {\n if (!item.tagName) continue;\n const component = cmpMetaToDocsComponent(item, file);\n resolveImportedTypes(component, file);\n docsRegistry.set(item.tagName, component);\n }\n cemChanged = JSON.stringify(docsRegistry.get(tagName)) !== prevSnapshot;\n } catch {\n // stale docs are acceptable on transpile error\n }\n if (cemChanged) {\n const docsVirtualMod =\n server.moduleGraph.getModuleById?.(VIRTUAL_DOCS_PREFIX) ??\n server.moduleGraph.idToModuleMap?.get(VIRTUAL_DOCS_PREFIX);\n if (docsVirtualMod)\n server.moduleGraph.invalidateModule(docsVirtualMod, new Set(), Date.now(), true);\n server.ws.send({ type: 'custom', event: 'stencil:docs-update' });\n }\n }\n server.ws.send({ type: 'custom', event: 'stencil:hmr', data: { tagName } });\n return [];\n },\n },\n };\n },\n);\n","export { unpluginStencil, getStencilCEM, STENCIL_DOCS_ID } from './plugin.js';\nexport type { StencilPluginOptions } from './options.js';\n\nimport { unpluginStencil } from './plugin.js';\n\nexport const stencilVite = unpluginStencil.vite;\nexport const stencilRollup = unpluginStencil.rollup;\nexport const stencilWebpack = unpluginStencil.webpack;\nexport const stencilEsbuild = unpluginStencil.esbuild;\nexport const stencilRspack = unpluginStencil.rspack;\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAmBA,MAAM,sBAAsB,IAAI,IAAI;CAClC;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,MAAM,mBAAmB,MACvB,MAAM,QACN,OAAO,MAAM,YACb,CAAC,MAAM,QAAQ,CAAC,KAChB,OAAO,KAAK,CAAW,EAAE,MAAM,MAAM,oBAAoB,IAAI,CAAC,CAAC;AAEjE,MAAM,oBAAoB;CACxB;CACA;CACA;CACA;AACF;;;;;;;;AASA,eAAsB,kBAAkB,KAAkD;CACxF,KAAK,MAAM,YAAY,mBAAmB;EACxC,MAAM,aAAa,KAAK,KAAK,QAAQ;EACrC,IAAI,CAAC,WAAW,UAAU,GAAG;EAC7B,IAAI;GACF,MAAM,EAAE,eAAe,MAAM,OAAO;GAEpC,MAAM,MAAO,MADA,WAAW,OAAO,KAAK,GACd,EAAE,OAAO,UAAU;GAKzC,MAAM,MAAM,IAAI,cAAc,gBAAgB,IAAI,UAAU,IAAI,IAAI,aAAa;GACjF,IAAI,CAAC,OAAO,OAAO,QAAQ,UAAU,OAAO;GAC5C,OAAO,cAAc,GAA8B;EACrD,QAAQ;GACN,OAAO;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AI,QAAQ,QAAQ,cAAc,IAAI,IAAI,GAAG;KAC3C,IAAI,aAAa;KACjB,IAAI;MACF,MAAM,eAAe,KAAK,UAAU,aAAa,IAAI,OAAO,CAAC;MAE7D,MAAM,SAAS,MAAM,UADR,aAAa,MAAM,OACE,GAAG;OAAE;OAAM,iBAAiB;MAAgB,CAAC;MAC/E,KAAK,MAAM,QAAQ,OAAO,QAAQ,CAAC,GAAG;OACpC,IAAI,CAAC,KAAK,SAAS;OACnB,MAAM,YAAY,uBAAuB,MAAM,IAAI;OACnD,qBAAqB,WAAW,IAAI;OACpC,aAAa,IAAI,KAAK,SAAS,SAAS;MAC1C;MACA,aAAa,KAAK,UAAU,aAAa,IAAI,OAAO,CAAC,MAAM;KAC7D,QAAQ,CAER;KACA,IAAI,YAAY;MACd,MAAM,iBACJ,OAAO,YAAY,gBAAgB,mBAAmB,KACtD,OAAO,YAAY,eAAe,IAAI,mBAAmB;MAC3D,IAAI,gBACF,OAAO,YAAY,iBAAiB,gCAAgB,IAAI,IAAI,GAAG,KAAK,IAAI,GAAG,IAAI;MACjF,OAAO,GAAG,KAAK;OAAE,MAAM;OAAU,OAAO;MAAsB,CAAC;KACjE;IACF;IACA,OAAO,GAAG,KAAK;KAAE,MAAM;KAAU,OAAO;KAAe,MAAM,EAAE,QAAQ;IAAE,CAAC;IAC1E,OAAO,CAAC;GACV;EACF;CACF;AACF,CACF;;;ACrUA,MAAa,cAAc,gBAAgB;AAC3C,MAAa,gBAAgB,gBAAgB;AAC7C,MAAa,iBAAiB,gBAAgB;AAC9C,MAAa,iBAAiB,gBAAgB;AAC9C,MAAa,gBAAgB,gBAAgB"}
package/package.json ADDED
@@ -0,0 +1,78 @@
1
+ {
2
+ "name": "@stencil/unplugin",
3
+ "version": "5.0.0-alpha.16",
4
+ "description": "Universal bundler plugin for Stencil components (Vite, Rollup, Webpack, esbuild)",
5
+ "license": "MIT",
6
+ "files": [
7
+ "dist"
8
+ ],
9
+ "type": "module",
10
+ "main": "./dist/index.mjs",
11
+ "module": "./dist/index.mjs",
12
+ "types": "./dist/index.d.mts",
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.mts",
16
+ "default": "./dist/index.mjs"
17
+ },
18
+ "./docs": {
19
+ "types": "./dist/docs.d.mts",
20
+ "default": "./dist/docs.mjs"
21
+ }
22
+ },
23
+ "scripts": {
24
+ "build": "tsdown",
25
+ "typecheck": "tsc --noEmit",
26
+ "test": "pnpm run test:unit",
27
+ "test:unit": "vitest run --config vitest.config.ts",
28
+ "test:browser": "vitest run --config vitest.browser.config.ts",
29
+ "playground": "vite playground"
30
+ },
31
+ "dependencies": {
32
+ "@rollup/pluginutils": "^5.4.0",
33
+ "jiti": "^2.0.0",
34
+ "local-pkg": "^1.2.1",
35
+ "unplugin": "^3.0.0"
36
+ },
37
+ "devDependencies": {
38
+ "@stencil/core": "workspace:*",
39
+ "@types/less": "^3.0.8",
40
+ "@vitest/browser": "catalog:",
41
+ "@vitest/browser-playwright": "catalog:",
42
+ "less": "^4.6.7",
43
+ "lightningcss": "^1.32.0",
44
+ "postcss": "^8.5.15",
45
+ "postcss-load-config": "^6.0.1",
46
+ "sass": "^1.101.0",
47
+ "tsdown": "catalog:",
48
+ "typescript": "catalog:",
49
+ "vite": "^8.1.0",
50
+ "vitest": "catalog:"
51
+ },
52
+ "peerDependencies": {
53
+ "@stencil/core": "^5.0.0-0",
54
+ "less": "^4.0.0",
55
+ "lightningcss": "^1.0.0",
56
+ "postcss": "^8.0.0",
57
+ "postcss-load-config": "^4.0.0 || ^5.0.0 || ^6.0.0",
58
+ "sass": "^1.0.0",
59
+ "typescript": ">=5.0.0"
60
+ },
61
+ "peerDependenciesMeta": {
62
+ "less": {
63
+ "optional": true
64
+ },
65
+ "lightningcss": {
66
+ "optional": true
67
+ },
68
+ "postcss": {
69
+ "optional": true
70
+ },
71
+ "postcss-load-config": {
72
+ "optional": true
73
+ },
74
+ "sass": {
75
+ "optional": true
76
+ }
77
+ }
78
+ }