@stencil/core 5.0.0-beta.9 → 5.0.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/app-data/index.d.ts +1 -1
  2. package/dist/app-data/index.js +1 -0
  3. package/dist/{client-BRu0GtRn.mjs → client-ClM4H9-P.mjs} +204 -76
  4. package/dist/compiler/browser.d.ts +120 -81
  5. package/dist/compiler/browser.js +964 -402
  6. package/dist/compiler/index.d.mts +110 -2
  7. package/dist/compiler/index.mjs +3 -3
  8. package/dist/compiler/utils/index.d.mts +2 -2
  9. package/dist/compiler/utils/index.mjs +3 -3
  10. package/dist/{compiler-wLrjuSOK.mjs → compiler-DFanjq9z.mjs} +5300 -3005
  11. package/dist/declarations/stencil-public-compiler.d.ts +178 -133
  12. package/dist/declarations/stencil-public-docs.d.ts +23 -0
  13. package/dist/declarations/stencil-public-runtime.d.ts +81 -59
  14. package/dist/{index-BvF31nqP.d.mts → index-DvfFOkiJ.d.mts} +220 -133
  15. package/dist/{index-BXAcVN2j.d.ts → index-XQHZl0MW.d.ts} +70 -57
  16. package/dist/{index-BAP9T4CB.d.mts → index-aBMJC5F9.d.mts} +6 -2
  17. package/dist/index.d.mts +3 -0
  18. package/dist/index.mjs +1 -1
  19. package/dist/jsx-runtime.d.mts +6 -0
  20. package/dist/jsx-runtime.mjs +1 -1
  21. package/dist/{node-75gQKkFz.mjs → node-DJP8JuAS.mjs} +42 -48
  22. package/dist/runtime/client/lazy.js +522 -262
  23. package/dist/runtime/client/runtime.d.ts +100 -68
  24. package/dist/runtime/client/runtime.js +522 -262
  25. package/dist/runtime/index.d.ts +6 -6
  26. package/dist/runtime/index.js +521 -261
  27. package/dist/runtime/server/index.d.mts +36 -12
  28. package/dist/runtime/server/index.mjs +635 -304
  29. package/dist/runtime/server/runner.d.mts +49 -6
  30. package/dist/runtime/server/runner.mjs +385 -87
  31. package/dist/signals/index.d.ts +11 -2
  32. package/dist/signals/index.js +15 -35
  33. package/dist/sys/node/index.d.mts +1 -1
  34. package/dist/sys/node/index.mjs +1 -1
  35. package/dist/sys/node/worker.mjs +2 -2
  36. package/dist/testing/index.d.mts +152 -124
  37. package/dist/testing/index.mjs +535 -269
  38. package/dist/{util-IKfWWLJo.mjs → util-C-H1H84W.mjs} +8 -1
  39. package/dist/{validation-DAdGTrys.mjs → validation-ByYYKvnS.mjs} +37 -3
  40. package/package.json +8 -4
@@ -370,7 +370,8 @@ const formatComponentRuntimeMeta = (compilerMeta, includeMethods) => {
370
370
  hostListeners.length > 0 ? hostListeners : void 0,
371
371
  Object.keys(watchers).length > 0 ? watchers : void 0,
372
372
  Object.keys(serializers).length > 0 ? serializers : void 0,
373
- Object.keys(deserializers).length > 0 ? deserializers : void 0
373
+ Object.keys(deserializers).length > 0 ? deserializers : void 0,
374
+ compilerMeta.encapsulation === "shadow" ? compilerMeta.shadowReferenceTarget : void 0
374
375
  ]);
375
376
  };
376
377
  /**
@@ -1178,11 +1179,11 @@ const BUILD = {
1178
1179
  shadowSlotAssignmentManual: false,
1179
1180
  shadowClonable: true,
1180
1181
  shadowSerializable: true,
1182
+ shadowReferenceTarget: true,
1181
1183
  initializeNextTick: false,
1182
1184
  asyncLoading: true,
1183
1185
  asyncQueue: false
1184
1186
  };
1185
- BUILD.isDev, BUILD.isTesting;
1186
1187
  BUILD.isTesting;
1187
1188
  /*!__STENCIL_STATIC_IMPORT_SWITCH__*/
1188
1189
  (typeof window !== "undefined" ? window : {}).HTMLElement;
@@ -1501,7 +1502,7 @@ const scopeSelector = (selector, scopeSelectorText, hostSelector, slotSelector)
1501
1502
  else return shallowPart.trim();
1502
1503
  }).join(", ");
1503
1504
  };
1504
- const isScopableAtRule = (selector) => selector.startsWith("@media") || selector.startsWith("@supports") || selector.startsWith("@page") || selector.startsWith("@document") || selector.startsWith("@layer");
1505
+ const isScopableAtRule = (selector) => selector.startsWith("@media") || selector.startsWith("@supports") || selector.startsWith("@page") || selector.startsWith("@document") || selector.startsWith("@layer") || selector.startsWith("@container");
1505
1506
  const scopeSelectors = (cssText, scopeSelectorText, hostSelector, slotSelector, commentOriginalSelector) => {
1506
1507
  return processRules(cssText, (rule) => {
1507
1508
  let selector = rule.selector;
@@ -1693,6 +1694,18 @@ const createJsVarName = (fileName) => {
1693
1694
  }
1694
1695
  return fileName;
1695
1696
  };
1697
+ /**
1698
+ * Create a function that lowercases the first string parameter before passing it to the provided function
1699
+ * @param fn the function to pass the lowercased path to
1700
+ * @returns the result of the provided function
1701
+ */
1702
+ const lowerPathParam = (fn) => (p) => fn(p.toLowerCase());
1703
+ /**
1704
+ * Determine if a stringified file path is a TypeScript declaration file based on the extension at the end of the path.
1705
+ * @param p the path to evaluate
1706
+ * @returns `true` if the path ends in `.d.ts` (case-sensitive), `false` otherwise.
1707
+ */
1708
+ const isDtsFile = lowerPathParam((p) => p.endsWith(".d.ts") || p.endsWith(".d.mts") || p.endsWith(".d.cts"));
1696
1709
  function getTextDocs(docs) {
1697
1710
  if (docs == null) return "";
1698
1711
  return [escapeWithPattern(docs.text.replace(LINE_BREAK_REGEX, " "), /\*\//, "*\\/", true), ...docs.tags.filter((tag) => tag.name !== "internal").map((tag) => {
@@ -1832,7 +1845,7 @@ const validateComponentTag = (tag) => {
1832
1845
  };
1833
1846
  //#endregion
1834
1847
  //#region src/version.ts
1835
- const version = "5.0.0-beta.9";
1848
+ const version = "5.0.0-rc.0";
1836
1849
  //#endregion
1837
1850
  //#region src/compiler/events.ts
1838
1851
  const buildEvents = () => {
@@ -1895,6 +1908,7 @@ const resolve = (id, _opts, cb) => {
1895
1908
  };
1896
1909
  //#endregion
1897
1910
  //#region src/compiler/sys/resolve/resolve-utils.ts
1911
+ const isLocalModule = (p) => p.startsWith(".") || p.startsWith("/");
1898
1912
  const isNodeModulePath = (p) => normalizePath(p).split("/").includes("node_modules");
1899
1913
  const getModuleId = (orgImport) => {
1900
1914
  if (orgImport.startsWith("~")) orgImport = orgImport.substring(1);
@@ -2345,15 +2359,6 @@ const createSystem = (c) => {
2345
2359
  }
2346
2360
  return results;
2347
2361
  };
2348
- /**
2349
- * `self` is the global namespace object used within a web worker.
2350
- * `window` is the browser's global namespace object (I reorganized this to check the reference on that second)
2351
- * `global` is Node's global namespace object. https://nodejs.org/api/globals.html#globals_global
2352
- *
2353
- * loading in this order should allow workers, which are most common, then browser,
2354
- * then Node to grab the reference to fetch correctly.
2355
- */
2356
- const fetch = typeof self !== "undefined" ? self?.fetch : typeof window !== "undefined" ? window?.fetch : typeof global !== "undefined" ? global?.fetch : void 0;
2357
2362
  const writeFile = async (p, data) => writeFileSync(p, data);
2358
2363
  const tmpDirSync = () => "/.tmp";
2359
2364
  const tick = Promise.resolve();
@@ -2364,6 +2369,7 @@ const createSystem = (c) => {
2364
2369
  if (typeof hashLength === "number") hashHex = hashHex.slice(0, hashLength);
2365
2370
  return hashHex;
2366
2371
  };
2372
+ const generateFileHash = async (filePath, hashLength) => generateContentHash(readFileSync(filePath), hashLength);
2367
2373
  const copy = async (copyTasks, srcDir) => {
2368
2374
  const results = {
2369
2375
  diagnostics: [],
@@ -2373,9 +2379,6 @@ const createSystem = (c) => {
2373
2379
  logger.info("todo, copy task", copyTasks.length, srcDir);
2374
2380
  return results;
2375
2381
  };
2376
- const getEnvironmentVar = (key) => {
2377
- return process$1?.env[key];
2378
- };
2379
2382
  const getLocalModulePath = (opts) => join$1(opts.rootDir, "node_modules", opts.moduleId, opts.path);
2380
2383
  const getRemoteModuleUrl = (opts) => {
2381
2384
  const npmBaseUrl = "https://cdn.jsdelivr.net/npm/";
@@ -2391,13 +2394,14 @@ const createSystem = (c) => {
2391
2394
  access,
2392
2395
  accessSync,
2393
2396
  addDestroy,
2397
+ checkVersion: async () => noop,
2394
2398
  copyFile,
2395
2399
  createDir,
2396
2400
  createDirSync,
2397
2401
  homeDir,
2398
2402
  isTTY,
2399
- getEnvironmentVar,
2400
2403
  destroy,
2404
+ dynamicImport: (p) => import(p),
2401
2405
  encodeToBase64,
2402
2406
  exit: async (exitCode) => logger.warn(`exit ${exitCode}`),
2403
2407
  getCurrentDirectory,
@@ -2408,6 +2412,7 @@ const createSystem = (c) => {
2408
2412
  isSymbolicLink,
2409
2413
  nextTick,
2410
2414
  normalizePath: normalize,
2415
+ onProcessInterrupt: noop,
2411
2416
  platformPath: path,
2412
2417
  readDir,
2413
2418
  readDirSync,
@@ -2417,7 +2422,6 @@ const createSystem = (c) => {
2417
2422
  realpathSync,
2418
2423
  removeDestroy,
2419
2424
  rename,
2420
- fetch,
2421
2425
  resolvePath,
2422
2426
  removeDir,
2423
2427
  removeDirSync,
@@ -2432,6 +2436,7 @@ const createSystem = (c) => {
2432
2436
  writeFile,
2433
2437
  writeFileSync,
2434
2438
  generateContentHash,
2439
+ generateFileHash,
2435
2440
  createWorkerController: null,
2436
2441
  details: {
2437
2442
  cpuModel: "",
@@ -2633,19 +2638,20 @@ const getTranspileCssConfig = (compileOpts, importData, results) => {
2633
2638
  minify: false,
2634
2639
  autoprefixer: false,
2635
2640
  module: compileOpts.module,
2636
- styleImportData: compileOpts.styleImportData
2641
+ styleImportData: compileOpts.styleImportData,
2642
+ docs: compileOpts.docs === true
2637
2643
  };
2638
2644
  };
2639
2645
  const getTranspileConfigOpt = (value, validValues, defaultValue) => {
2640
2646
  if (value === null || value === "null") return null;
2641
- value = isString$1(value) ? value.toLowerCase().trim() : null;
2647
+ value = isString$1(value) ? value.toLowerCase().trim() : void 0;
2642
2648
  if (validValues.has(value)) return value;
2643
2649
  return defaultValue;
2644
2650
  };
2645
2651
  const VALID_EXPORT = /* @__PURE__ */ new Set(["customelement", "module"]);
2646
- const VALID_METADATA = /* @__PURE__ */ new Set(["compilerstatic", null]);
2652
+ const VALID_METADATA = /* @__PURE__ */ new Set(["compilerstatic"]);
2647
2653
  const VALID_MODULE = /* @__PURE__ */ new Set(["cjs", "esm"]);
2648
- const VALID_PROXY = /* @__PURE__ */ new Set(["defineproperty", null]);
2654
+ const VALID_PROXY = /* @__PURE__ */ new Set(["defineproperty"]);
2649
2655
  const VALID_STYLE = /* @__PURE__ */ new Set(["static"]);
2650
2656
  const VALID_STYLE_IMPORT_DATA = /* @__PURE__ */ new Set(["queryparams"]);
2651
2657
  const VALID_TARGET = /* @__PURE__ */ new Set([
@@ -2825,7 +2831,7 @@ const validateReadmeOutputTarget = (config, outputTarget) => {
2825
2831
  if (!isAbsolute(outputTarget.dir)) outputTarget.dir = join$1(config.rootDir, outputTarget.dir);
2826
2832
  if (outputTarget.footer == null) outputTarget.footer = NOTE;
2827
2833
  outputTarget.strict = !!outputTarget.strict;
2828
- if (!isBoolean$1(outputTarget.skipInDev)) outputTarget.skipInDev = !config._docsFlag;
2834
+ if (!isBoolean$1(outputTarget.skipInDev)) outputTarget.skipInDev = true;
2829
2835
  return outputTarget;
2830
2836
  };
2831
2837
  const validateJsonDocsOutputTarget = (config, diagnostics, outputTarget) => {
@@ -2837,7 +2843,7 @@ const validateJsonDocsOutputTarget = (config, diagnostics, outputTarget) => {
2837
2843
  if (isString$1(outputTarget.typesFile) && !isAbsolute(outputTarget.typesFile)) outputTarget.typesFile = join$1(config.rootDir, outputTarget.typesFile);
2838
2844
  else if (outputTarget.typesFile !== null && outputTarget.file.endsWith(".json")) outputTarget.typesFile = outputTarget.file.replace(/\.json$/, ".d.ts");
2839
2845
  outputTarget.strict = !!outputTarget.strict;
2840
- if (!isBoolean$1(outputTarget.skipInDev)) outputTarget.skipInDev = !config._docsFlag;
2846
+ if (!isBoolean$1(outputTarget.skipInDev)) outputTarget.skipInDev = true;
2841
2847
  return outputTarget;
2842
2848
  };
2843
2849
  const validateCustomDocsOutputTarget = (config, diagnostics, outputTarget) => {
@@ -2846,7 +2852,7 @@ const validateCustomDocsOutputTarget = (config, diagnostics, outputTarget) => {
2846
2852
  err.messageText = `docs-custom outputTarget missing the "generator" function`;
2847
2853
  }
2848
2854
  outputTarget.strict = !!outputTarget.strict;
2849
- if (!isBoolean$1(outputTarget.skipInDev)) outputTarget.skipInDev = !config._docsFlag;
2855
+ if (!isBoolean$1(outputTarget.skipInDev)) outputTarget.skipInDev = true;
2850
2856
  return outputTarget;
2851
2857
  };
2852
2858
  const validateVScodeDocsOutputTarget = (config, diagnostics, outputTarget) => {
@@ -2854,21 +2860,22 @@ const validateVScodeDocsOutputTarget = (config, diagnostics, outputTarget) => {
2854
2860
  const err = buildError(diagnostics);
2855
2861
  err.messageText = `docs-vscode outputTarget missing the "file" path`;
2856
2862
  }
2857
- if (!isBoolean$1(outputTarget.skipInDev)) outputTarget.skipInDev = !config._docsFlag;
2863
+ if (!isBoolean$1(outputTarget.skipInDev)) outputTarget.skipInDev = true;
2858
2864
  return outputTarget;
2859
2865
  };
2860
2866
  const DEFAULT_AGENT_SKILL_DIR = "dist/skill";
2861
2867
  const validateAgentSkillOutputTarget = (config, outputTarget) => {
2862
2868
  outputTarget.dir = getAbsolutePath(config, outputTarget.dir || DEFAULT_AGENT_SKILL_DIR);
2863
2869
  outputTarget.name = toSkillName(outputTarget.name || config.fsNamespace);
2864
- if (!isBoolean$1(outputTarget.skipInDev)) outputTarget.skipInDev = !config._docsFlag;
2870
+ if (!isBoolean$1(outputTarget.skipInDev)) outputTarget.skipInDev = true;
2865
2871
  return outputTarget;
2866
2872
  };
2873
+ const DEFAULT_CUSTOM_ELEMENTS_MANIFEST_FILE = "dist/custom-elements.json";
2867
2874
  const validateCustomElementsManifestOutputTarget = (config, outputTarget) => {
2868
- if (!isString$1(outputTarget.file)) outputTarget.file = "custom-elements.json";
2875
+ if (!isString$1(outputTarget.file)) outputTarget.file = DEFAULT_CUSTOM_ELEMENTS_MANIFEST_FILE;
2869
2876
  if (!isAbsolute(outputTarget.file)) outputTarget.file = join$1(config.rootDir, outputTarget.file);
2870
2877
  outputTarget.strict = !!outputTarget.strict;
2871
- if (!isBoolean$1(outputTarget.skipInDev)) outputTarget.skipInDev = !config._docsFlag;
2878
+ if (!isBoolean$1(outputTarget.skipInDev)) outputTarget.skipInDev = true;
2872
2879
  return outputTarget;
2873
2880
  };
2874
2881
  //#endregion
@@ -3813,7 +3820,8 @@ const validateConfig = (userConfig = {}, bootstrapConfig) => {
3813
3820
  ...config,
3814
3821
  devMode,
3815
3822
  compat: config.compat || {},
3816
- generateExportMaps: isBoolean$1(config.generateExportMaps) ? config.generateExportMaps : !isString$1(config.configPath),
3823
+ generateExportMaps: config.generateExportMaps === true,
3824
+ enableCssOnlyComponents: config.enableCssOnlyComponents ?? true,
3817
3825
  hydratedFlag: validateHydrated(config),
3818
3826
  logLevel,
3819
3827
  logger,
@@ -3843,7 +3851,7 @@ const validateConfig = (userConfig = {}, bootstrapConfig) => {
3843
3851
  setBooleanConfig(validatedConfig, "profile", validatedConfig.devMode);
3844
3852
  setBooleanConfig(validatedConfig, "writeLog", false);
3845
3853
  setBooleanConfig(validatedConfig, "buildAppCore", true);
3846
- setBooleanConfig(validatedConfig, "autoprefixCss", false);
3854
+ if (!isObject(validatedConfig.autoprefixCss)) setBooleanConfig(validatedConfig, "autoprefixCss", false);
3847
3855
  setBooleanConfig(validatedConfig, "validateTypes", !validatedConfig._isTesting);
3848
3856
  setBooleanConfig(validatedConfig, "allowInlineScripts", true);
3849
3857
  if (!isString$1(validatedConfig.taskQueue)) validatedConfig.taskQueue = "async";
@@ -3871,29 +3879,159 @@ const validateConfig = (userConfig = {}, bootstrapConfig) => {
3871
3879
  };
3872
3880
  };
3873
3881
  //#endregion
3882
+ //#region src/compiler/docs/css-doc-comments.ts
3883
+ /**
3884
+ * A JSDoc-style comment is `/** ... *\/` or `/*! ... *\/` - postcss's `Comment.text` already
3885
+ * strips the `/*`/`*\/` delimiters, so this checks the leading `*` or `!` that remains.
3886
+ * @param commentText a postcss `Comment` node's `.text`
3887
+ * @returns `true` if the comment is JSDoc-style
3888
+ */
3889
+ const isJsDocComment = (commentText) => commentText.startsWith("*") || commentText.startsWith("!");
3890
+ /**
3891
+ * Strip the leading `*`/`!` marker and per-line `*` prefixes, returning trimmed lines.
3892
+ * @param commentText a postcss `Comment` node's `.text`
3893
+ * @returns the comment's lines, delimiters and leading `*`s stripped
3894
+ */
3895
+ const normalizeJsDocLines = (commentText) => {
3896
+ return commentText.replace(/^[*!]/, "").split(/\r?\n/).map((line) => line.trim().replace(/^\*/, "").trim()).filter((line, i, arr) => !(line === "" && (i === 0 || i === arr.length - 1)));
3897
+ };
3898
+ /**
3899
+ * @param commentText a postcss `Comment` node's `.text`
3900
+ * @returns the comment's lines joined into a single trimmed line of text
3901
+ */
3902
+ const normalizeJsDocText = (commentText) => normalizeJsDocLines(commentText).filter(Boolean).join(" ").trim();
3903
+ /**
3904
+ * @param value a CSS descriptor value, possibly quoted (e.g. a `syntax` descriptor's `"<length>"`)
3905
+ * @returns the value with any surrounding quotes removed
3906
+ */
3907
+ const stripQuotes = (value) => value.replace(/^['"]|['"]$/g, "");
3908
+ /**
3909
+ * Extract the `syntax`/`initial-value` descriptors from a native `@property` at-rule's body.
3910
+ * @param node a postcss `AtRule` node whose `name` is `property`
3911
+ * @returns the extracted descriptors, if present
3912
+ */
3913
+ const parsePropertyAtRuleDescriptors = (node) => {
3914
+ let syntax;
3915
+ let initialValue;
3916
+ node.each((child) => {
3917
+ if (child.type !== "decl") return;
3918
+ if (child.prop === "syntax") syntax = stripQuotes(child.value);
3919
+ else if (child.prop === "initial-value") initialValue = child.value;
3920
+ });
3921
+ return {
3922
+ syntax,
3923
+ initialValue
3924
+ };
3925
+ };
3926
+ /** `--name: docs`, `--name - docs` (as `@attr`/`@slot` use) or `--name docs`. */
3927
+ const CUSTOM_PROPERTY_TAG_RE = /^(--[\w-]+)\s*(?::|-(?=\s))?(.*)$/;
3928
+ /**
3929
+ * @param text the text after a `@prop`/`@cssprop` tag
3930
+ * @returns the custom property name and description, or `undefined` if `text` doesn't start
3931
+ * with a custom property name
3932
+ */
3933
+ const parseCustomPropertyTag = (text) => {
3934
+ const match = text.trim().match(CUSTOM_PROPERTY_TAG_RE);
3935
+ return match ? {
3936
+ name: match[1],
3937
+ docs: match[2].trim()
3938
+ } : void 0;
3939
+ };
3940
+ //#endregion
3874
3941
  //#region src/compiler/docs/style-docs.ts
3875
3942
  /**
3876
3943
  * Parse CSS docstrings that Stencil supports, as documented here:
3877
3944
  * https://stenciljs.com/docs/docs-json#css-variables
3878
3945
  *
3879
- * Docstrings found in the supplied style text will be added to the
3880
- * `styleDocs` param
3946
+ * Docstrings found in the supplied style text will be added to the `styleDocs` param, via three
3947
+ * mechanisms, in order of precedence (an earlier mechanism always wins over a later one for the
3948
+ * same custom property name):
3949
+ * 1. An explicit `@prop`/`@cssprop`/`@cssproperty` annotation in a block comment, anywhere in the file.
3950
+ * 2. A doc-commented `--foo: value;` declaration inside the component's "root" rule - `:host`
3951
+ * for `shadow`/`scoped` encapsulation, or the component's own tag selector for `none`.
3952
+ * 3. A native `@property --foo { ... }` at-rule, with the `syntax`/`initial-value` descriptors
3953
+ * surfaced as `syntax`/`default`. Not scoped - `@property` is a global registration. For a
3954
+ * property already documented by 1 or 2, it still supplies `syntax`/`default`.
3881
3955
  *
3882
3956
  * @param styleDocs the array to hold formatted CSS docstrings
3883
3957
  * @param styleText the CSS text we're working with
3884
3958
  * @param mode a mode associated with the parsed style, if applicable (e.g. this is not applicable for global styles)
3959
+ * @param tag the component's tag name, used to scope auto-detection for `none` encapsulation
3960
+ * @param encapsulation the component's encapsulation, used to pick the "root" scope for auto-detection
3885
3961
  */
3886
- function parseStyleDocs(styleDocs, styleText, mode) {
3962
+ function parseStyleDocs(styleDocs, styleText, mode, tag, encapsulation) {
3887
3963
  if (typeof styleText !== "string") return;
3888
- let match = styleText.match(CSS_DOC_START);
3964
+ let remainingText = styleText;
3965
+ let match = remainingText.match(CSS_DOC_START);
3889
3966
  while (match !== null) {
3890
- styleText = styleText.substring(match.index + match[0].length);
3891
- const endIndex = styleText.indexOf(CSS_DOC_END);
3967
+ remainingText = remainingText.substring(match.index + match[0].length);
3968
+ const endIndex = remainingText.indexOf(CSS_DOC_END);
3892
3969
  if (endIndex === -1) break;
3893
- parseCssComment(styleDocs, styleText.substring(0, endIndex), mode);
3894
- styleText = styleText.substring(endIndex + CSS_DOC_END.length);
3895
- match = styleText.match(CSS_DOC_START);
3970
+ parseCssComment(styleDocs, remainingText.substring(0, endIndex), mode);
3971
+ remainingText = remainingText.substring(endIndex + CSS_DOC_END.length);
3972
+ match = remainingText.match(CSS_DOC_START);
3896
3973
  }
3974
+ if (styleText.includes("--")) parseScopedAndNativeStyleDocs(styleDocs, styleText, mode, tag, encapsulation);
3975
+ }
3976
+ /**
3977
+ * Auto-detect doc-commented custom-property declarations within the component's "root" rule,
3978
+ * and native `@property` at-rule registrations, merging them into `styleDocs`. Mirrors the
3979
+ * equivalent detection for CSS-only components in `css-components/parse-css-component.ts`.
3980
+ *
3981
+ * @param styleDocs the array to hold formatted CSS docstrings - also consulted so an explicit
3982
+ * `@prop`/`@cssprop` annotation always wins over an auto-detected entry for the same name
3983
+ * @param styleText the CSS text we're working with
3984
+ * @param mode a mode associated with the parsed style, if applicable
3985
+ * @param tag the component's tag name
3986
+ * @param encapsulation the component's encapsulation
3987
+ */
3988
+ function parseScopedAndNativeStyleDocs(styleDocs, styleText, mode, tag, encapsulation) {
3989
+ let root;
3990
+ try {
3991
+ root = postcss().process(styleText, { from: void 0 }).root;
3992
+ } catch {
3993
+ return;
3994
+ }
3995
+ const hasName = (name) => styleDocs.some((styleDoc) => styleDoc.name === name);
3996
+ const rootSelector = encapsulation === "shadow" || encapsulation === "scoped" ? ":host" : tag;
3997
+ if (rootSelector) root.walkRules((rule) => {
3998
+ if (!rule.selectors.some((selector) => selector.trim() === rootSelector)) return;
3999
+ const children = rule.nodes;
4000
+ for (let i = 0; i < children.length; i++) {
4001
+ const child = children[i];
4002
+ if (child.type !== "decl" || !child.prop.startsWith("--") || hasName(child.prop)) continue;
4003
+ const prev = children[i - 1];
4004
+ if (!prev || prev.type !== "comment" || !isJsDocComment(prev.text)) continue;
4005
+ styleDocs.push({
4006
+ name: child.prop,
4007
+ docs: normalizeJsDocText(prev.text),
4008
+ annotation: "prop",
4009
+ mode
4010
+ });
4011
+ }
4012
+ });
4013
+ root.walkAtRules("property", (node) => {
4014
+ const propName = node.params.trim();
4015
+ if (!propName.startsWith("--")) return;
4016
+ const { syntax, initialValue } = parsePropertyAtRuleDescriptors(node);
4017
+ const prev = node.prev();
4018
+ const docs = prev && prev.type === "comment" && isJsDocComment(prev.text) ? normalizeJsDocText(prev.text) : "";
4019
+ const existing = styleDocs.find((styleDoc) => styleDoc.name === propName);
4020
+ if (existing) {
4021
+ existing.docs ||= docs;
4022
+ if (syntax) existing.syntax ??= syntax;
4023
+ if (initialValue) existing.default ??= initialValue;
4024
+ return;
4025
+ }
4026
+ styleDocs.push({
4027
+ name: propName,
4028
+ docs,
4029
+ annotation: "prop",
4030
+ mode,
4031
+ ...syntax && { syntax },
4032
+ ...initialValue && { default: initialValue }
4033
+ });
4034
+ });
3897
4035
  }
3898
4036
  /**
3899
4037
  * Parse a CSS comment string and insert it into the provided array of
@@ -3910,13 +4048,11 @@ function parseCssComment(styleDocs, comment, mode) {
3910
4048
  return line;
3911
4049
  }).join(" ").replace(/\t/g, " ").trim();
3912
4050
  while (comment.includes(" ")) comment = comment.replace(" ", " ");
3913
- comment.split(CSS_PROP_ANNOTATION).forEach((d) => {
3914
- const cssDocument = d.trim();
3915
- if (!cssDocument.startsWith(`--`)) return;
3916
- const splt = cssDocument.split(`:`);
4051
+ comment.split(CSS_PROP_ANNOTATION_RE).forEach((d) => {
4052
+ const prop = parseCustomPropertyTag(d);
4053
+ if (!prop) return;
3917
4054
  const styleDoc = {
3918
- name: splt[0].trim(),
3919
- docs: (splt.shift() && splt.join(`:`)).trim(),
4055
+ ...prop,
3920
4056
  annotation: "prop",
3921
4057
  mode
3922
4058
  };
@@ -3933,9 +4069,11 @@ const CSS_DOC_START = /\/\*(\*|!)/;
3933
4069
  */
3934
4070
  const CSS_DOC_END = "*/";
3935
4071
  /**
3936
- * The `@prop` annotation we support within CSS docstrings
4072
+ * The `@prop` annotation we support within CSS docstrings. `@cssprop`/`@cssproperty` are also
4073
+ * recognized as synonyms (the more common names in other web-component-analyzer/docgen
4074
+ * ecosystems).
3937
4075
  */
3938
- const CSS_PROP_ANNOTATION = "@prop";
4076
+ const CSS_PROP_ANNOTATION_RE = /@(?:cssproperty|cssprop|prop)\b/;
3939
4077
  //#endregion
3940
4078
  //#region src/compiler/sys/browser-stubs/browserslist.ts
3941
4079
  const browserslist = (_query) => [];
@@ -4047,6 +4185,39 @@ const DEFAULT_BROWSER_TARGETS = [
4047
4185
  //#endregion
4048
4186
  //#region src/compiler/style/css-parser/parse-css.ts
4049
4187
  /**
4188
+ * Splits a selector list on top-level commas in a single pass: a comma only
4189
+ * splits when it's outside a quoted string and at paren depth 0, so commas in
4190
+ * `:is(:a,:has(:b))` or `[title="a,b"]` aren't treated as separators.
4191
+ * Backslash escapes (inside or outside a string) are skipped so they can't shift state,
4192
+ * so e.g. `[title="a\,b"]` is treated as a single selector.
4193
+ * @param selectors The selector list to split
4194
+ * @returns An array of selectors, with whitespace trimmed from each selector
4195
+ */
4196
+ const splitSelectorList = (selectors) => {
4197
+ const parts = [];
4198
+ let depth = 0;
4199
+ let quote = null;
4200
+ let start = 0;
4201
+ for (let i = 0; i < selectors.length; i++) {
4202
+ const ch = selectors[i];
4203
+ if (quote) {
4204
+ if (ch === "\\") i++;
4205
+ else if (ch === quote) quote = null;
4206
+ continue;
4207
+ }
4208
+ if (ch === "\"" || ch === "'") quote = ch;
4209
+ else if (ch === "\\") i++;
4210
+ else if (ch === "(") depth++;
4211
+ else if (ch === ")") depth = Math.max(0, depth - 1);
4212
+ else if (ch === "," && depth === 0) {
4213
+ parts.push(selectors.slice(start, i));
4214
+ start = i + 1;
4215
+ }
4216
+ }
4217
+ parts.push(selectors.slice(start));
4218
+ return parts.map((s) => s.trim());
4219
+ };
4220
+ /**
4050
4221
  * Parses CSS string input into an AST representation.
4051
4222
  * Used for minification, finding & resolving URLs and during SSR / prerendering, removing unused selectors.
4052
4223
  *
@@ -4171,11 +4342,8 @@ const parseCss = (css, filePath) => {
4171
4342
  const selector = () => {
4172
4343
  const m = match(/^([^{]+)/);
4173
4344
  if (!m) return null;
4174
- return trim(m[0]).replace(/\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*\/+/g, "").replace(/"(?:\\"|[^"])*"|'(?:\\'|[^'])*'/g, function(str) {
4175
- return str.replace(/,/g, "‌");
4176
- }).split(/\s*(?![^(]*\)),\s*/).map(function(s) {
4177
- return s.replace(/\u200C/g, ",");
4178
- });
4345
+ const cleaned = trim(m[0]).replace(/\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*\/+/g, "");
4346
+ return splitSelectorList(cleaned);
4179
4347
  };
4180
4348
  const declaration = () => {
4181
4349
  const pos = position();
@@ -4773,12 +4941,10 @@ const optimizeCss = async (inputOpts) => {
4773
4941
  const CREATE_EVENT = "__stencil_createEvent";
4774
4942
  const DEFINE_CUSTOM_ELEMENT = "__stencil_defineCustomElement";
4775
4943
  const GET_ELEMENT = "__stencil_getElement";
4776
- const HOST = "__stencil_Host";
4777
4944
  const HTML_ELEMENT = "HTMLElement";
4778
4945
  const PROXY_CUSTOM_ELEMENT = "__stencil_proxyCustomElement";
4779
4946
  const REGISTER_INSTANCE = "__stencil_registerInstance";
4780
4947
  const REGISTER_HOST = "__stencil_registerHost";
4781
- const H = "__stencil_h";
4782
4948
  const TRANSFORM_TAG = "__stencil_transformTag";
4783
4949
  const GET_REGISTRY = "__stencil_getRegistry";
4784
4950
  const INJECT_SIDE_EFFECT_STYLE = "__stencil_injectSideEffectStyle";
@@ -4786,9 +4952,7 @@ const RUNTIME_APIS = {
4786
4952
  createEvent: `createEvent as ${CREATE_EVENT}`,
4787
4953
  defineCustomElement: `defineCustomElement as ${DEFINE_CUSTOM_ELEMENT}`,
4788
4954
  getElement: `getElement as ${GET_ELEMENT}`,
4789
- h: `h as ${H}`,
4790
4955
  legacyH: `h`,
4791
- Host: `Host as ${HOST}`,
4792
4956
  HTMLElement: HTML_ELEMENT,
4793
4957
  proxyCustomElement: `proxyCustomElement as ${PROXY_CUSTOM_ELEMENT}`,
4794
4958
  registerHost: `registerHost as ${REGISTER_HOST}`,
@@ -8268,7 +8432,7 @@ function hostRefElementInternalsPropAccess() {
8268
8432
  const updateLazyComponentConstructor = (classMembers, classNode, moduleFile, cmp) => {
8269
8433
  const cstrMethodArgs = [ts$1.factory.createParameterDeclaration(void 0, void 0, ts$1.factory.createIdentifier(HOST_REF_ARG))];
8270
8434
  const cstrStatements = [
8271
- registerInstanceStatement(moduleFile),
8435
+ registerInstanceStatement(moduleFile, classNode),
8272
8436
  ...addCreateEvents(moduleFile, cmp),
8273
8437
  ...createLazyAttachInternalsBinding(cmp)
8274
8438
  ];
@@ -8277,17 +8441,26 @@ const updateLazyComponentConstructor = (classMembers, classNode, moduleFile, cmp
8277
8441
  /**
8278
8442
  * Create a statement containing an expression calling the `registerInstance`
8279
8443
  * helper with the {@link d.HostRef} argument passed to the lazy element
8280
- * constructor
8444
+ * constructor.
8445
+ *
8446
+ * The call is guarded by `new.target === <ClassName>` so only the
8447
+ * most-derived component class registers the instance. A base component's
8448
+ * constructor runs (via `super()`) before the derived class's field
8449
+ * initializers, so registering there would wire up props and state before the
8450
+ * derived class has applied its own defaults.
8281
8451
  *
8282
8452
  * **NOTE** this mutates the `moduleFile` param to add an import of the
8283
8453
  * `registerInstance` method from the Stencil core component runtime API.
8284
8454
  *
8285
8455
  * @param moduleFile information about a module containing a Stencil component
8286
- * @returns an expression statement for a call to the `registerInstance` helper
8456
+ * @param classNode the class declaration of the component
8457
+ * @returns a statement calling the `registerInstance` helper
8287
8458
  */
8288
- const registerInstanceStatement = (moduleFile) => {
8459
+ const registerInstanceStatement = (moduleFile, classNode) => {
8289
8460
  addCoreRuntimeApi(moduleFile, RUNTIME_APIS.registerInstance);
8290
- return ts$1.factory.createExpressionStatement(ts$1.factory.createCallExpression(ts$1.factory.createIdentifier(REGISTER_INSTANCE), void 0, [ts$1.factory.createThis(), ts$1.factory.createIdentifier(HOST_REF_ARG)]));
8461
+ const registerCall = ts$1.factory.createExpressionStatement(ts$1.factory.createCallExpression(ts$1.factory.createIdentifier(REGISTER_INSTANCE), void 0, [ts$1.factory.createThis(), ts$1.factory.createIdentifier(HOST_REF_ARG)]));
8462
+ if (!classNode.name) return registerCall;
8463
+ return ts$1.factory.createIfStatement(ts$1.factory.createStrictEquality(ts$1.factory.createMetaProperty(ts$1.SyntaxKind.NewKeyword, ts$1.factory.createIdentifier("target")), ts$1.factory.createIdentifier(classNode.name.text)), registerCall);
8291
8464
  };
8292
8465
  //#endregion
8293
8466
  //#region src/compiler/transformers/remove-static-meta-properties.ts
@@ -8349,23 +8522,48 @@ const TYPE_LIBRARY = {};
8349
8522
  * @param typeName the type's name
8350
8523
  * @param checker a {@link ts.TypeChecker} instance
8351
8524
  * @param pathToTypeModule the path to the home module of the type
8525
+ * @param symbol the symbol the type was looked up by, if known
8352
8526
  * @returns the unique ID for the type in question
8353
8527
  */
8354
- function addToLibrary(type, typeName, checker, pathToTypeModule) {
8528
+ function addToLibrary(type, typeName, checker, pathToTypeModule, symbol) {
8355
8529
  pathToTypeModule = relative(process.cwd(), pathToTypeModule);
8356
8530
  if (pathToTypeModule.startsWith("node_modules")) return "node_modules::" + typeName;
8357
8531
  const id = getTypeId(pathToTypeModule, typeName);
8358
8532
  if (!type.isTypeParameter() && !(id in TYPE_LIBRARY)) {
8359
- const declaration = getTypeDeclaration(checker, type);
8360
- if (declaration !== "") TYPE_LIBRARY[id] = {
8361
- declaration,
8362
- docstring: getTypeDocstring(type, checker),
8363
- path: pathToTypeModule
8364
- };
8533
+ const alias = symbol?.declarations?.find(ts$1.isTypeAliasDeclaration);
8534
+ const declaration = alias ? alias.getText() : getTypeDeclaration(checker, type);
8535
+ if (declaration !== "") {
8536
+ TYPE_LIBRARY[id] = {
8537
+ declaration,
8538
+ docstring: getTypeDocstring(type, checker, alias ? symbol : void 0),
8539
+ path: pathToTypeModule
8540
+ };
8541
+ if (alias) addReferencedTypes(alias.type, checker);
8542
+ }
8365
8543
  }
8366
8544
  return id;
8367
8545
  }
8368
8546
  /**
8547
+ * Add the project types referenced in a type node (e.g. `Box` and `Item` in `Box<Item[]>`) to the
8548
+ * library. Types from TypeScript's lib files or other packages are left out.
8549
+ *
8550
+ * @param node the type node to search
8551
+ * @param checker a {@link ts.TypeChecker} instance
8552
+ */
8553
+ const addReferencedTypes = (node, checker) => {
8554
+ const visit = (child) => {
8555
+ if (ts$1.isTypeReferenceNode(child)) {
8556
+ const name = ts$1.isIdentifier(child.typeName) ? child.typeName : child.typeName.right;
8557
+ const nameSymbol = checker.getSymbolAtLocation(name);
8558
+ const refSymbol = nameSymbol && resolveAliasedSymbol(checker, nameSymbol);
8559
+ const sourceFile = (refSymbol?.declarations?.find(isTypeDeclLike))?.getSourceFile();
8560
+ if (sourceFile && !sourceFile.hasNoDefaultLib && !isNodeModulePath(sourceFile.fileName)) addToLibrary(checker.getDeclaredTypeOfSymbol(refSymbol), refSymbol.getName(), checker, normalizePath(sourceFile.fileName, false), refSymbol);
8561
+ }
8562
+ ts$1.forEachChild(child, visit);
8563
+ };
8564
+ visit(node);
8565
+ };
8566
+ /**
8369
8567
  * Given a `ts.SourceFile` representing an importer module and an import path
8370
8568
  * representing the path to another module, return the {@link ts.SourceFile}
8371
8569
  * corresponding to the imported module.
@@ -8443,10 +8641,11 @@ function getTypeDeclaration(checker, type) {
8443
8641
  *
8444
8642
  * @param type the type in question
8445
8643
  * @param checker a {@link ts.TypeChecker} instance
8644
+ * @param aliasSymbol the symbol of the alias the type was declared as, if any
8446
8645
  * @returns the type's docstring if present, else an empty string
8447
8646
  */
8448
- function getTypeDocstring(type, checker) {
8449
- const symbol = type?.symbol;
8647
+ function getTypeDocstring(type, checker, aliasSymbol) {
8648
+ const symbol = aliasSymbol ?? type?.symbol;
8450
8649
  return symbol ? ts$1.displayPartsToString(symbol.getDocumentationComment(checker)) : "";
8451
8650
  }
8452
8651
  /**
@@ -8717,6 +8916,9 @@ const objectLiteralToObjectMap = (objectLiteral, typeChecker, diagnostics, error
8717
8916
  case ts$1.SyntaxKind.FalseKeyword:
8718
8917
  val = false;
8719
8918
  break;
8919
+ case ts$1.SyntaxKind.NullKeyword:
8920
+ val = null;
8921
+ break;
8720
8922
  case ts$1.SyntaxKind.Identifier:
8721
8923
  const escapedText = propAssignment.initializer.escapedText;
8722
8924
  if (escapedText === "String") val = String;
@@ -8903,7 +9105,7 @@ const getAllTypeReferences = (checker, node) => {
8903
9105
  */
8904
9106
  const getTypeReferenceLocation = (typeName, type, sourceFile, checker, program) => {
8905
9107
  const importTypeDeclaration = sourceFile.statements.find((st) => {
8906
- if (!(ts$1.isImportDeclaration(st) && st.importClause && ts$1.isImportClause(st.importClause) && st.importClause.namedBindings && ts$1.isNamedImports(st.importClause.namedBindings) && Array.isArray(st.importClause.namedBindings.elements) && st.importClause.namedBindings.elements.find((nbe) => nbe.name.getText() === typeName))) return false;
9108
+ if (!(ts$1.isImportDeclaration(st) && st.importClause && ts$1.isImportClause(st.importClause) && st.importClause.namedBindings && ts$1.isNamedImports(st.importClause.namedBindings) && Array.isArray(st.importClause.namedBindings.elements) && st.importClause.namedBindings.elements.find((nbe) => nbe.name.text === typeName))) return false;
8907
9109
  return true;
8908
9110
  });
8909
9111
  const namedImportBindings = importTypeDeclaration?.importClause?.namedBindings;
@@ -8912,7 +9114,7 @@ const getTypeReferenceLocation = (typeName, type, sourceFile, checker, program)
8912
9114
  const options = program.getCompilerOptions();
8913
9115
  const importHomeModule = getHomeModule(sourceFile, localImportPath, options, ts$1.createCompilerHost(options), program);
8914
9116
  if (importHomeModule) {
8915
- const importElement = namedImportBindings.elements.find((nbe) => nbe.name.getText() === typeName);
9117
+ const importElement = namedImportBindings.elements.find((nbe) => nbe.name.text === typeName);
8916
9118
  const importName = importElement.name;
8917
9119
  const originalTypeName = getOriginalTypeName(importName, checker);
8918
9120
  const importedAs = importElement.propertyName ? importElement.propertyName.getText() : typeName;
@@ -8928,7 +9130,7 @@ const getTypeReferenceLocation = (typeName, type, sourceFile, checker, program)
8928
9130
  return {
8929
9131
  location: "import",
8930
9132
  path: localImportPath,
8931
- id: addToLibrary(type, originalTypeName, checker, normalizePath(typeSourceFile.fileName, false)),
9133
+ id: addToLibrary(type, originalTypeName, checker, normalizePath(typeSourceFile.fileName, false), importedSymbol),
8932
9134
  referenceLocation: importedAs
8933
9135
  };
8934
9136
  }
@@ -8953,7 +9155,8 @@ const getTypeReferenceLocation = (typeName, type, sourceFile, checker, program)
8953
9155
  return statementModifiers?.some((modifier) => modifier.kind === ts$1.SyntaxKind.DefaultKeyword) ? { isDefault: true } : {};
8954
9156
  }, void 0);
8955
9157
  if (localExport) {
8956
- const id = addToLibrary(type, typeName, checker, sourceFile.fileName);
9158
+ const localDecl = findTypeWithName(sourceFile, typeName);
9159
+ const id = addToLibrary(type, typeName, checker, sourceFile.fileName, localDecl && checker.getSymbolAtLocation(localDecl.name));
8957
9160
  return {
8958
9161
  location: "local",
8959
9162
  path: sourceFile.fileName,
@@ -8979,7 +9182,7 @@ const getTypeReferenceLocation = (typeName, type, sourceFile, checker, program)
8979
9182
  return {
8980
9183
  location: "import",
8981
9184
  path: localImportPath,
8982
- id: addToLibrary(type, declarationName === "default" ? typeName : declarationName, checker, normalizePath(declaration.getSourceFile().fileName, false)),
9185
+ id: addToLibrary(type, declarationName === "default" ? typeName : declarationName, checker, normalizePath(declaration.getSourceFile().fileName, false), importedSymbol),
8983
9186
  isDefault: true
8984
9187
  };
8985
9188
  }
@@ -9187,9 +9390,9 @@ const serializeSymbol = (checker, symbol) => {
9187
9390
  };
9188
9391
  };
9189
9392
  /**
9190
- * Maps a TypeScript 4.3+ JSDocTagInfo to a flattened Stencil CompilerJsDocTagInfo.
9393
+ * Maps a TypeScript 4.3+ JSDocTagInfo to a flattened Stencil JsonDocsTag.
9191
9394
  * @param tags A readonly array of JSDocTagInfo objects.
9192
- * @returns An array of CompilerJsDocTagInfo objects.
9395
+ * @returns An array of JsonDocsTag objects.
9193
9396
  */
9194
9397
  const mapJSDocTagInfo = (tags) => {
9195
9398
  return tags.map((tag) => ({
@@ -9309,11 +9512,11 @@ function foundSuper(constructorBodyStatements) {
9309
9512
  * @param statements a list of statements which should be added to the
9310
9513
  * constructor
9311
9514
  * @param parameters an optional list of parameters for the constructor
9312
- * @param includeFalseArg whether to include a `false` argument in the `super()` call.
9313
- * This is used in native Stencil components which extend other Stencil components to stop the base component from being initialized.
9515
+ * @param superArgs the arguments for the `super()` call (see {@link SuperArgs}). `'false'` also
9516
+ * replaces an existing `super()` call.
9314
9517
  * @returns a list of updated class elements
9315
9518
  */
9316
- const updateConstructor = (classNode, classMembers, statements, parameters, includeFalseArg) => {
9519
+ const updateConstructor = (classNode, classMembers, statements, parameters, superArgs) => {
9317
9520
  const constructorIndex = classMembers.findIndex((m) => ts$1.isConstructorDeclaration(m) && m.body != null);
9318
9521
  const constructorMethod = classMembers[constructorIndex];
9319
9522
  if (constructorIndex < 0 && !statements?.length && !needsSuper(classNode)) return classMembers;
@@ -9321,14 +9524,14 @@ const updateConstructor = (classNode, classMembers, statements, parameters, incl
9321
9524
  const constructorBodyStatements = constructorMethod.body?.statements;
9322
9525
  let foundSuperCall = foundSuper(constructorBodyStatements);
9323
9526
  if (!foundSuperCall && needsSuper(classNode)) statements = [
9324
- createConstructorBodyWithSuper(includeFalseArg),
9527
+ createConstructorBodyWithSuper(superArgs),
9325
9528
  ...statements,
9326
9529
  ...constructorBodyStatements
9327
9530
  ];
9328
9531
  else {
9329
9532
  const updatedStatements = constructorBodyStatements.filter((s) => s !== foundSuperCall);
9330
9533
  if (foundSuperCall) {
9331
- if (includeFalseArg) foundSuperCall = createConstructorBodyWithSuper(includeFalseArg);
9534
+ if (superArgs === "false") foundSuperCall = createConstructorBodyWithSuper(superArgs);
9332
9535
  statements = [
9333
9536
  foundSuperCall,
9334
9537
  ...statements,
@@ -9338,7 +9541,7 @@ const updateConstructor = (classNode, classMembers, statements, parameters, incl
9338
9541
  }
9339
9542
  classMembers[constructorIndex] = ts$1.factory.updateConstructorDeclaration(constructorMethod, retrieveTsModifiers(constructorMethod), [...parameters ?? [], ...constructorMethod.parameters], ts$1.factory.updateBlock(constructorMethod?.body ?? ts$1.factory.createBlock([]), statements));
9340
9543
  } else {
9341
- if (needsSuper(classNode)) statements = [createConstructorBodyWithSuper(includeFalseArg), ...statements];
9544
+ if (needsSuper(classNode)) statements = [createConstructorBodyWithSuper(superArgs), ...statements];
9342
9545
  classMembers.unshift(ts$1.factory.createConstructorDeclaration(void 0, parameters ?? [], ts$1.factory.createBlock(statements, true)));
9343
9546
  }
9344
9547
  return classMembers;
@@ -9357,12 +9560,12 @@ const needsSuper = (classDeclaration) => {
9357
9560
  };
9358
9561
  /**
9359
9562
  * Create a statement with a call to `super()` suitable for including in the body of a constructor.
9360
- * @param includeFalseArg whether to include a `false` argument in the `super()` call.
9361
- * This is used in native Stencil components which extend other Stencil components to stop the base component from being initialized.
9362
- * @returns a {@link ts.ExpressionStatement} node equivalent to `super()`
9563
+ * @param superArgs the arguments for the call (see {@link SuperArgs})
9564
+ * @returns a {@link ts.ExpressionStatement} node for the `super()` call
9363
9565
  */
9364
- const createConstructorBodyWithSuper = (includeFalseArg) => {
9365
- return ts$1.factory.createExpressionStatement(ts$1.factory.createCallExpression(ts$1.factory.createIdentifier("super"), void 0, includeFalseArg ? [ts$1.factory.createFalse()] : void 0));
9566
+ const createConstructorBodyWithSuper = (superArgs) => {
9567
+ const args = superArgs === "false" ? [ts$1.factory.createFalse()] : superArgs === "forward" ? [ts$1.factory.createSpreadElement(ts$1.factory.createIdentifier("arguments"))] : void 0;
9568
+ return ts$1.factory.createExpressionStatement(ts$1.factory.createCallExpression(ts$1.factory.createIdentifier("super"), void 0, args));
9366
9569
  };
9367
9570
  /**
9368
9571
  * Given a {@link ts.PropertyDeclaration} node get its name as a string
@@ -9600,7 +9803,7 @@ const transformCssToEsmModule = (input) => {
9600
9803
  defaultVarName: createCssVarName(input.file, input.mode),
9601
9804
  styleDocs: []
9602
9805
  };
9603
- if (input.docs) parseStyleDocs(results.styleDocs, input.input, input.mode);
9806
+ if (input.docs) parseStyleDocs(results.styleDocs, input.input, input.mode, input.tag, input.encapsulation);
9604
9807
  try {
9605
9808
  const varNames = /* @__PURE__ */ new Set([results.defaultVarName]);
9606
9809
  if (isString$1(input.tag) && input.encapsulation === "scoped") {
@@ -9697,7 +9900,7 @@ const getCssToEsmImports = (varNames, cssText, filePath, modeName) => {
9697
9900
  isNodeModule: false
9698
9901
  };
9699
9902
  if (!isLocalCssImport(cssImportData.srcImportText)) continue;
9700
- else if (cssImportData.url === "stencil-globals" || cssImportData.url === "stencil-hydrate") continue;
9903
+ else if (cssImportData.url === "stencil-component-globals" || cssImportData.url === "stencil-hydrate" || cssImportData.url === "stencil-css-components") continue;
9701
9904
  else if (isCssNodeModule(cssImportData.url)) {
9702
9905
  cssImportData.filePath = cssImportData.url.substring(1);
9703
9906
  cssImportData.isNodeModule = true;
@@ -9912,6 +10115,7 @@ var BuildContext = class {
9912
10115
  completedTasks = [];
9913
10116
  compilerCtx;
9914
10117
  components = [];
10118
+ cssOnlyComponents = [];
9915
10119
  componentGraph = /* @__PURE__ */ new Map();
9916
10120
  config;
9917
10121
  data = {};
@@ -9953,6 +10157,7 @@ var BuildContext = class {
9953
10157
  styleBuildCount = 0;
9954
10158
  stylesPromise = null;
9955
10159
  stylesUpdated = [];
10160
+ globalStylesUpdated = [];
9956
10161
  timeSpan = null;
9957
10162
  timestamp;
9958
10163
  transpileBuildCount = 0;
@@ -10133,12 +10338,18 @@ var CompilerContext = class {
10133
10338
  */
10134
10339
  prevStylesMap = /* @__PURE__ */ new Map();
10135
10340
  globalStyleCache = /* @__PURE__ */ new Map();
10341
+ cssOnlyComponentsCache = /* @__PURE__ */ new Map();
10342
+ stencilCss;
10343
+ globalStyleVirtualImports = /* @__PURE__ */ new Map();
10136
10344
  styleModeNames = /* @__PURE__ */ new Set();
10137
10345
  worker = null;
10138
10346
  reset() {
10139
10347
  this.cache.clear();
10140
10348
  this.cssModuleImports.clear();
10141
10349
  this.globalStyleCache.clear();
10350
+ this.cssOnlyComponentsCache.clear();
10351
+ this.stencilCss = void 0;
10352
+ this.globalStyleVirtualImports.clear();
10142
10353
  this.collections.length = 0;
10143
10354
  this.compilerOptions = null;
10144
10355
  this.hasSuccessfulBuild = false;
@@ -10229,6 +10440,7 @@ const resetModuleLegacy = (moduleFile) => {
10229
10440
  moduleFile.externalImports.length = 0;
10230
10441
  moduleFile.isCollectionDependency = false;
10231
10442
  moduleFile.localImports.length = 0;
10443
+ moduleFile.functionalComponentDeps.length = 0;
10232
10444
  moduleFile.originalCollectionComponentPath = null;
10233
10445
  moduleFile.originalImports.length = 0;
10234
10446
  moduleFile.hasVdomXlink = false;
@@ -10327,7 +10539,7 @@ const performAutomaticKeyInsertion = (transformCtx) => {
10327
10539
  * @returns the result of handling the node
10328
10540
  */
10329
10541
  function findRenderMethodVisitor(node) {
10330
- if (ts$1.isMethodDeclaration(node) && node.name.getText() === "render" && numReturnStatements(node) === 1) {
10542
+ if (ts$1.isMethodDeclaration(node) && ts$1.isIdentifier(node.name) && node.name.text === "render" && numReturnStatements(node) === 1) {
10331
10543
  resetKeyCounter();
10332
10544
  return ts$1.visitEachChild(node, jsxElementVisitor, transformCtx);
10333
10545
  } else return ts$1.visitEachChild(node, findRenderMethodVisitor, transformCtx);
@@ -10743,31 +10955,6 @@ const createIdentifierFromStyleIdentifier = (styleIdentifier, externalStyleIds)
10743
10955
  return ts$1.factory.createBinaryExpression(createIdentifierFromStyleIdentifier(styleIdentifier, [id]), ts$1.SyntaxKind.PlusToken, createIdentifierFromStyleIdentifier(styleIdentifier, externalStyleIds.slice(1)));
10744
10956
  };
10745
10957
  //#endregion
10746
- //#region src/compiler/transformers/host-data-transform.ts
10747
- const transformHostData = (classElements, moduleFile) => {
10748
- if (classElements.some((e) => ts$1.isMethodDeclaration(e) && e.name.escapedText === "hostData")) {
10749
- const renderIndex = classElements.findIndex((e) => ts$1.isMethodDeclaration(e) && e.name.escapedText === "render");
10750
- if (renderIndex >= 0) {
10751
- const renderMethod = classElements[renderIndex];
10752
- classElements[renderIndex] = ts$1.factory.updateMethodDeclaration(renderMethod, retrieveModifierLike(renderMethod), renderMethod.asteriskToken, ts$1.factory.createIdentifier(INTERNAL_RENDER), renderMethod.questionToken, renderMethod.typeParameters, renderMethod.parameters, renderMethod.type, renderMethod.body);
10753
- }
10754
- classElements.push(syntheticRender(moduleFile, renderIndex >= 0));
10755
- }
10756
- };
10757
- const syntheticRender = (moduleFile, hasRender) => {
10758
- addCoreRuntimeApi(moduleFile, RUNTIME_APIS.Host);
10759
- addCoreRuntimeApi(moduleFile, RUNTIME_APIS.h);
10760
- const hArguments = [ts$1.factory.createIdentifier(HOST), ts$1.factory.createCallExpression(ts$1.factory.createPropertyAccessExpression(ts$1.factory.createThis(), "hostData"), void 0, void 0)];
10761
- if (hasRender) hArguments.push(ts$1.factory.createCallExpression(ts$1.factory.createPropertyAccessExpression(ts$1.factory.createThis(), INTERNAL_RENDER), void 0, void 0));
10762
- /**
10763
- * render() {
10764
- * return h(arguments);
10765
- * }
10766
- */
10767
- return ts$1.factory.createMethodDeclaration(void 0, void 0, "render", void 0, void 0, [], void 0, ts$1.factory.createBlock([ts$1.factory.createReturnStatement(ts$1.factory.createCallExpression(ts$1.factory.createIdentifier(H), void 0, hArguments))]));
10768
- };
10769
- const INTERNAL_RENDER = "__stencil_render";
10770
- //#endregion
10771
10958
  //#region src/compiler/transformers/reactive-handler-meta-transform.ts
10772
10959
  /**
10773
10960
  * Add a getter to a class for a static representation of the watchers
@@ -10849,7 +11036,6 @@ const updateLazyComponentMembers = (transformOpts, styleStatements, classNode, m
10849
11036
  addReactivePropHandlers(classMembers, cmp, "watchers");
10850
11037
  addReactivePropHandlers(classMembers, cmp, "serializers");
10851
11038
  addReactivePropHandlers(classMembers, cmp, "deserializers");
10852
- transformHostData(classMembers, moduleFile);
10853
11039
  if (transformOpts.style === "static") addStaticStylePropertyToClass(styleStatements, cmp, buildCtx);
10854
11040
  return classMembers;
10855
11041
  };
@@ -11072,7 +11258,7 @@ const updateNativeConstructor = (classMembers, moduleFile, cmp, classNode) => {
11072
11258
  ...addCreateEvents(moduleFile, cmp),
11073
11259
  ...createNativeAttachInternalsBinding(cmp)
11074
11260
  ];
11075
- updateConstructor(classNode, classMembers, nativeCstrStatements, cstrMethodArgs, cmp.doesExtend);
11261
+ updateConstructor(classNode, classMembers, nativeCstrStatements, cstrMethodArgs, cmp.doesExtend ? "false" : void 0);
11076
11262
  };
11077
11263
  /**
11078
11264
  * Generates a series of expression statements used to help initialize a Stencil component
@@ -11233,7 +11419,7 @@ const updateNativeSuperClass = (node, moduleFile, transformOpts) => {
11233
11419
  const ctor = withHeritageClauses.members.find(ts$1.isConstructorDeclaration);
11234
11420
  if (!foundSuper(ctor?.body?.statements)) {
11235
11421
  const params = Array.from(ctor?.parameters ?? []);
11236
- withHeritageClauses = ts$1.factory.updateClassDeclaration(withHeritageClauses, withHeritageClauses.modifiers, withHeritageClauses.name, withHeritageClauses.typeParameters, withHeritageClauses.heritageClauses, updateConstructor(withHeritageClauses, Array.from(withHeritageClauses.members), [], params, true));
11422
+ withHeritageClauses = ts$1.factory.updateClassDeclaration(withHeritageClauses, withHeritageClauses.modifiers, withHeritageClauses.name, withHeritageClauses.typeParameters, withHeritageClauses.heritageClauses, updateConstructor(withHeritageClauses, Array.from(withHeritageClauses.members), [], params, "false"));
11237
11423
  }
11238
11424
  return updateComponentClass(transformOpts, withHeritageClauses, withHeritageClauses.heritageClauses, removeStaticMetaProperties(withHeritageClauses));
11239
11425
  };
@@ -11269,7 +11455,7 @@ const updateNativeHostComponentHeritageClauses = (classNode, moduleFile) => {
11269
11455
  const updateNativeBaseClass = (node, moduleFile) => {
11270
11456
  const withHeritageClauses = updateNativeHostComponentHeritageClauses(node, moduleFile);
11271
11457
  const members = removeStaticMetaProperties(withHeritageClauses);
11272
- const membersWithCtor = updateConstructor(withHeritageClauses, members, [], void 0, false);
11458
+ const membersWithCtor = updateConstructor(withHeritageClauses, members, [], void 0);
11273
11459
  return ts$1.factory.updateClassDeclaration(withHeritageClauses, withHeritageClauses.modifiers, withHeritageClauses.name, withHeritageClauses.typeParameters, withHeritageClauses.heritageClauses, membersWithCtor);
11274
11460
  };
11275
11461
  /**
@@ -11297,7 +11483,6 @@ const updateNativeHostComponentMembers = (transformOpts, classNode, moduleFile,
11297
11483
  addReactivePropHandlers(classMembers, cmp, "deserializers");
11298
11484
  if (cmp.isPlain) addNativeComponentMeta(classMembers, cmp);
11299
11485
  if (transformOpts.style === "static") addNativeStaticStyle(classMembers, cmp, buildCtx);
11300
- transformHostData(classMembers, moduleFile);
11301
11486
  return classMembers;
11302
11487
  };
11303
11488
  //#endregion
@@ -11500,110 +11685,6 @@ const isDecoratorNamed = (propName) => {
11500
11685
  };
11501
11686
  };
11502
11687
  //#endregion
11503
- //#region src/compiler/transformers/decorators-to-static/attach-internals.ts
11504
- /**
11505
- * Convert the attach internals decorator to static, saving the name of the
11506
- * decorated property so an `ElementInternals` object can be bound to it later
11507
- * on.
11508
- *
11509
- * The `@AttachInternals` decorator is used to indicate a field on a class
11510
- * where the return value of the `HTMLElement.attachInternals` method should be
11511
- * bound. This then allows component authors to use that interface to make their
11512
- * Stencil components rich participants in whatever `HTMLFormElement` instances
11513
- * they find themselves inside of in the future.
11514
- *
11515
- * The decorator also accepts an optional `states` option to define initial
11516
- * custom states that will be set on the `ElementInternals.states` CustomStateSet.
11517
- * Each state property can have a JSDoc comment that will be extracted for documentation.
11518
- *
11519
- * **Note**: this function will mutate the `newMembers` parameter in order to
11520
- * add new members to the class.
11521
- *
11522
- * @param diagnostics for reporting errors and warnings
11523
- * @param decoratedMembers the decorated members found on the class
11524
- * @param newMembers an out param for new class members
11525
- * @param typeChecker a TypeScript typechecker, needed for resolving the prop
11526
- * declaration name
11527
- * @param decoratorName the name of the decorator to look for
11528
- */
11529
- const attachInternalsDecoratorsToStatic = (diagnostics, decoratedMembers, newMembers, typeChecker, decoratorName) => {
11530
- const attachInternalsMembers = decoratedMembers.filter(ts$1.isPropertyDeclaration).filter((prop) => {
11531
- return !!retrieveTsDecorators(prop)?.find(isDecoratorNamed(decoratorName));
11532
- });
11533
- if (attachInternalsMembers.length === 0) return;
11534
- if (attachInternalsMembers.length > 1) {
11535
- const error = buildError(diagnostics);
11536
- error.messageText = `Stencil does not support adding more than one AttachInternals() decorator to a component`;
11537
- return;
11538
- }
11539
- const [decoratedProp] = attachInternalsMembers;
11540
- const { staticName: name } = tsPropDeclName(decoratedProp, typeChecker);
11541
- const decorator = retrieveTsDecorators(decoratedProp)?.find(isDecoratorNamed(decoratorName));
11542
- const customStates = parseCustomStatesFromDecorator(decorator, typeChecker);
11543
- const formAssociated = parseFormAssociatedFromDecorator(decorator);
11544
- newMembers.push(createStaticGetter("attachInternalsMemberName", convertValueToLiteral(name)));
11545
- if (customStates.length > 0) newMembers.push(createStaticGetter("attachInternalsCustomStates", convertValueToLiteral(customStates)));
11546
- if (formAssociated) newMembers.push(createStaticGetter("formAssociated", convertValueToLiteral(true)));
11547
- };
11548
- /**
11549
- * Parse the formAssociated option from the decorator.
11550
- * Returns true (form-associated) unless explicitly set to false.
11551
- *
11552
- * @param decorator the decorator node to parse
11553
- * @returns whether the component should be form-associated
11554
- */
11555
- function parseFormAssociatedFromDecorator(decorator) {
11556
- if (!decorator || !ts$1.isCallExpression(decorator.expression)) return true;
11557
- const [firstArg] = decorator.expression.arguments;
11558
- if (!firstArg || !ts$1.isObjectLiteralExpression(firstArg)) return true;
11559
- const formAssociatedProp = firstArg.properties.find((prop) => ts$1.isPropertyAssignment(prop) && ts$1.isIdentifier(prop.name) && prop.name.text === "formAssociated");
11560
- if (!formAssociatedProp) return true;
11561
- if (formAssociatedProp.initializer.kind === ts$1.SyntaxKind.FalseKeyword) return false;
11562
- return true;
11563
- }
11564
- /**
11565
- * Parse custom states from the decorator AST, including JSDoc comments.
11566
- *
11567
- * Supports JSDoc comments on state properties:
11568
- * ```ts
11569
- * @AttachInternals({
11570
- * states: {
11571
- * hovered: false,
11572
- * /&#42;&#42; Whether is currently active &#42;/
11573
- * active: true
11574
- * }
11575
- * })
11576
- * ```
11577
- *
11578
- * @param decorator the decorator node to parse
11579
- * @param typeChecker a TypeScript typechecker for resolving symbols
11580
- * @returns array of custom state metadata with docs
11581
- */
11582
- function parseCustomStatesFromDecorator(decorator, typeChecker) {
11583
- if (!decorator || !ts$1.isCallExpression(decorator.expression)) return [];
11584
- const [firstArg] = decorator.expression.arguments;
11585
- if (!firstArg || !ts$1.isObjectLiteralExpression(firstArg)) return [];
11586
- const statesProp = firstArg.properties.find((prop) => ts$1.isPropertyAssignment(prop) && ts$1.isIdentifier(prop.name) && prop.name.text === "states");
11587
- if (!statesProp || !ts$1.isObjectLiteralExpression(statesProp.initializer)) return [];
11588
- const customStates = [];
11589
- for (const prop of statesProp.initializer.properties) {
11590
- if (!ts$1.isPropertyAssignment(prop)) continue;
11591
- const stateName = ts$1.isIdentifier(prop.name) ? prop.name.text : ts$1.isStringLiteral(prop.name) ? prop.name.text : null;
11592
- if (!stateName) continue;
11593
- let initialValue = false;
11594
- if (prop.initializer.kind === ts$1.SyntaxKind.TrueKeyword) initialValue = true;
11595
- else if (prop.initializer.kind === ts$1.SyntaxKind.FalseKeyword) initialValue = false;
11596
- const symbol = typeChecker.getSymbolAtLocation(prop.name);
11597
- const docs = symbol ? ts$1.displayPartsToString(symbol.getDocumentationComment(typeChecker)) : "";
11598
- customStates.push({
11599
- name: stateName,
11600
- initialValue,
11601
- docs
11602
- });
11603
- }
11604
- return customStates;
11605
- }
11606
- //#endregion
11607
11688
  //#region src/compiler/transformers/decorators-to-static/style-to-static.ts
11608
11689
  const styleToStatic = (newMembers, componentOptions) => {
11609
11690
  const defaultModeStyles = [];
@@ -11668,6 +11749,12 @@ const normalizeStyleUrl = (style) => {
11668
11749
  //#region src/compiler/transformers/decorators-to-static/component-decorator.ts
11669
11750
  let hasShownDeprecatedApiError = false;
11670
11751
  /**
11752
+ * Reset the deprecated API error flag. Call this at the start of each build.
11753
+ */
11754
+ const resetDeprecatedApiWarning = () => {
11755
+ hasShownDeprecatedApiError = false;
11756
+ };
11757
+ /**
11671
11758
  * Perform code generation to create new class members for a Stencil component
11672
11759
  * which will drive the runtime functionality specified by various options
11673
11760
  * passed to the `@Component` decorator.
@@ -11703,6 +11790,7 @@ const componentDecoratorToStatic = (config, typeChecker, diagnostics, cmpNode, n
11703
11790
  if (enc.slotAssignment === "manual") newMembers.push(createStaticGetter("slotAssignment", convertValueToLiteral("manual")));
11704
11791
  if (enc.clonable === true) newMembers.push(createStaticGetter("clonable", convertValueToLiteral(true)));
11705
11792
  if (enc.serializable === true) newMembers.push(createStaticGetter("serializable", convertValueToLiteral(true)));
11793
+ if (enc.referenceTarget) newMembers.push(createStaticGetter("referenceTarget", convertValueToLiteral(enc.referenceTarget.trim())));
11706
11794
  } else if (enc.type === "scoped") {
11707
11795
  newMembers.push(createStaticGetter("encapsulation", convertValueToLiteral("scoped")));
11708
11796
  if (enc.patches && enc.patches.length > 0) newMembers.push(createStaticGetter("patches", convertValueToLiteral(enc.patches)));
@@ -11780,6 +11868,12 @@ const validateComponent = (config, diagnostics, typeChecker, componentOptions, c
11780
11868
  augmentDiagnosticWithNode(err, findTagNode("mode", componentDecorator));
11781
11869
  return false;
11782
11870
  }
11871
+ if (enc.referenceTarget !== void 0 && (typeof enc.referenceTarget !== "string" || enc.referenceTarget.trim() === "")) {
11872
+ const err = buildError(diagnostics);
11873
+ err.messageText = `The "referenceTarget" option must be a non-empty string matching the id of an element in the component's shadow root.`;
11874
+ augmentDiagnosticWithNode(err, findTagNode("referenceTarget", componentDecorator));
11875
+ return false;
11876
+ }
11783
11877
  }
11784
11878
  if ((enc.type === "none" || enc.type === "scoped") && enc.patches) {
11785
11879
  const validPatches = [
@@ -11868,6 +11962,110 @@ const findTagNode = (propName, node) => {
11868
11962
  return out;
11869
11963
  };
11870
11964
  //#endregion
11965
+ //#region src/compiler/transformers/decorators-to-static/attach-internals.ts
11966
+ /**
11967
+ * Convert the attach internals decorator to static, saving the name of the
11968
+ * decorated property so an `ElementInternals` object can be bound to it later
11969
+ * on.
11970
+ *
11971
+ * The `@AttachInternals` decorator is used to indicate a field on a class
11972
+ * where the return value of the `HTMLElement.attachInternals` method should be
11973
+ * bound. This then allows component authors to use that interface to make their
11974
+ * Stencil components rich participants in whatever `HTMLFormElement` instances
11975
+ * they find themselves inside of in the future.
11976
+ *
11977
+ * The decorator also accepts an optional `states` option to define initial
11978
+ * custom states that will be set on the `ElementInternals.states` CustomStateSet.
11979
+ * Each state property can have a JSDoc comment that will be extracted for documentation.
11980
+ *
11981
+ * **Note**: this function will mutate the `newMembers` parameter in order to
11982
+ * add new members to the class.
11983
+ *
11984
+ * @param diagnostics for reporting errors and warnings
11985
+ * @param decoratedMembers the decorated members found on the class
11986
+ * @param newMembers an out param for new class members
11987
+ * @param typeChecker a TypeScript typechecker, needed for resolving the prop
11988
+ * declaration name
11989
+ * @param decoratorName the name of the decorator to look for
11990
+ */
11991
+ const attachInternalsDecoratorsToStatic = (diagnostics, decoratedMembers, newMembers, typeChecker, decoratorName) => {
11992
+ const attachInternalsMembers = decoratedMembers.filter(ts$1.isPropertyDeclaration).filter((prop) => {
11993
+ return !!retrieveTsDecorators(prop)?.find(isDecoratorNamed(decoratorName));
11994
+ });
11995
+ if (attachInternalsMembers.length === 0) return;
11996
+ if (attachInternalsMembers.length > 1) {
11997
+ const error = buildError(diagnostics);
11998
+ error.messageText = `Stencil does not support adding more than one AttachInternals() decorator to a component`;
11999
+ return;
12000
+ }
12001
+ const [decoratedProp] = attachInternalsMembers;
12002
+ const { staticName: name } = tsPropDeclName(decoratedProp, typeChecker);
12003
+ const decorator = retrieveTsDecorators(decoratedProp)?.find(isDecoratorNamed(decoratorName));
12004
+ const customStates = parseCustomStatesFromDecorator(decorator, typeChecker);
12005
+ const formAssociated = parseFormAssociatedFromDecorator(decorator);
12006
+ newMembers.push(createStaticGetter("attachInternalsMemberName", convertValueToLiteral(name)));
12007
+ if (customStates.length > 0) newMembers.push(createStaticGetter("attachInternalsCustomStates", convertValueToLiteral(customStates)));
12008
+ if (formAssociated) newMembers.push(createStaticGetter("formAssociated", convertValueToLiteral(true)));
12009
+ };
12010
+ /**
12011
+ * Parse the formAssociated option from the decorator.
12012
+ * Returns true (form-associated) unless explicitly set to false.
12013
+ *
12014
+ * @param decorator the decorator node to parse
12015
+ * @returns whether the component should be form-associated
12016
+ */
12017
+ function parseFormAssociatedFromDecorator(decorator) {
12018
+ if (!decorator || !ts$1.isCallExpression(decorator.expression)) return true;
12019
+ const [firstArg] = decorator.expression.arguments;
12020
+ if (!firstArg || !ts$1.isObjectLiteralExpression(firstArg)) return true;
12021
+ const formAssociatedProp = firstArg.properties.find((prop) => ts$1.isPropertyAssignment(prop) && ts$1.isIdentifier(prop.name) && prop.name.text === "formAssociated");
12022
+ if (!formAssociatedProp) return true;
12023
+ if (formAssociatedProp.initializer.kind === ts$1.SyntaxKind.FalseKeyword) return false;
12024
+ return true;
12025
+ }
12026
+ /**
12027
+ * Parse custom states from the decorator AST, including JSDoc comments.
12028
+ *
12029
+ * Supports JSDoc comments on state properties:
12030
+ * ```ts
12031
+ * @AttachInternals({
12032
+ * states: {
12033
+ * hovered: false,
12034
+ * /&#42;&#42; Whether is currently active &#42;/
12035
+ * active: true
12036
+ * }
12037
+ * })
12038
+ * ```
12039
+ *
12040
+ * @param decorator the decorator node to parse
12041
+ * @param typeChecker a TypeScript typechecker for resolving symbols
12042
+ * @returns array of custom state metadata with docs
12043
+ */
12044
+ function parseCustomStatesFromDecorator(decorator, typeChecker) {
12045
+ if (!decorator || !ts$1.isCallExpression(decorator.expression)) return [];
12046
+ const [firstArg] = decorator.expression.arguments;
12047
+ if (!firstArg || !ts$1.isObjectLiteralExpression(firstArg)) return [];
12048
+ const statesProp = firstArg.properties.find((prop) => ts$1.isPropertyAssignment(prop) && ts$1.isIdentifier(prop.name) && prop.name.text === "states");
12049
+ if (!statesProp || !ts$1.isObjectLiteralExpression(statesProp.initializer)) return [];
12050
+ const customStates = [];
12051
+ for (const prop of statesProp.initializer.properties) {
12052
+ if (!ts$1.isPropertyAssignment(prop)) continue;
12053
+ const stateName = ts$1.isIdentifier(prop.name) ? prop.name.text : ts$1.isStringLiteral(prop.name) ? prop.name.text : null;
12054
+ if (!stateName) continue;
12055
+ let initialValue = false;
12056
+ if (prop.initializer.kind === ts$1.SyntaxKind.TrueKeyword) initialValue = true;
12057
+ else if (prop.initializer.kind === ts$1.SyntaxKind.FalseKeyword) initialValue = false;
12058
+ const symbol = typeChecker.getSymbolAtLocation(prop.name);
12059
+ const docs = symbol ? ts$1.displayPartsToString(symbol.getDocumentationComment(typeChecker)) : "";
12060
+ customStates.push({
12061
+ name: stateName,
12062
+ initialValue,
12063
+ docs
12064
+ });
12065
+ }
12066
+ return customStates;
12067
+ }
12068
+ //#endregion
11871
12069
  //#region src/compiler/transformers/decorators-to-static/decorators-constants.ts
11872
12070
  /**
11873
12071
  * All the decorators supported by Stencil
@@ -12304,8 +12502,8 @@ var ImportAliasMap = class extends Map {
12304
12502
  for (const importDeclaration of importDeclarations) if (importDeclaration.moduleSpecifier.getText().includes("@stencil/core")) {
12305
12503
  const namedBindings = importDeclaration.importClause?.namedBindings;
12306
12504
  if (namedBindings && ts$1.isNamedImports(namedBindings)) for (const element of namedBindings.elements) {
12307
- const importName = element.name.getText();
12308
- const originalImportName = element.propertyName?.getText() ?? importName;
12505
+ const importName = element.name.text;
12506
+ const originalImportName = element.propertyName?.text ?? importName;
12309
12507
  if (STENCIL_DECORATORS.includes(originalImportName)) this.set(originalImportName, importName);
12310
12508
  }
12311
12509
  }
@@ -12315,6 +12513,102 @@ var ImportAliasMap = class extends Map {
12315
12513
  }
12316
12514
  };
12317
12515
  //#endregion
12516
+ //#region src/compiler/transformers/decorators-to-static/json-serialize-prop.ts
12517
+ /**
12518
+ * `@Prop({ serialize: 'json' })` is shorthand for a `@PropSerialize()` / `@AttrDeserialize()` pair
12519
+ * that writes the value to the prop's attribute as JSON on the server, and reads it back in the
12520
+ * browser. These are the generated methods' names (no leading `_`: the runtime metadata drops
12521
+ * those keys), and the alias of the `Build` import they use.
12522
+ */
12523
+ const JSON_SERIALIZE_METHOD = "stencilSerializeJson";
12524
+ const JSON_DESERIALIZE_METHOD = "stencilDeserializeJson";
12525
+ const BUILD_ALIAS = "__stencil_Build";
12526
+ /**
12527
+ * Find the props declared `@Prop({ serialize: 'json' })`, reporting invalid combinations.
12528
+ * @param diagnostics for surfacing errors
12529
+ * @param typeChecker a TypeScript typechecker instance
12530
+ * @param decoratedMembers the class's decorated members
12531
+ * @param propDecoratorName the name `@Prop` is imported as
12532
+ * @param handWritten serializers and deserializers written with the decorators
12533
+ * @returns the names of the props to serialize as JSON
12534
+ */
12535
+ const getJsonSerializedProps = (diagnostics, typeChecker, decoratedMembers, propDecoratorName, handWritten) => decoratedMembers.flatMap((member) => {
12536
+ if (!ts$1.isPropertyDeclaration(member) && !ts$1.isGetAccessor(member)) return [];
12537
+ const decorator = retrieveTsDecorators(member)?.find(isDecoratorNamed(propDecoratorName));
12538
+ if (!decorator) return [];
12539
+ const [options] = getDecoratorParameters(decorator, typeChecker);
12540
+ if (options?.serialize == null) return [];
12541
+ const { staticName: propName } = tsPropDeclName(member, typeChecker);
12542
+ const error = (messageText) => {
12543
+ const err = buildError(diagnostics);
12544
+ err.messageText = messageText;
12545
+ augmentDiagnosticWithNode(err, decorator);
12546
+ };
12547
+ if (options.serialize !== "json") {
12548
+ error(`@Prop({ serialize }) on "${propName}" must be 'json'. For other formats, use @PropSerialize() and @AttrDeserialize().`);
12549
+ return [];
12550
+ }
12551
+ if (options.attribute === null) {
12552
+ error(`@Prop({ serialize: 'json' }) on "${propName}" needs an attribute to write to, but it has "attribute: null".`);
12553
+ return [];
12554
+ }
12555
+ if (handWritten.some((h) => h.propName === propName)) {
12556
+ error(`"${propName}" has both @Prop({ serialize: 'json' }) and its own @PropSerialize() / @AttrDeserialize(). Use one or the other.`);
12557
+ return [];
12558
+ }
12559
+ return [propName];
12560
+ });
12561
+ /**
12562
+ * The methods `@Prop({ serialize: 'json' })` uses, shared by every such prop in a class:
12563
+ *
12564
+ * ```ts
12565
+ * stencilSerializeJson(value) {
12566
+ * return __stencil_Build.isServer ? JSON.stringify(value) : null;
12567
+ * }
12568
+ * stencilDeserializeJson(value, propName) {
12569
+ * try {
12570
+ * return JSON.parse(value);
12571
+ * } catch {
12572
+ * if (__stencil_Build.isDev) console.warn(...);
12573
+ * // leave the prop as it is
12574
+ * return __stencil_Build.isServer ? undefined : this[propName];
12575
+ * }
12576
+ * }
12577
+ * ```
12578
+ *
12579
+ * The serializer only writes on the server, like a hand-written one should: in the browser the
12580
+ * attribute's job is done, and rewriting it on every change would be wasted work.
12581
+ * @returns the two method declarations
12582
+ */
12583
+ const createJsonSerializerMethods = () => {
12584
+ const f = ts$1.factory;
12585
+ const build = (flag) => f.createPropertyAccessExpression(f.createIdentifier(BUILD_ALIAS), flag);
12586
+ const jsonCall = (method, arg) => f.createCallExpression(f.createPropertyAccessExpression(f.createIdentifier("JSON"), method), void 0, [arg]);
12587
+ const param = (name) => f.createParameterDeclaration(void 0, void 0, name);
12588
+ const method = (name, params, body) => f.createMethodDeclaration(void 0, void 0, name, void 0, void 0, params.map(param), void 0, f.createBlock(body, true));
12589
+ const serialize = method(JSON_SERIALIZE_METHOD, ["value"], [f.createReturnStatement(f.createConditionalExpression(build("isServer"), void 0, jsonCall("stringify", f.createIdentifier("value")), void 0, f.createNull()))]);
12590
+ const warn = f.createIfStatement(build("isDev"), f.createExpressionStatement(f.createCallExpression(f.createPropertyAccessExpression(f.createIdentifier("console"), "warn"), void 0, [f.createTemplateExpression(f.createTemplateHead("The \""), [f.createTemplateSpan(f.createIdentifier("propName"), f.createTemplateMiddle(`" attribute isn't valid JSON, so the prop was left as it is: `)), f.createTemplateSpan(f.createIdentifier("value"), f.createTemplateTail(""))])])));
12591
+ return [serialize, method(JSON_DESERIALIZE_METHOD, ["value", "propName"], [f.createTryStatement(f.createBlock([f.createReturnStatement(jsonCall("parse", f.createIdentifier("value")))], true), f.createCatchClause(void 0, f.createBlock([warn, f.createReturnStatement(f.createConditionalExpression(build("isServer"), void 0, f.createIdentifier("undefined"), void 0, f.createElementAccessExpression(f.createThis(), f.createIdentifier("propName"))))], true)), void 0)])];
12592
+ };
12593
+ /**
12594
+ * Import `Build` (as {@link BUILD_ALIAS}) from `@stencil/core`, for the generated methods. Added
12595
+ * to an existing `@stencil/core` import, which a component's source always has.
12596
+ * @param sourceFile the source file
12597
+ * @returns the source file with the import
12598
+ */
12599
+ const addBuildImport = (sourceFile) => {
12600
+ const f = ts$1.factory;
12601
+ const specifier = f.createImportSpecifier(false, f.createIdentifier("Build"), f.createIdentifier(BUILD_ALIAS));
12602
+ let added = false;
12603
+ const statements = sourceFile.statements.map((s) => {
12604
+ if (added || !ts$1.isImportDeclaration(s) || !ts$1.isStringLiteral(s.moduleSpecifier) || s.moduleSpecifier.text !== "@stencil/core" || !s.importClause?.namedBindings || !ts$1.isNamedImports(s.importClause.namedBindings) || s.importClause.isTypeOnly) return s;
12605
+ added = true;
12606
+ return f.updateImportDeclaration(s, s.modifiers, f.updateImportClause(s.importClause, false, s.importClause.name, f.updateNamedImports(s.importClause.namedBindings, [...s.importClause.namedBindings.elements, specifier])), s.moduleSpecifier, s.attributes);
12607
+ });
12608
+ if (!added) statements.unshift(f.createImportDeclaration(void 0, f.createImportClause(false, void 0, f.createNamedImports([specifier])), f.createStringLiteral(STENCIL_CORE_ID)));
12609
+ return f.updateSourceFile(sourceFile, statements);
12610
+ };
12611
+ //#endregion
12318
12612
  //#region src/compiler/transformers/decorators-to-static/listen-decorator.ts
12319
12613
  const listenDecoratorsToStatic = (diagnostics, typeChecker, decoratedMembers, newMembers, decoratorName) => {
12320
12614
  const listeners = decoratedMembers.filter(ts$1.isMethodDeclaration).map((method) => parseListenDecorators(diagnostics, typeChecker, method, decoratorName));
@@ -12679,7 +12973,8 @@ const parseMethodDecorator = (config, diagnostics, tsSourceFile, typeChecker, pr
12679
12973
  const returnTypeNode = typeChecker.typeToTypeNode(returnType, method, ts$1.NodeBuilderFlags.NoTruncation | ts$1.NodeBuilderFlags.NoTypeReduction);
12680
12974
  let returnString = typeToString(typeChecker, returnType);
12681
12975
  let signatureString = typeChecker.signatureToString(signature, method, flags, ts$1.SignatureKind.Call);
12682
- if (!config._isTesting) {
12976
+ const isAsync = !!method.modifiers?.some((m) => m.kind === ts$1.SyntaxKind.AsyncKeyword);
12977
+ if (!config._isTesting && !isAsync) {
12683
12978
  if (returnString === "void") {
12684
12979
  const warn = buildWarn(diagnostics);
12685
12980
  warn.header = "@Method requires async";
@@ -12727,7 +13022,7 @@ const isTypePromise = (typeStr) => {
12727
13022
  };
12728
13023
  const validateMethods = (diagnostics, members) => {
12729
13024
  members.filter(ts$1.isMethodDeclaration).map((method) => {
12730
- if (method.name.getText() === "componentDidUnload") {
13025
+ if (ts$1.isIdentifier(method.name) && method.name.text === "componentDidUnload") {
12731
13026
  const err = buildError(diagnostics);
12732
13027
  err.header = `Replace "componentDidUnload()" with "disconnectedCallback()"`;
12733
13028
  err.messageText = `The "componentDidUnload()" method was removed in Stencil 2. Please use the "disconnectedCallback()" method instead.`;
@@ -13092,7 +13387,7 @@ const getPropertyNameText = (name) => {
13092
13387
  };
13093
13388
  //#endregion
13094
13389
  //#region src/compiler/transformers/decorators-to-static/serialize-decorators.ts
13095
- const serializeDecoratorsToStatic = (typeChecker, decoratedProps, newMembers, decoratorName, translateType, propDecoratorName) => {
13390
+ const serializeDecoratorsToStatic = (typeChecker, decoratedProps, newMembers, decoratorName, translateType, propDecoratorName, generated = []) => {
13096
13391
  const props = decoratedProps.filter((prop) => ts$1.isPropertyDeclaration(prop) || ts$1.isGetAccessor(prop)).flatMap((prop) => {
13097
13392
  if (retrieveTsDecorators(prop)?.find(isDecoratorNamed(propDecoratorName))) {
13098
13393
  const { staticName } = tsPropDeclName(prop, typeChecker);
@@ -13100,7 +13395,7 @@ const serializeDecoratorsToStatic = (typeChecker, decoratedProps, newMembers, de
13100
13395
  }
13101
13396
  return [];
13102
13397
  });
13103
- const serializers = decoratedProps.filter(ts$1.isMethodDeclaration).flatMap((method) => parseSerializeDecorator(typeChecker, method, decoratorName, props));
13398
+ const serializers = [...decoratedProps.filter(ts$1.isMethodDeclaration).flatMap((method) => parseSerializeDecorator(typeChecker, method, decoratorName, props)), ...generated];
13104
13399
  if (serializers.length > 0) {
13105
13400
  if (translateType === "PropSerialize") newMembers.push(createStaticGetter("serializers", convertValueToLiteral(serializers)));
13106
13401
  else newMembers.push(createStaticGetter("deserializers", convertValueToLiteral(serializers)));
@@ -13195,27 +13490,32 @@ const parseWatchDecorator = (typeChecker, method, decoratorName) => {
13195
13490
  * @param diagnostics for surfacing errors and warnings
13196
13491
  * @param typeChecker a TypeScript typechecker instance
13197
13492
  * @param program a {@link ts.Program} object
13493
+ * @param includeClassExpressions also convert `ts.ClassExpression` nodes (e.g. a mixin factory's
13494
+ * `(Base) => class extends Base {}`), not just named `ts.ClassDeclaration`s
13198
13495
  * @returns a TypeScript transformer factory which can be passed to
13199
13496
  * TypeScript to transform source code during the compilation process
13200
13497
  */
13201
- const convertDecoratorsToStatic = (config, diagnostics, typeChecker, program) => {
13498
+ /** Source files with a `@Prop({ serialize: 'json' })`, which need a `Build` import. */
13499
+ const filesWithJsonProps = /* @__PURE__ */ new WeakSet();
13500
+ const convertDecoratorsToStatic = (config, diagnostics, typeChecker, program, includeClassExpressions = false) => {
13202
13501
  return (transformCtx) => {
13203
13502
  let sourceFile;
13204
13503
  const visit = (node) => {
13205
- if (ts$1.isClassDeclaration(node)) return visitClassDeclaration(config, diagnostics, typeChecker, program, node, sourceFile);
13504
+ if (ts$1.isClassDeclaration(node) || includeClassExpressions && ts$1.isClassExpression(node)) return visitClassDeclaration(config, diagnostics, typeChecker, program, node, sourceFile);
13206
13505
  return ts$1.visitEachChild(node, visit, transformCtx);
13207
13506
  };
13208
13507
  return (tsSourceFile) => {
13209
13508
  sourceFile = tsSourceFile;
13210
- return ts$1.visitEachChild(tsSourceFile, visit, transformCtx);
13509
+ const updated = ts$1.visitEachChild(tsSourceFile, visit, transformCtx);
13510
+ return filesWithJsonProps.has(tsSourceFile) ? addBuildImport(updated) : updated;
13211
13511
  };
13212
13512
  };
13213
13513
  };
13214
13514
  /**
13215
- * Visit {@link ts.ClassDeclaration} nodes as part of the tree-traversal
13515
+ * Visit {@link ts.ClassDeclaration}/{@link ts.ClassExpression} nodes as part of the tree-traversal
13216
13516
  * required for {@link convertDecoratorsToStatic} to work.
13217
13517
  *
13218
- * If a given class declaration node is not decorated with `@Component` this
13518
+ * If a given class node is not decorated with `@Component` this
13219
13519
  * function will simply return it as-is. If it _is_ decorated, then it will
13220
13520
  *
13221
13521
  * 1. Convert the arguments to the `@Component` decorator to static values.
@@ -13224,7 +13524,7 @@ const convertDecoratorsToStatic = (config, diagnostics, typeChecker, program) =>
13224
13524
  * to static values.
13225
13525
  * 3. Validate that the various options selected by the component author are
13226
13526
  * valid, both individually and in combination.
13227
- * 4. Return an updated class declaration node which is ready to be used in
13527
+ * 4. Return an updated class node which is ready to be used in
13228
13528
  * the rest of the Stencil compilation pipeline (e.g. in output target
13229
13529
  * generation).
13230
13530
  *
@@ -13243,10 +13543,22 @@ const visitClassDeclaration = (config, diagnostics, typeChecker, program, classN
13243
13543
  const decoratedMembers = classMembers.filter((member) => (retrieveTsDecorators(member)?.length ?? 0) > 0);
13244
13544
  if (!decoratedMembers.length && !componentDecorator) return classNode;
13245
13545
  const filteredMethodsAndFields = removeStencilMethodDecorators(Array.from(classMembers), diagnostics, importAliasMap);
13246
- if (componentDecorator) componentDecoratorToStatic(config, typeChecker, diagnostics, classNode, filteredMethodsAndFields, componentDecorator);
13546
+ if (componentDecorator && ts$1.isClassDeclaration(classNode)) componentDecoratorToStatic(config, typeChecker, diagnostics, classNode, filteredMethodsAndFields, componentDecorator);
13247
13547
  if (decoratedMembers.length > 0) {
13248
- const serializers = serializeDecoratorsToStatic(typeChecker, decoratedMembers, filteredMethodsAndFields, importAliasMap.get("PropSerialize"), "PropSerialize", importAliasMap.get("Prop"));
13249
- const deserializers = serializeDecoratorsToStatic(typeChecker, decoratedMembers, filteredMethodsAndFields, importAliasMap.get("AttrDeserialize"), "AttrDeserialize", importAliasMap.get("Prop"));
13548
+ const handWritten = serializeDecoratorsToStatic(typeChecker, decoratedMembers, [], importAliasMap.get("PropSerialize"), "PropSerialize", importAliasMap.get("Prop")).concat(serializeDecoratorsToStatic(typeChecker, decoratedMembers, [], importAliasMap.get("AttrDeserialize"), "AttrDeserialize", importAliasMap.get("Prop")));
13549
+ const jsonProps = getJsonSerializedProps(diagnostics, typeChecker, decoratedMembers, importAliasMap.get("Prop"), handWritten);
13550
+ if (jsonProps.length > 0) {
13551
+ filteredMethodsAndFields.push(...createJsonSerializerMethods());
13552
+ filesWithJsonProps.add(sourceFile);
13553
+ }
13554
+ const serializers = serializeDecoratorsToStatic(typeChecker, decoratedMembers, filteredMethodsAndFields, importAliasMap.get("PropSerialize"), "PropSerialize", importAliasMap.get("Prop"), jsonProps.map((propName) => ({
13555
+ propName,
13556
+ methodName: JSON_SERIALIZE_METHOD
13557
+ })));
13558
+ const deserializers = serializeDecoratorsToStatic(typeChecker, decoratedMembers, filteredMethodsAndFields, importAliasMap.get("AttrDeserialize"), "AttrDeserialize", importAliasMap.get("Prop"), jsonProps.map((propName) => ({
13559
+ propName,
13560
+ methodName: JSON_DESERIALIZE_METHOD
13561
+ })));
13250
13562
  propDecoratorsToStatic(config, diagnostics, decoratedMembers, typeChecker, program, filteredMethodsAndFields, importAliasMap.get("Prop"), serializers, deserializers);
13251
13563
  stateDecoratorsToStatic(decoratedMembers, filteredMethodsAndFields, typeChecker, importAliasMap.get("State"));
13252
13564
  eventDecoratorsToStatic(config, diagnostics, decoratedMembers, typeChecker, program, filteredMethodsAndFields, importAliasMap.get("Event"));
@@ -13258,8 +13570,9 @@ const visitClassDeclaration = (config, diagnostics, typeChecker, program, classN
13258
13570
  }
13259
13571
  validateMethods(diagnostics, classMembers);
13260
13572
  const currentDecorators = retrieveTsDecorators(classNode);
13261
- const updatedClassFields = updateConstructor(classNode, filteredMethodsAndFields, []);
13262
- return ts$1.factory.updateClassDeclaration(classNode, [...filterDecorators(currentDecorators, CLASS_DECORATORS_TO_REMOVE.map((decorator) => importAliasMap.get(decorator))) ?? [], ...retrieveTsModifiers(classNode) ?? []], classNode.name, classNode.typeParameters, classNode.heritageClauses, updatedClassFields);
13573
+ const updatedClassFields = updateConstructor(classNode, filteredMethodsAndFields, [], void 0, "forward");
13574
+ const updatedModifiers = [...filterDecorators(currentDecorators, CLASS_DECORATORS_TO_REMOVE.map((decorator) => importAliasMap.get(decorator))) ?? [], ...retrieveTsModifiers(classNode) ?? []];
13575
+ return ts$1.isClassDeclaration(classNode) ? ts$1.factory.updateClassDeclaration(classNode, updatedModifiers, classNode.name, classNode.typeParameters, classNode.heritageClauses, updatedClassFields) : ts$1.factory.updateClassExpression(classNode, updatedModifiers, classNode.name, classNode.typeParameters, classNode.heritageClauses, updatedClassFields);
13263
13576
  };
13264
13577
  /**
13265
13578
  * Take a list of `ClassElement` AST nodes and remove any decorators from
@@ -13525,12 +13838,18 @@ const gatherVdomMeta = (m, args, typeChecker) => {
13525
13838
  };
13526
13839
  //#endregion
13527
13840
  //#region src/compiler/transformers/static-to-meta/call-expression.ts
13528
- const parseCallExpression = (m, node, typeChecker) => {
13841
+ /**
13842
+ * @param m the module or component to record vdom metadata on
13843
+ * @param node the call expression to parse
13844
+ * @param typeChecker used to resolve functional components / JSX-returning calls to their source
13845
+ * @param moduleFile the module to record those dependencies on; defaults to `m` when it's a module
13846
+ */
13847
+ const parseCallExpression = (m, node, typeChecker, moduleFile = "functionalComponentDeps" in m ? m : void 0) => {
13529
13848
  if (node.arguments != null && node.arguments.length > 0) {
13530
- if (ts$1.isIdentifier(node.expression)) visitCallExpressionArgs(m, node.expression, node.arguments, typeChecker);
13849
+ if (ts$1.isIdentifier(node.expression)) visitCallExpressionArgs(m, node.expression, node.arguments, typeChecker, moduleFile);
13531
13850
  else if (ts$1.isPropertyAccessExpression(node.expression)) {
13532
13851
  const n = node.expression.name;
13533
- if (ts$1.isIdentifier(n) && n) visitCallExpressionArgs(m, n, node.arguments, typeChecker);
13852
+ if (ts$1.isIdentifier(n) && n) visitCallExpressionArgs(m, n, node.arguments, typeChecker, moduleFile);
13534
13853
  }
13535
13854
  } else if (ts$1.isPropertyAccessExpression(node.expression)) {
13536
13855
  if (ts$1.isIdentifier(node.expression.name)) {
@@ -13540,24 +13859,20 @@ const parseCallExpression = (m, node, typeChecker) => {
13540
13859
  if (!declarations || declarations.length === 0) return;
13541
13860
  const sourceFile = declarations[0].getSourceFile();
13542
13861
  if (!sourceFile) return;
13543
- const sourceFilePath = normalizePath(sourceFile.fileName);
13544
- const moduleFile = m;
13545
- if (moduleFile.functionalComponentDeps) {
13546
- if (!moduleFile.functionalComponentDeps.includes(sourceFilePath)) moduleFile.functionalComponentDeps.push(sourceFilePath);
13547
- }
13862
+ addFunctionalComponentDep(moduleFile, sourceFile);
13548
13863
  }
13549
13864
  }
13550
13865
  };
13551
- const visitCallExpressionArgs = (m, callExpressionName, args, typeChecker) => {
13866
+ const visitCallExpressionArgs = (m, callExpressionName, args, typeChecker, moduleFile) => {
13552
13867
  const fnName = callExpressionName.escapedText;
13553
13868
  if (fnName === "h" || fnName === "__stencil_h" || fnName === "createElement") {
13554
- visitCallExpressionArg(m, args[0], typeChecker);
13869
+ visitCallExpressionArg(m, args[0], typeChecker, moduleFile);
13555
13870
  if (fnName === "h" || fnName === "__stencil_h") gatherVdomMeta(m, args, typeChecker);
13556
13871
  } else if (fnName === "jsx" || fnName === "jsxs" || fnName === "_jsx" || fnName === "_jsxs") {
13557
- visitCallExpressionArg(m, args[0], typeChecker);
13872
+ visitCallExpressionArg(m, args[0], typeChecker, moduleFile);
13558
13873
  gatherVdomMeta(m, args, typeChecker);
13559
13874
  if (args.length > 2 && args[2]) m.hasVdomKey = true;
13560
- } else if (args.length > 1 && fnName === "createElementNS") visitCallExpressionArg(m, args[1], typeChecker);
13875
+ } else if (args.length > 1 && fnName === "createElementNS") visitCallExpressionArg(m, args[1], typeChecker, moduleFile);
13561
13876
  else if (fnName === "require" && args.length > 0 && m.originalImports) {
13562
13877
  const arg = args[0];
13563
13878
  if (ts$1.isStringLiteral(arg)) {
@@ -13565,7 +13880,7 @@ const visitCallExpressionArgs = (m, callExpressionName, args, typeChecker) => {
13565
13880
  }
13566
13881
  }
13567
13882
  };
13568
- const visitCallExpressionArg = (m, arg, typeChecker) => {
13883
+ const visitCallExpressionArg = (m, arg, typeChecker, moduleFile) => {
13569
13884
  if (ts$1.isStringLiteral(arg)) {
13570
13885
  let tag = arg.text;
13571
13886
  if (typeof tag === "string") {
@@ -13573,31 +13888,31 @@ const visitCallExpressionArg = (m, arg, typeChecker) => {
13573
13888
  m.htmlTagNames.push(tag);
13574
13889
  if (tag.includes("-")) m.potentialCmpRefs.push(tag);
13575
13890
  }
13576
- } else if (typeChecker && ts$1.isIdentifier(arg)) resolveFunctionalComponentDep(m, arg, typeChecker);
13891
+ } else if (typeChecker && ts$1.isIdentifier(arg)) resolveFunctionalComponentDep(moduleFile, arg, typeChecker);
13577
13892
  };
13578
13893
  /**
13579
13894
  * Resolves a functional component identifier to its source file and tracks it
13580
13895
  * as a dependency so that build-conditionals can be properly propagated.
13896
+ * Follows import / re-export aliases through to the declaring file.
13581
13897
  *
13582
- * @param m the module or component metadata to track the dependency on
13898
+ * @param moduleFile the module to track the dependency on
13583
13899
  * @param identifier the identifier node representing the functional component
13584
13900
  * @param typeChecker the TypeScript type checker for symbol resolution
13585
13901
  */
13586
- const resolveFunctionalComponentDep = (m, identifier, typeChecker) => {
13902
+ const resolveFunctionalComponentDep = (moduleFile, identifier, typeChecker) => {
13903
+ if (!moduleFile) return;
13587
13904
  try {
13588
13905
  const symbol = typeChecker.getSymbolAtLocation(identifier);
13589
13906
  if (!symbol) return;
13590
- const declarations = (typeChecker.getAliasedSymbol(symbol) || symbol).declarations;
13591
- if (!declarations || declarations.length === 0) return;
13592
- const sourceFile = declarations[0].getSourceFile();
13593
- if (!sourceFile) return;
13594
- const sourceFilePath = normalizePath(sourceFile.fileName);
13595
- const moduleFile = m;
13596
- if (moduleFile.functionalComponentDeps) {
13597
- if (!moduleFile.functionalComponentDeps.includes(sourceFilePath)) moduleFile.functionalComponentDeps.push(sourceFilePath);
13598
- }
13907
+ const sourceFile = (symbol.flags & ts$1.SymbolFlags.Alias ? typeChecker.getAliasedSymbol(symbol) : symbol).declarations?.[0]?.getSourceFile();
13908
+ if (sourceFile) addFunctionalComponentDep(moduleFile, sourceFile);
13599
13909
  } catch {}
13600
13910
  };
13911
+ const addFunctionalComponentDep = (moduleFile, sourceFile) => {
13912
+ const deps = moduleFile?.functionalComponentDeps;
13913
+ const sourceFilePath = normalizePath(sourceFile.fileName);
13914
+ if (deps && !deps.includes(sourceFilePath)) deps.push(sourceFilePath);
13915
+ };
13601
13916
  //#endregion
13602
13917
  //#region src/compiler/transformers/component-build-conditionals.ts
13603
13918
  const setComponentBuildConditionals = (cmpMeta) => {
@@ -13727,7 +14042,7 @@ const tsResolveModuleName = (config, compilerCtx, moduleName, containingFile) =>
13727
14042
  const tsGetSourceFile = (config, module) => {
13728
14043
  if (!module || !module.resolvedModule) return null;
13729
14044
  const compilerOptions = { ...config.tsCompilerOptions };
13730
- const host = ts$1.createCompilerHost(compilerOptions);
14045
+ const host = ts$1.createCompilerHost(compilerOptions, true);
13731
14046
  return ts$1.createProgram([module.resolvedModule.resolvedFileName], compilerOptions, host).getSourceFile(module.resolvedModule.resolvedFileName);
13732
14047
  };
13733
14048
  const tsResolveModuleNamePackageJsonPath = (config, compilerCtx, moduleName, containingFile) => {
@@ -13870,11 +14185,11 @@ const parseStaticWatchers = (staticMembers) => {
13870
14185
  //#endregion
13871
14186
  //#region src/compiler/transformers/static-to-meta/class-extension/shared.ts
13872
14187
  /**
13873
- * Warns when an `extends`/`Mixin(...)` target resolved to *something* but no class declaration
13874
- * could be found inside it - e.g. a mixin factory whose class isn't a named declaration
13875
- * (`(Base) => class extends Base {}` rather than `(Base) => { class Foo extends Base {} return
13876
- * Foo; }`). Without this, the target is silently dropped: any `@Prop`/`@State` etc. it declares
13877
- * just never appears on the extending component, with no diagnostic explaining why.
14188
+ * Warns when an `extends`/`Mixin(...)` target resolved to *something* but no class literal
14189
+ * could be found inside it - e.g. a mixin factory that returns an existing class by reference
14190
+ * (`(Base) => SomeExistingClass`) rather than a class literal. Without this, the target is
14191
+ * silently dropped: any `@Prop`/`@State` etc. it declares just never appears on the extending
14192
+ * component, with no diagnostic explaining why.
13878
14193
  * @param buildCtx used to surface the warning - omit to warn silently (e.g. from tests)
13879
14194
  * @param targetName the identifier the target was reached through
13880
14195
  * @param anchor the node to attach the warning to
@@ -13882,27 +14197,32 @@ const parseStaticWatchers = (staticMembers) => {
13882
14197
  function warnMixinFactoryClassNotFound(buildCtx, targetName, anchor) {
13883
14198
  if (!buildCtx) return;
13884
14199
  const err = buildWarn(buildCtx.diagnostics);
13885
- err.messageText = `Found "${targetName}", but couldn't find a class declaration inside it. If it's meant to be a mixin factory, make sure it declares and returns a named class, e.g. \`(Base) => { class ${targetName}Class extends Base {} return ${targetName}Class; }\` - a factory that returns a class expression directly (\`(Base) => class extends Base {}\`) isn't recognized, and any \`@Prop\`/\`@State\`/etc. it declares won't be applied.`;
14200
+ err.messageText = `Found "${targetName}", but couldn't find a class inside it. If it's meant to be a mixin factory, make sure it returns a class literal directly, e.g. \`(Base) => class extends Base {}\` or \`(Base) => { class ${targetName}Class extends Base {} return ${targetName}Class; }\` - returning an existing class by reference (\`(Base) => SomeExistingClass\`) isn't recognized, and any \`@Prop\`/\`@State\`/etc. it declares won't be applied.`;
13886
14201
  if (!buildCtx.config._isTesting) augmentDiagnosticWithNode(err, anchor);
13887
14202
  }
13888
14203
  /**
13889
- * Walks the AST looking for a class declaration, optionally by name - descends
13890
- * into a mixin factory's wrapping function (arrow function or `function`
13891
- * declaration) body too, since a mixin factory's class is always nested one
13892
- * level inside it (e.g. `const Foo = (Base) => class extends Base {}`).
14204
+ * Walks the AST looking for a class declaration or class expression, optionally by name -
14205
+ * descends into a mixin factory's wrapping function (arrow function or `function` declaration)
14206
+ * body too, since a mixin factory's class is always nested one level inside it. Recognizes all of:
14207
+ * `const Foo = (Base) => class extends Base {}` (concise arrow body), `const Foo = (Base) => {
14208
+ * return class extends Base {}; }` (block body, `return` of a class expression), and `const Foo =
14209
+ * (Base) => { class FooClass extends Base {} return FooClass; }` (block body, named declaration).
13893
14210
  * @param node the node to search from
13894
- * @param name if given, only matches a class declaration with this name
13895
- * @returns the found class declaration, or `undefined`
14211
+ * @param name if given, only matches a class with this name
14212
+ * @returns the found class, or `undefined`
13896
14213
  */
13897
14214
  function findClassWalk(node, name) {
13898
14215
  if (!node) return void 0;
13899
- if (ts$1.isClassDeclaration(node)) {
14216
+ if (ts$1.isClassDeclaration(node) || ts$1.isClassExpression(node)) {
13900
14217
  if (!name || node.name?.text === name) return node;
13901
14218
  } else if (ts$1.isVariableDeclaration(node) && (!name || name === node.name?.text) && node.initializer && ts$1.isArrowFunction(node.initializer)) {
14219
+ const body = node.initializer.body;
14220
+ if (ts$1.isClassExpression(body)) return body;
13902
14221
  let found;
13903
- ts$1.forEachChild(node.initializer.body, (child) => {
14222
+ ts$1.forEachChild(body, (child) => {
13904
14223
  if (found) return;
13905
14224
  if (ts$1.isClassDeclaration(child)) found = child;
14225
+ else if (ts$1.isReturnStatement(child) && child.expression && ts$1.isClassExpression(child.expression)) found = child.expression;
13906
14226
  });
13907
14227
  return found;
13908
14228
  }
@@ -13915,6 +14235,22 @@ function findClassWalk(node, name) {
13915
14235
  return found;
13916
14236
  }
13917
14237
  /**
14238
+ * The declared name of a mixin-factory statement (`function Foo() {}`, or `const Foo = ...`) -
14239
+ * survives the decorator-to-static-getter transform even when the factory's inner class doesn't
14240
+ * have a name of its own, so it can anchor a post-transform re-lookup via `findClassWalk`.
14241
+ * @param node the factory statement (or its variable declaration) to read a name from
14242
+ * @returns the declared name, or `undefined` if it can't be determined
14243
+ */
14244
+ function factoryDeclaredName(node) {
14245
+ if (!node) return void 0;
14246
+ if (ts$1.isFunctionDeclaration(node)) return node.name?.text;
14247
+ if (ts$1.isVariableDeclaration(node)) return ts$1.isIdentifier(node.name) ? node.name.text : void 0;
14248
+ if (ts$1.isVariableStatement(node)) {
14249
+ const decl = node.declarationList.declarations[0];
14250
+ return decl && ts$1.isIdentifier(decl.name) ? decl.name.text : void 0;
14251
+ }
14252
+ }
14253
+ /**
13918
14254
  * Matches a top-level class/function/variable declaration by name - the three
13919
14255
  * shapes a mixin or base-class export can take (a plain class, a mixin
13920
14256
  * factory function declaration, or a mixin factory assigned to a `const`).
@@ -13932,22 +14268,173 @@ function matchesNamedDeclaration(name) {
13932
14268
  };
13933
14269
  }
13934
14270
  /**
13935
- * Finds a re-export of `className` in `sourceFile` - `export { X } from './y'` or
13936
- * `export { X as Y } from './y'` - as used by barrel entry points (e.g. `@stencil/core`'s own
13937
- * public `index.d.mts`, which re-exports its runtime API from `./declarations/stencil-public-runtime`
13938
- * rather than declaring it directly).
14271
+ * Finds a re-export of `className` in `sourceFile`: `export { X } from './y'`, or the
14272
+ * bundler-split shape `import { X as name } from './y'; export { name };` (no `from` clause).
13939
14273
  * @param sourceFile the (barrel) source file to scan
13940
14274
  * @param className the exported name to look for
13941
- * @returns the module specifier and the name to look for in that module (the local name, before
13942
- * any `as` aliasing), or `undefined` if no matching re-export is found
14275
+ * @returns the module specifier and name to look for there (before any `as` aliasing), or
14276
+ * `undefined` if not found
13943
14277
  */
13944
14278
  function findReExport(sourceFile, className) {
13945
14279
  for (const stmt of sourceFile.statements) {
13946
- if (!ts$1.isExportDeclaration(stmt) || !stmt.moduleSpecifier || !ts$1.isStringLiteral(stmt.moduleSpecifier) || !stmt.exportClause || !ts$1.isNamedExports(stmt.exportClause)) continue;
13947
- for (const element of stmt.exportClause.elements) if (element.name.text === className) return {
14280
+ if (!ts$1.isExportDeclaration(stmt) || !stmt.exportClause || !ts$1.isNamedExports(stmt.exportClause)) continue;
14281
+ const element = stmt.exportClause.elements.find((el) => el.name.text === className);
14282
+ if (!element) continue;
14283
+ if (stmt.moduleSpecifier && ts$1.isStringLiteral(stmt.moduleSpecifier)) return {
13948
14284
  moduleSpecifier: stmt.moduleSpecifier.text,
13949
14285
  localName: element.propertyName?.text ?? element.name.text
13950
14286
  };
14287
+ const importOrigin = findImportOrigin(sourceFile, element.propertyName?.text ?? element.name.text);
14288
+ if (importOrigin) return importOrigin;
14289
+ }
14290
+ }
14291
+ /**
14292
+ * @param sourceFile the (barrel) source file to scan
14293
+ * @returns the module specifiers of its `export * from './x'` statements, in order
14294
+ */
14295
+ function findStarReExportSpecifiers(sourceFile) {
14296
+ return sourceFile.statements.flatMap((stmt) => ts$1.isExportDeclaration(stmt) && !stmt.exportClause && !stmt.isTypeOnly && stmt.moduleSpecifier && ts$1.isStringLiteral(stmt.moduleSpecifier) ? [stmt.moduleSpecifier.text] : []);
14297
+ }
14298
+ /**
14299
+ * Finds `name`'s import in `sourceFile` and returns its module and origin name (before any `as`
14300
+ * aliasing; `'default'` for a default import).
14301
+ * @param sourceFile the source file to scan for a matching import
14302
+ * @param name the local (post-aliasing) name an import bound
14303
+ * @returns the import's module specifier and origin name, or `undefined` if `name` isn't imported
14304
+ */
14305
+ function findImportOrigin(sourceFile, name) {
14306
+ for (const stmt of sourceFile.statements) {
14307
+ if (!ts$1.isImportDeclaration(stmt) || !stmt.importClause || !ts$1.isStringLiteral(stmt.moduleSpecifier)) continue;
14308
+ const moduleSpecifier = stmt.moduleSpecifier.text;
14309
+ if (stmt.importClause.name?.text === name) return {
14310
+ moduleSpecifier,
14311
+ localName: "default"
14312
+ };
14313
+ const bindings = stmt.importClause.namedBindings;
14314
+ if (!bindings || !ts$1.isNamedImports(bindings)) continue;
14315
+ const element = bindings.elements.find((el) => el.name.text === name);
14316
+ if (element) return {
14317
+ moduleSpecifier,
14318
+ localName: element.propertyName?.text ?? element.name.text
14319
+ };
14320
+ }
14321
+ }
14322
+ /**
14323
+ * Finds `name` as a top-level declaration in `sf` (see `matchesNamedDeclaration`), following a
14324
+ * same-file export alias if `name` is only ever the public side of a local rename
14325
+ * (`export { RealName as name }`, no `from` clause).
14326
+ * @param sf the source file to search
14327
+ * @param name the declaration name to look for, which may only exist as an export alias
14328
+ * @returns the matched statement, or `undefined`
14329
+ */
14330
+ function findStatementByName(sf, name) {
14331
+ const direct = sf.statements.find(matchesNamedDeclaration(name));
14332
+ if (direct) return direct;
14333
+ for (const stmt of sf.statements) {
14334
+ if (!ts$1.isExportDeclaration(stmt) || stmt.moduleSpecifier || !stmt.exportClause || !ts$1.isNamedExports(stmt.exportClause)) continue;
14335
+ const aliasedName = stmt.exportClause.elements.find((el) => el.name.text === name)?.propertyName?.text;
14336
+ if (aliasedName && aliasedName !== name) return sf.statements.find(matchesNamedDeclaration(aliasedName));
14337
+ }
14338
+ }
14339
+ /**
14340
+ * Picks the runtime target out of a `package.json` `exports` condition entry - prefers `import`
14341
+ * over `require`/`node`/`default`, recursing into nested condition objects.
14342
+ * @param entry an `exports` map value: a path string, or nested conditions
14343
+ * @returns the resolved relative path, or `undefined` if no usable condition was found
14344
+ */
14345
+ function pickJsCondition(entry) {
14346
+ if (typeof entry === "string") return entry;
14347
+ if (typeof entry !== "object" || entry === null) return;
14348
+ const conditions = entry;
14349
+ for (const key of [
14350
+ "import",
14351
+ "require",
14352
+ "node",
14353
+ "default"
14354
+ ]) if (key in conditions) {
14355
+ const picked = pickJsCondition(conditions[key]);
14356
+ if (picked) return picked;
14357
+ }
14358
+ }
14359
+ /**
14360
+ * Reads and parses `filePath` as JS, with parent nodes set - unlike `tsGetSourceFile`, which
14361
+ * never triggers binding, so `.parent` stays unset and `node.getSourceFile()` returns `undefined`.
14362
+ * @param config the current Stencil validated config
14363
+ * @param filePath the absolute path of the JS file to read and parse
14364
+ * @returns the parsed source file, or `undefined` if it couldn't be read
14365
+ */
14366
+ function readJsSourceFile(config, filePath) {
14367
+ try {
14368
+ const text = config.sys.readFileSync(filePath);
14369
+ if (typeof text !== "string") return;
14370
+ return ts$1.createSourceFile(filePath, text, ts$1.ScriptTarget.ESNext, true, ts$1.ScriptKind.JS);
14371
+ } catch {
14372
+ return;
14373
+ }
14374
+ }
14375
+ /**
14376
+ * Resolves the runtime JS entry for a bare (non-relative) module specifier by reading its
14377
+ * package's own `package.json` `exports` map, instead of `tsResolveModuleName` - which always
14378
+ * resolves to the package's `types` entry, an ambient signature with no body a mixin factory's
14379
+ * class can never be found inside.
14380
+ * @param config the current Stencil validated config
14381
+ * @param compilerCtx the current compiler context
14382
+ * @param moduleSpecifier the bare package specifier to resolve
14383
+ * @param containingFile the file the specifier was imported from
14384
+ * @returns the resolved JS source file, or `undefined` if it couldn't be resolved this way
14385
+ */
14386
+ function resolveModuleJsEntry(config, compilerCtx, moduleSpecifier, containingFile) {
14387
+ if (isLocalModule(moduleSpecifier)) return;
14388
+ const pkgJsonPath = tsResolveModuleNamePackageJsonPath(config, compilerCtx, moduleSpecifier, containingFile);
14389
+ if (!pkgJsonPath) return;
14390
+ let pkgJson;
14391
+ try {
14392
+ pkgJson = JSON.parse(config.sys.readFileSync(pkgJsonPath));
14393
+ } catch {
14394
+ return;
14395
+ }
14396
+ const pkgName = pkgJson.name;
14397
+ if (!pkgName || !moduleSpecifier.startsWith(pkgName) || !pkgJson.exports) return;
14398
+ const subpath = moduleSpecifier === pkgName ? "." : `.${moduleSpecifier.slice(pkgName.length)}`;
14399
+ const exportsMap = pkgJson.exports;
14400
+ const conditionEntry = typeof exportsMap === "string" ? subpath === "." ? exportsMap : void 0 : exportsMap[subpath] ?? (subpath === "." ? exportsMap : void 0);
14401
+ const target = conditionEntry && pickJsCondition(conditionEntry);
14402
+ if (!target) return;
14403
+ return readJsSourceFile(config, normalizePath(join$1(dirname(pkgJsonPath), target)));
14404
+ }
14405
+ /**
14406
+ * Finds `className`'s class inside a resolved JS entry (see `resolveModuleJsEntry`), following
14407
+ * re-export hops the same way `resolveAndProcessExtendedClass` walks a `.d.ts`/`.ts` source.
14408
+ * @param config the current Stencil validated config
14409
+ * @param compilerCtx the current compiler context
14410
+ * @param source the JS source file to search
14411
+ * @param className the class (or mixin factory) name to look for
14412
+ * @param hopsRemaining re-export hops still allowed before giving up
14413
+ * @returns the found class and the source file it's declared in, or `undefined`
14414
+ */
14415
+ function findClassInJsModule(config, compilerCtx, source, className, hopsRemaining = 3) {
14416
+ const matchedStatement = findStatementByName(source, className);
14417
+ if (matchedStatement) {
14418
+ const classNode = ts$1.isClassDeclaration(matchedStatement) ? matchedStatement : findClassWalk(matchedStatement);
14419
+ return classNode && {
14420
+ classNode,
14421
+ sourceFile: source
14422
+ };
14423
+ }
14424
+ if (hopsRemaining <= 0) return;
14425
+ const readReExported = (moduleSpecifier) => {
14426
+ const resolvedFileName = tsResolveModuleName(config, compilerCtx, moduleSpecifier, source.fileName)?.resolvedModule?.resolvedFileName;
14427
+ return resolvedFileName ? readJsSourceFile(config, resolvedFileName) : void 0;
14428
+ };
14429
+ const reExport = findReExport(source, className);
14430
+ if (reExport) {
14431
+ const nextSource = readReExported(reExport.moduleSpecifier);
14432
+ return nextSource && findClassInJsModule(config, compilerCtx, nextSource, reExport.localName, hopsRemaining - 1);
14433
+ }
14434
+ for (const moduleSpecifier of findStarReExportSpecifiers(source)) {
14435
+ const nextSource = readReExported(moduleSpecifier);
14436
+ const found = nextSource && findClassInJsModule(config, compilerCtx, nextSource, className, hopsRemaining - 1);
14437
+ if (found) return found;
13951
14438
  }
13952
14439
  }
13953
14440
  /**
@@ -14036,14 +14523,15 @@ function convertDiskSourceFileDecorators(sourceFile, config, target = ts$1.Scrip
14036
14523
  const program = ts$1.createProgram([sourceFile.fileName], compilerOptions, host);
14037
14524
  const typeChecker = program.getTypeChecker();
14038
14525
  const ownSourceFile = program.getSourceFile(sourceFile.fileName) ?? sourceFile;
14039
- const result = ts$1.transform(ownSourceFile, [convertDecoratorsToStatic(config, [], typeChecker, program)]);
14526
+ const result = ts$1.transform(ownSourceFile, [convertDecoratorsToStatic(config, [], typeChecker, program, true)]);
14040
14527
  const printed = ts$1.createPrinter({ removeComments: false }).printFile(result.transformed[0]);
14041
14528
  return ts$1.createSourceFile(sourceFile.fileName, printed, target, true);
14042
14529
  }
14043
14530
  /**
14044
14531
  * Resolves an `extends` target through a module specifier: resolves the
14045
14532
  * module, finds the named class/mixin-factory export, and adds it (and its
14046
- * own ancestors) to `dependentClasses`. Follows one level of re-export (barrel file) when the
14533
+ * own ancestors) to `dependentClasses`. Follows one level of re-export (barrel file, named or
14534
+ * `export *`) when the
14047
14535
  * declaration isn't found directly in the resolved module.
14048
14536
  * @param compilerCtx the current compiler context
14049
14537
  * @param buildCtx the current build context
@@ -14056,13 +14544,17 @@ function convertDiskSourceFileDecorators(sourceFile, config, target = ts$1.Scrip
14056
14544
  * @param ogModule the original module file of the class declaration
14057
14545
  * @param targetScriptTarget the script target to convert decorators with, if needed
14058
14546
  * @param barrelHopsRemaining re-export hops still allowed before giving up
14547
+ * @param originalModuleSpecifier the specifier this lookup started from, before any barrel hops
14548
+ * @param originalContainingFile the file `originalModuleSpecifier` was imported from
14059
14549
  * @returns the found class declaration, or `undefined`
14060
14550
  */
14061
- function resolveAndProcessExtendedClass(compilerCtx, buildCtx, classDeclaration, currentSource, moduleSpecifier, className, dependentClasses, typeChecker, ogModule, targetScriptTarget = ts$1.ScriptTarget.ESNext, barrelHopsRemaining = 1) {
14551
+ function resolveAndProcessExtendedClass(compilerCtx, buildCtx, classDeclaration, currentSource, moduleSpecifier, className, dependentClasses, typeChecker, ogModule, targetScriptTarget = ts$1.ScriptTarget.ESNext, barrelHopsRemaining = 1, originalModuleSpecifier = moduleSpecifier, originalContainingFile = currentSource.fileName) {
14062
14552
  let keepLooking = true;
14063
14553
  const foundFile = tsResolveModuleName(buildCtx.config, compilerCtx, moduleSpecifier, currentSource.fileName);
14064
14554
  if (!foundFile?.resolvedModule || !className) return;
14065
- let foundSource = compilerCtx.moduleMap.get(foundFile.resolvedModule.resolvedFileName)?.staticSourceFile;
14555
+ const resolvedFileName = foundFile.resolvedModule.resolvedFileName;
14556
+ let foundSource = compilerCtx.moduleMap.get(resolvedFileName)?.staticSourceFile;
14557
+ if (!foundSource && isJsFile(currentSource.fileName) && isJsFile(resolvedFileName)) foundSource = readJsSourceFile(buildCtx.config, resolvedFileName);
14066
14558
  if (!foundSource) {
14067
14559
  foundSource = tsGetSourceFile(buildCtx.config, foundFile);
14068
14560
  if (!foundSource) {
@@ -14074,10 +14566,10 @@ function resolveAndProcessExtendedClass(compilerCtx, buildCtx, classDeclaration,
14074
14566
  }
14075
14567
  foundSource = convertDiskSourceFileDecorators(foundSource, buildCtx.config, targetScriptTarget);
14076
14568
  }
14077
- const matchedStatement = foundSource.statements.find(matchesNamedDeclaration(className));
14569
+ const matchedStatement = findStatementByName(foundSource, className);
14078
14570
  if (!matchedStatement) {
14079
- const reExport = barrelHopsRemaining > 0 ? findReExport(foundSource, className) : void 0;
14080
- if (reExport) return resolveAndProcessExtendedClass(compilerCtx, buildCtx, classDeclaration, foundSource, reExport.moduleSpecifier, reExport.localName, dependentClasses, typeChecker, ogModule, targetScriptTarget, barrelHopsRemaining - 1);
14571
+ const reExport = barrelHopsRemaining > 0 ? findReExport(foundSource, className) ?? findStarReExportOf(buildCtx.config, compilerCtx, foundSource, className) : void 0;
14572
+ if (reExport) return resolveAndProcessExtendedClass(compilerCtx, buildCtx, classDeclaration, foundSource, reExport.moduleSpecifier, reExport.localName, dependentClasses, typeChecker, ogModule, targetScriptTarget, barrelHopsRemaining - 1, originalModuleSpecifier, originalContainingFile);
14081
14573
  const err = buildWarn(buildCtx.diagnostics);
14082
14574
  err.messageText = `Unable to find "${className}" in the imported module "${moduleSpecifier}".
14083
14575
  Please import class / mixin-factory declarations directly and not via barrel files.`;
@@ -14085,21 +14577,61 @@ function resolveAndProcessExtendedClass(compilerCtx, buildCtx, classDeclaration,
14085
14577
  return;
14086
14578
  }
14087
14579
  let foundClassDeclaration = matchedStatement ? ts$1.isClassDeclaration(matchedStatement) ? matchedStatement : void 0 : void 0;
14088
- if (!foundClassDeclaration && matchedStatement) {
14580
+ let foundClassSource = foundSource;
14581
+ const findInJsEntry = () => {
14582
+ if (!isDtsFile(foundSource.fileName) || isLocalModule(originalModuleSpecifier)) return;
14583
+ const jsSource = resolveModuleJsEntry(buildCtx.config, compilerCtx, originalModuleSpecifier, originalContainingFile);
14584
+ return jsSource && findClassInJsModule(buildCtx.config, compilerCtx, jsSource, className);
14585
+ };
14586
+ if (foundClassDeclaration) {
14587
+ const foundInJs = findInJsEntry();
14588
+ if (foundInJs) {
14589
+ foundClassDeclaration = foundInJs.classNode;
14590
+ foundClassSource = foundInJs.sourceFile;
14591
+ }
14592
+ } else if (matchedStatement) {
14089
14593
  foundClassDeclaration = findClassWalk(matchedStatement);
14090
14594
  keepLooking = false;
14595
+ if (!foundClassDeclaration) {
14596
+ const foundInJs = findInJsEntry();
14597
+ if (foundInJs) {
14598
+ foundClassDeclaration = foundInJs.classNode;
14599
+ foundClassSource = foundInJs.sourceFile;
14600
+ }
14601
+ }
14091
14602
  if (!foundClassDeclaration) warnMixinFactoryClassNotFound(buildCtx, className, classDeclaration);
14092
14603
  }
14093
14604
  if (foundClassDeclaration && !dependentClasses.some((dc) => dc.classNode === foundClassDeclaration)) {
14094
14605
  dependentClasses.push({
14095
14606
  classNode: foundClassDeclaration,
14096
- sourceFile: foundSource,
14097
- fileName: foundFile.resolvedModule.resolvedFileName
14607
+ sourceFile: foundClassSource,
14608
+ fileName: foundClassSource.fileName
14098
14609
  });
14099
14610
  if (keepLooking) buildExtendsTree(compilerCtx, foundClassDeclaration, dependentClasses, typeChecker, buildCtx, ogModule);
14100
14611
  }
14101
14612
  return foundClassDeclaration;
14102
14613
  }
14614
+ /**
14615
+ * Finds the first `export * from './x'` in `barrel` whose target declares `className` directly.
14616
+ * @param config the current Stencil validated config
14617
+ * @param compilerCtx the current compiler context
14618
+ * @param barrel the source file to scan
14619
+ * @param className the declaration name to look for
14620
+ * @returns the re-export to follow, in `findReExport`'s shape, or `undefined`
14621
+ */
14622
+ function findStarReExportOf(config, compilerCtx, barrel, className) {
14623
+ for (const moduleSpecifier of findStarReExportSpecifiers(barrel)) {
14624
+ const resolved = tsResolveModuleName(config, compilerCtx, moduleSpecifier, barrel.fileName);
14625
+ const fileName = resolved?.resolvedModule?.resolvedFileName;
14626
+ if (!fileName) continue;
14627
+ const target = compilerCtx.moduleMap.get(fileName)?.staticSourceFile ?? (isJsFile(fileName) ? readJsSourceFile(config, fileName) : tsGetSourceFile(config, resolved));
14628
+ if (target && findStatementByName(target, className)) return {
14629
+ moduleSpecifier,
14630
+ localName: className
14631
+ };
14632
+ }
14633
+ }
14634
+ const isJsFile = (fileName) => /\.[cm]?js$/.test(fileName);
14103
14635
  function convertDtsToJs(declarationSourceFile, compilerCtx) {
14104
14636
  const jsPath = normalizePath(declarationSourceFile.replace(/\.d\.ts$/, ".js").replace("/types/", "/collection/"));
14105
14637
  return compilerCtx.moduleMap.get(jsPath)?.staticSourceFile;
@@ -14123,6 +14655,7 @@ function buildExtendsTree(compilerCtx, classDeclaration, dependentClasses, typeC
14123
14655
  const targetScriptTarget = (ogModule?.staticSourceFile)?.languageVersion ?? ts$1.ScriptTarget.ESNext;
14124
14656
  let classIdentifiers = [];
14125
14657
  let foundClassDeclaration;
14658
+ let foundClassName;
14126
14659
  let keepLooking = true;
14127
14660
  extendsClause.types.forEach((type) => {
14128
14661
  if (ts$1.isExpressionWithTypeArguments(type) && ts$1.isCallExpression(type.expression) && type.expression.expression.getText() === "Mixin") classIdentifiers = type.expression.arguments.filter(ts$1.isIdentifier);
@@ -14139,9 +14672,11 @@ function buildExtendsTree(compilerCtx, classDeclaration, dependentClasses, typeC
14139
14672
  declarations = [...source.statements];
14140
14673
  }
14141
14674
  foundClassDeclaration = declarations?.find(ts$1.isClassDeclaration);
14675
+ foundClassName = foundClassDeclaration?.name?.getText();
14142
14676
  if (!foundClassDeclaration) {
14143
14677
  const node = declarations?.[0];
14144
14678
  foundClassDeclaration = findClassWalk(node);
14679
+ foundClassName = foundClassDeclaration?.name?.getText() ?? factoryDeclaredName(node);
14145
14680
  if (!node) throw "revert to sad path";
14146
14681
  keepLooking = false;
14147
14682
  if (!foundClassDeclaration) warnMixinFactoryClassNotFound(buildCtx, extendee.getText(), classDeclaration);
@@ -14150,7 +14685,7 @@ function buildExtendsTree(compilerCtx, classDeclaration, dependentClasses, typeC
14150
14685
  const foundModule = compilerCtx.moduleMap.get(foundClassDeclaration.getSourceFile().fileName);
14151
14686
  if (foundModule) {
14152
14687
  const moduleSourceFile = foundModule.staticSourceFile;
14153
- const sourceClass = findClassWalk(moduleSourceFile, foundClassDeclaration.name?.getText());
14688
+ const sourceClass = findClassWalk(moduleSourceFile, foundClassName);
14154
14689
  if (sourceClass) {
14155
14690
  dependentClasses.push({
14156
14691
  classNode: sourceClass,
@@ -14171,20 +14706,24 @@ function buildExtendsTree(compilerCtx, classDeclaration, dependentClasses, typeC
14171
14706
  if (!buildCtx.config._isTesting) augmentDiagnosticWithNode(err, classDeclaration);
14172
14707
  return;
14173
14708
  }
14174
- if (matchedStatement && ts$1.isClassDeclaration(matchedStatement)) foundClassDeclaration = matchedStatement;
14175
- else if (matchedStatement) {
14709
+ if (matchedStatement && ts$1.isClassDeclaration(matchedStatement)) {
14710
+ foundClassDeclaration = matchedStatement;
14711
+ foundClassName = foundClassDeclaration.name?.getText();
14712
+ } else if (matchedStatement) {
14176
14713
  foundClassDeclaration = findClassWalk(matchedStatement);
14714
+ foundClassName = foundClassDeclaration?.name?.getText() ?? extendee.getText();
14177
14715
  keepLooking = false;
14178
14716
  if (!foundClassDeclaration) warnMixinFactoryClassNotFound(buildCtx, extendee.getText(), classDeclaration);
14179
14717
  } else {
14180
14718
  foundClassDeclaration = findClassWalk(currentSource, extendee.getText());
14719
+ foundClassName = foundClassDeclaration?.name?.getText() ?? extendee.getText();
14181
14720
  keepLooking = false;
14182
14721
  }
14183
14722
  if (foundClassDeclaration && !dependentClasses.some((dc) => dc.classNode === foundClassDeclaration)) {
14184
14723
  const foundModule = compilerCtx.moduleMap.get(currentSource.fileName);
14185
14724
  if (foundModule?.staticSourceFile) {
14186
14725
  const transformedSource = foundModule.staticSourceFile;
14187
- const transformedClass = findClassWalk(transformedSource, foundClassDeclaration.name?.getText());
14726
+ const transformedClass = findClassWalk(transformedSource, foundClassName);
14188
14727
  if (transformedClass) {
14189
14728
  dependentClasses.push({
14190
14729
  classNode: transformedClass,
@@ -14469,7 +15008,7 @@ function convertInMemorySourceDecorators(sourceFile, config) {
14469
15008
  const program = ts$1.createProgram([sourceFile.fileName], compilerOptions, compilerHost);
14470
15009
  const typeChecker = program.getTypeChecker();
14471
15010
  const ownSourceFile = program.getSourceFile(sourceFile.fileName) ?? sourceFile;
14472
- const result = ts$1.transform(ownSourceFile, [convertDecoratorsToStatic(config, [], typeChecker, program)]);
15011
+ const result = ts$1.transform(ownSourceFile, [convertDecoratorsToStatic(config, [], typeChecker, program, true)]);
14473
15012
  const printed = ts$1.createPrinter({ removeComments: false }).printFile(result.transformed[0]);
14474
15013
  const scriptKind = sourceFile.fileName.endsWith(".tsx") || sourceFile.fileName.endsWith(".ts") ? ts$1.ScriptKind.TSX : ts$1.ScriptKind.JS;
14475
15014
  return ts$1.createSourceFile(sourceFile.fileName, printed, sourceFile.languageVersion, true, scriptKind);
@@ -14494,19 +15033,6 @@ function getExtendsClassNames(node) {
14494
15033
  if (ts$1.isCallExpression(expr) && expr.expression.getText() === "Mixin") return expr.arguments.filter(ts$1.isIdentifier).map((id) => id.text);
14495
15034
  return [];
14496
15035
  }
14497
- function findImportSpecifier(sf, localName) {
14498
- for (const stmt of sf.statements) {
14499
- if (!ts$1.isImportDeclaration(stmt) || !ts$1.isStringLiteral(stmt.moduleSpecifier)) continue;
14500
- const clause = stmt.importClause;
14501
- if (!clause) continue;
14502
- if (clause.name?.text === localName) return stmt.moduleSpecifier.text;
14503
- const bindings = clause.namedBindings;
14504
- if (bindings && ts$1.isNamedImports(bindings)) {
14505
- for (const el of bindings.elements) if (el.name.text === localName) return stmt.moduleSpecifier.text;
14506
- }
14507
- }
14508
- return null;
14509
- }
14510
15036
  /**
14511
15037
  * A single-file mini-program (see `convertInMemorySourceDecorators`) can
14512
15038
  * never load an imported module's own `SourceFile`, so a type that's
@@ -14530,7 +15056,7 @@ function reclassifyGlobalTypeReferences(members, declaringSf, declaringPath, res
14530
15056
  if (!references) return;
14531
15057
  Object.entries(references).forEach(([typeName, reference]) => {
14532
15058
  if (reference.location !== "global") return;
14533
- const specifier = findImportSpecifier(declaringSf, typeName);
15059
+ const specifier = findImportOrigin(declaringSf, typeName)?.moduleSpecifier;
14534
15060
  if (!specifier) return;
14535
15061
  const resolved = resolveImport(specifier, declaringPath);
14536
15062
  reference.location = "import";
@@ -14542,7 +15068,7 @@ function reclassifyGlobalTypeReferences(members, declaringSf, declaringPath, res
14542
15068
  }
14543
15069
  /**
14544
15070
  * Looks for `name` as a direct top-level declaration in `sf`; if not found, follows one level of
14545
- * re-export (barrel file) via `resolveImport` - matching `compiler-ctx-merge.ts`'s equivalent
15071
+ * re-export (barrel file, named or `export *`) via `resolveImport` - matching `compiler-ctx-merge.ts`'s equivalent
14546
15072
  * one-hop fallback (see `findReExport` in `shared.ts` for why it's capped at one hop).
14547
15073
  *
14548
15074
  * @param sf the source file to search
@@ -14553,26 +15079,31 @@ function reclassifyGlobalTypeReferences(members, declaringSf, declaringPath, res
14553
15079
  * differ from `sf`/`path` if resolved through a re-export), or `undefined`
14554
15080
  */
14555
15081
  function findDeclarationOrReExport(sf, path, name, resolveImport) {
14556
- const direct = sf.statements.find(matchesNamedDeclaration(name));
15082
+ const direct = findStatementByName(sf, name);
14557
15083
  if (direct) return {
14558
15084
  statement: direct,
14559
15085
  sourceFile: sf,
14560
15086
  path
14561
15087
  };
14562
- const reExport = findReExport(sf, name);
14563
- if (!reExport) return void 0;
14564
- const resolved = resolveImport(reExport.moduleSpecifier, path);
14565
- if (!resolved) return void 0;
14566
- const { code, path: resolvedPath } = resolved;
14567
- const isTs = resolvedPath.endsWith(".tsx") || resolvedPath.endsWith(".ts");
14568
- const reExportSf = ts$1.createSourceFile(resolvedPath, code, ts$1.ScriptTarget.ESNext, true, isTs ? ts$1.ScriptKind.TSX : ts$1.ScriptKind.JS);
14569
- const statement = reExportSf.statements.find(matchesNamedDeclaration(reExport.localName));
14570
- if (!statement) return void 0;
14571
- return {
14572
- statement,
14573
- sourceFile: reExportSf,
14574
- path: resolvedPath
15088
+ const findIn = (moduleSpecifier, localName) => {
15089
+ const resolved = resolveImport(moduleSpecifier, path);
15090
+ if (!resolved) return void 0;
15091
+ const { code, path: resolvedPath } = resolved;
15092
+ const isTs = resolvedPath.endsWith(".tsx") || resolvedPath.endsWith(".ts");
15093
+ const reExportSf = ts$1.createSourceFile(resolvedPath, code, ts$1.ScriptTarget.ESNext, true, isTs ? ts$1.ScriptKind.TSX : ts$1.ScriptKind.JS);
15094
+ const statement = findStatementByName(reExportSf, localName);
15095
+ return statement && {
15096
+ statement,
15097
+ sourceFile: reExportSf,
15098
+ path: resolvedPath
15099
+ };
14575
15100
  };
15101
+ const reExport = findReExport(sf, name);
15102
+ if (reExport) return findIn(reExport.moduleSpecifier, reExport.localName);
15103
+ for (const moduleSpecifier of findStarReExportSpecifiers(sf)) {
15104
+ const found = findIn(moduleSpecifier, name);
15105
+ if (found) return found;
15106
+ }
14576
15107
  }
14577
15108
  /**
14578
15109
  * Recursively resolves a class's `extends` heritage into a flat, deduplicated
@@ -14603,7 +15134,7 @@ function resolveAncestors(classNode, sf, path, resolveImport, visited, ancestors
14603
15134
  let foundSf = sf;
14604
15135
  let foundPath = path;
14605
15136
  let keepLooking = true;
14606
- const sameFileStatement = sf.statements.find(matchesNamedDeclaration(parentName));
15137
+ const sameFileStatement = findStatementByName(sf, parentName);
14607
15138
  if (sameFileStatement) {
14608
15139
  if (ts$1.isClassDeclaration(sameFileStatement)) foundClass = sameFileStatement;
14609
15140
  else {
@@ -14612,7 +15143,7 @@ function resolveAncestors(classNode, sf, path, resolveImport, visited, ancestors
14612
15143
  if (!foundClass) warnMixinFactoryClassNotFound(buildCtx, parentName, rootClassDeclaration);
14613
15144
  }
14614
15145
  } else {
14615
- const specifier = findImportSpecifier(sf, parentName);
15146
+ const specifier = findImportOrigin(sf, parentName)?.moduleSpecifier;
14616
15147
  if (!specifier) continue;
14617
15148
  const resolved = resolveImport(specifier, path);
14618
15149
  if (!resolved) continue;
@@ -14644,7 +15175,8 @@ function resolveAncestors(classNode, sf, path, resolveImport, visited, ancestors
14644
15175
  ancestors.push({
14645
15176
  classNode: foundClass,
14646
15177
  sourceFile: foundSf,
14647
- path: foundPath
15178
+ path: foundPath,
15179
+ factoryName: parentName
14648
15180
  });
14649
15181
  if (keepLooking) resolveAncestors(foundClass, foundSf, foundPath, resolveImport, visited, ancestors, rootClassDeclaration, buildCtx);
14650
15182
  }
@@ -14661,8 +15193,8 @@ function resolveAncestors(classNode, sf, path, resolveImport, visited, ancestors
14661
15193
  * @returns the ancestor's metadata
14662
15194
  */
14663
15195
  function extractAncestorMeta(ancestor, cmpSourceFile, resolveImport, config) {
14664
- const { classNode, sourceFile: parentSf, path: resolvedPath } = ancestor;
14665
- const className = classNode.name?.text;
15196
+ const { classNode, sourceFile: parentSf, path: resolvedPath, factoryName } = ancestor;
15197
+ const className = classNode.name?.text ?? factoryName;
14666
15198
  const parentStaticMembers = classNode.members.filter(isStaticGetter);
14667
15199
  let resolvedClassNode = classNode;
14668
15200
  let resolvedStaticMembers = parentStaticMembers;
@@ -14672,6 +15204,8 @@ function extractAncestorMeta(ancestor, cmpSourceFile, resolveImport, config) {
14672
15204
  "events",
14673
15205
  "listeners",
14674
15206
  "watchers",
15207
+ "serializers",
15208
+ "deserializers",
14675
15209
  "methods"
14676
15210
  ].includes(m.name.text));
14677
15211
  if (!hasUsableStaticMembers && className) {
@@ -14691,6 +15225,8 @@ function extractAncestorMeta(ancestor, cmpSourceFile, resolveImport, config) {
14691
15225
  events: reanchorInheritedTypeReferences(reclassifyGlobalTypeReferences(parseStaticEvents(resolvedStaticMembers) ?? [], parentSf, resolvedPath, resolveImport), resolvedPath, cmpSourceFile.fileName),
14692
15226
  listeners: parseStaticListeners(resolvedStaticMembers) ?? [],
14693
15227
  watchers: parseStaticWatchers(resolvedStaticMembers) ?? [],
15228
+ serializers: parseStaticSerializers(resolvedStaticMembers, "serializers") ?? [],
15229
+ deserializers: parseStaticSerializers(resolvedStaticMembers, "deserializers") ?? [],
14694
15230
  methodNames: resolvedClassNode.members.filter(ts$1.isMethodDeclaration).map((m) => ts$1.isIdentifier(m.name) ? m.name.text : "").filter(Boolean)
14695
15231
  };
14696
15232
  }
@@ -14720,8 +15256,8 @@ function mergeExtendedClassMetaWithResolveImport(cmpNode, staticMembers, sourceF
14720
15256
  let events = parseStaticEvents(staticMembers);
14721
15257
  let watchers = parseStaticWatchers(staticMembers);
14722
15258
  let classMethods = cmpNode.members.filter(ts$1.isMethodDeclaration).map((m) => ts$1.isIdentifier(m.name) ? m.name.text : "").filter(Boolean);
14723
- const serializers = [];
14724
- const deserializers = [];
15259
+ let serializers = parseStaticSerializers(staticMembers, "serializers");
15260
+ let deserializers = parseStaticSerializers(staticMembers, "deserializers");
14725
15261
  const ancestors = [];
14726
15262
  resolveAncestors(cmpNode, sourceFile, sourceFile.fileName, resolveImport, /* @__PURE__ */ new Set(), ancestors, cmpNode, buildCtx);
14727
15263
  ancestors.forEach((ancestor) => {
@@ -14735,6 +15271,8 @@ function mergeExtendedClassMetaWithResolveImport(cmpNode, staticMembers, sourceF
14735
15271
  events = [...deDupeMembers(parentMeta.events, events), ...events];
14736
15272
  listeners = [...deDupeMembers(parentMeta.listeners, listeners), ...listeners];
14737
15273
  watchers = [...deDupeMembers(parentMeta.watchers, watchers), ...watchers];
15274
+ serializers = [...deDupeMembers(parentMeta.serializers ?? [], serializers), ...serializers];
15275
+ deserializers = [...deDupeMembers(parentMeta.deserializers ?? [], deserializers), ...deserializers];
14738
15276
  classMethods = [...classMethods, ...parentMeta.methodNames];
14739
15277
  });
14740
15278
  return {
@@ -14754,7 +15292,6 @@ function mergeExtendedClassMetaWithResolveImport(cmpNode, staticMembers, sourceF
14754
15292
  //#region src/compiler/transformers/static-to-meta/class-methods.ts
14755
15293
  const parseClassMethods = (classMethods, cmpMeta) => {
14756
15294
  if (!classMethods?.length) return;
14757
- const hasHostData = classMethods.includes("hostData");
14758
15295
  cmpMeta.hasAttributeChangedCallbackFn = classMethods.includes("attributeChangedCallback");
14759
15296
  cmpMeta.hasConnectedCallbackFn = classMethods.includes("connectedCallback");
14760
15297
  cmpMeta.hasDisconnectedCallbackFn = classMethods.includes("disconnectedCallback");
@@ -14766,8 +15303,7 @@ const parseClassMethods = (classMethods, cmpMeta) => {
14766
15303
  cmpMeta.hasComponentShouldUpdateFn = classMethods.includes("componentShouldUpdate");
14767
15304
  cmpMeta.hasComponentDidUpdateFn = classMethods.includes("componentDidUpdate");
14768
15305
  cmpMeta.hasLifecycle = cmpMeta.hasComponentWillLoadFn || cmpMeta.hasComponentDidLoadFn || cmpMeta.hasComponentWillUpdateFn || cmpMeta.hasComponentDidUpdateFn;
14769
- cmpMeta.hasRenderFn = classMethods.includes("render") || hasHostData;
14770
- cmpMeta.hasVdomRender = cmpMeta.hasVdomRender || hasHostData;
15306
+ cmpMeta.hasRenderFn = classMethods.includes("render");
14771
15307
  };
14772
15308
  //#endregion
14773
15309
  //#region src/compiler/transformers/static-to-meta/element-ref.ts
@@ -14846,6 +15382,20 @@ const parseStaticSlotAssignment = (encapsulation, staticMembers) => {
14846
15382
  return null;
14847
15383
  };
14848
15384
  /**
15385
+ * Find and return the shadow root `referenceTarget` for a component.
15386
+ *
15387
+ * @param encapsulation the encapsulation mode to use for a component
15388
+ * @param staticMembers a collection of static getters to search
15389
+ * @returns the `referenceTarget` id if encapsulation is 'shadow' and one is set, otherwise `null`
15390
+ */
15391
+ const parseStaticShadowReferenceTarget = (encapsulation, staticMembers) => {
15392
+ if (encapsulation === "shadow") {
15393
+ const referenceTarget = getStaticValue(staticMembers, "referenceTarget");
15394
+ if (typeof referenceTarget === "string" && referenceTarget.trim()) return referenceTarget.trim();
15395
+ }
15396
+ return null;
15397
+ };
15398
+ /**
14849
15399
  * Find and return the shadow DOM mode for a component.
14850
15400
  *
14851
15401
  * @param encapsulation the encapsulation mode to use for a component
@@ -15062,6 +15612,7 @@ const parseStaticComponentMeta = (compilerCtx, typeChecker, cmpNode, moduleFile,
15062
15612
  shadowSerializable: !!parseStaticShadowSerializable(encapsulation, staticMembers),
15063
15613
  shadowMode: parseStaticShadowMode(encapsulation, staticMembers),
15064
15614
  slotAssignment: parseStaticSlotAssignment(encapsulation, staticMembers),
15615
+ shadowReferenceTarget: parseStaticShadowReferenceTarget(encapsulation, staticMembers),
15065
15616
  patches: parseStaticPatches(encapsulation, staticMembers),
15066
15617
  properties,
15067
15618
  virtualProperties: parseVirtualProps(docs),
@@ -15147,13 +15698,13 @@ const parseStaticComponentMeta = (compilerCtx, typeChecker, cmpNode, moduleFile,
15147
15698
  hasPatchClone: false,
15148
15699
  hasPatchInsert: false
15149
15700
  };
15150
- const visitComponentChildNode = (node, ctx) => {
15151
- validateComponentMembers(node, ctx);
15152
- if (ts$1.isCallExpression(node)) parseCallExpression(cmp, node, typeChecker);
15701
+ if (!isCollectionDependency) validateComponentMembers(cmpNode, buildCtx);
15702
+ const visitComponentChildNode = (node) => {
15703
+ if (ts$1.isCallExpression(node)) parseCallExpression(cmp, node, typeChecker, moduleFile);
15153
15704
  else if (ts$1.isStringLiteral(node)) parseStringLiteral(cmp, node);
15154
- node.forEachChild((child) => visitComponentChildNode(child, ctx));
15705
+ node.forEachChild(visitComponentChildNode);
15155
15706
  };
15156
- visitComponentChildNode(cmpNode, buildCtx);
15707
+ visitComponentChildNode(cmpNode);
15157
15708
  parseClassMethods(classMethods, cmp);
15158
15709
  cmp.hasModernPropertyDecls = detectModernPropDeclarations(cmpNode) || doesExtend;
15159
15710
  cmp.htmlAttrNames = unique(cmp.htmlAttrNames);
@@ -15171,31 +15722,32 @@ const parseStaticComponentMeta = (compilerCtx, typeChecker, cmpNode, moduleFile,
15171
15722
  return cmpNode;
15172
15723
  };
15173
15724
  /**
15174
- * Check whether a class declaration is a Stencil component, i.e. it's
15175
- * decorated with `@Component({ tag: ... })`.
15176
- * @param classNode the class declaration to check
15177
- * @returns whether `classNode` is a Stencil component class
15725
+ * Warn about members a Stencil component class should not define.
15726
+ * @param cmpNode the component class declaration
15727
+ * @param buildCtx the current build context, used to surface diagnostics
15178
15728
  */
15179
- const isStencilComponentClass = (classNode) => {
15180
- const decorator = ts$1.getDecorators(classNode)?.[0];
15181
- return decorator != null && ts$1.isCallExpression(decorator.expression) && decorator.expression.arguments.length === 1 && ts$1.isObjectLiteralExpression(decorator.expression.arguments[0]) && decorator.expression.arguments[0].properties.some((prop) => ts$1.isPropertyAssignment(prop) && prop.name.getText() === "tag");
15182
- };
15183
- const validateComponentMembers = (node, buildCtx) => {
15184
- /**
15185
- * validate if:
15186
- */
15187
- if (ts$1.isGetAccessorDeclaration(node) && ts$1.isIdentifier(node.name) && typeof node.name.escapedText === "string" && BLACKLISTED_COMPONENT_METHODS.includes(node.name.escapedText) && node.parent && ts$1.isClassDeclaration(node.parent) && isStencilComponentClass(node.parent)) {
15188
- const propName = node.name.escapedText;
15189
- const componentName = node.parent.name.getText();
15190
- const err = buildWarn(buildCtx.diagnostics);
15191
- err.messageText = `The component "${componentName}" has a getter called "${propName}". This getter is reserved for use by Stencil components and should not be defined by the user.`;
15192
- augmentDiagnosticWithNode(err, node);
15193
- }
15194
- if (ts$1.isMethodDeclaration(node) && ts$1.isIdentifier(node.name) && node.name.escapedText === "componentShouldUpdate" && node.parameters.length > 1 && node.parent && ts$1.isClassDeclaration(node.parent) && isStencilComponentClass(node.parent)) {
15195
- const componentName = node.parent.name.getText();
15196
- const err = buildWarn(buildCtx.diagnostics);
15197
- err.messageText = `The component "${componentName}" defines "componentShouldUpdate" with ${node.parameters.length} parameters. As of Stencil v5, "componentShouldUpdate" is called once per render with a single "changes" argument (a map of prop/state names to "{ newVal, oldVal }") instead of once per prop with "(newVal, oldVal, propName)". This method will still compile, but any extra parameters will be "undefined" at runtime.`;
15198
- augmentDiagnosticWithNode(err, node);
15729
+ const validateComponentMembers = (cmpNode, buildCtx) => {
15730
+ const componentName = cmpNode.name?.text ?? "";
15731
+ for (const member of cmpNode.members) {
15732
+ if (!member.name || !ts$1.isIdentifier(member.name)) continue;
15733
+ const memberName = member.name.text;
15734
+ /**
15735
+ * the component has a getter called "shadowRoot"
15736
+ */
15737
+ if (ts$1.isGetAccessorDeclaration(member) && BLACKLISTED_COMPONENT_METHODS.includes(memberName)) {
15738
+ const err = buildWarn(buildCtx.diagnostics);
15739
+ err.messageText = `The component "${componentName}" has a getter called "${memberName}". This getter is reserved for use by Stencil components and should not be defined by the user.`;
15740
+ augmentDiagnosticWithNode(err, ts$1.getOriginalNode(member));
15741
+ }
15742
+ /**
15743
+ * the component defines a "componentShouldUpdate" method with more than one parameter,
15744
+ * which was the pre-v5 per-prop signature "(newVal, oldVal, propName)"
15745
+ */
15746
+ if (ts$1.isMethodDeclaration(member) && memberName === "componentShouldUpdate" && member.parameters.length > 1) {
15747
+ const err = buildWarn(buildCtx.diagnostics);
15748
+ err.messageText = `The component "${componentName}" defines "componentShouldUpdate" with ${member.parameters.length} parameters. As of Stencil v5, "componentShouldUpdate" is called once per render with a single "changes" argument (a map of prop/state names to "{ newVal, oldVal }") instead of once per prop with "(newVal, oldVal, propName)". This method will still compile, but any extra parameters will be "undefined" at runtime.`;
15749
+ augmentDiagnosticWithNode(err, ts$1.getOriginalNode(member));
15750
+ }
15199
15751
  }
15200
15752
  };
15201
15753
  const parseVirtualProps = (docs) => {
@@ -15365,27 +15917,15 @@ const updateModule = (config, compilerCtx, buildCtx, tsSourceFile, sourceFileTex
15365
15917
  if (ts$1.isClassDeclaration(node)) {
15366
15918
  parseStaticComponentMeta(compilerCtx, typeChecker, node, moduleFile, buildCtx, void 0);
15367
15919
  if (isExportableMixinClass(node)) moduleFile.hasExportableMixins = true;
15368
- return;
15920
+ if (getComponentTagName(node.members.filter(isStaticGetter)) != null) return;
15369
15921
  } else if (ts$1.isImportDeclaration(node)) {
15370
15922
  parseModuleImport(config, compilerCtx, buildCtx, moduleFile, srcDirPath, node, true);
15371
15923
  return;
15924
+ } else if (ts$1.isExportDeclaration(node)) {
15925
+ parseModuleReExport(moduleFile, srcDirPath, node);
15926
+ return;
15372
15927
  } else if (ts$1.isCallExpression(node)) parseCallExpression(moduleFile, node, typeChecker);
15373
15928
  else if (ts$1.isStringLiteral(node)) parseStringLiteral(moduleFile, node);
15374
- else if (ts$1.isVariableStatement(node)) node.declarationList.declarations.forEach((declaration) => {
15375
- if (declaration.initializer) {
15376
- if (ts$1.isArrowFunction(declaration.initializer) || ts$1.isFunctionExpression(declaration.initializer)) {
15377
- const funcBody = declaration.initializer.body;
15378
- if (ts$1.isBlock(funcBody)) funcBody.statements.forEach((statement) => {
15379
- if (ts$1.isClassDeclaration(statement)) {
15380
- if (isExportableMixinClass(statement)) moduleFile.hasExportableMixins = true;
15381
- statement.members.forEach((member) => {
15382
- if (ts$1.isPropertyDeclaration(member) && member.initializer) ts$1.forEachChild(member.initializer, visitNode);
15383
- });
15384
- }
15385
- });
15386
- }
15387
- }
15388
- });
15389
15929
  node.forEachChild(visitNode);
15390
15930
  };
15391
15931
  if (collection != null) {
@@ -15539,18 +16079,32 @@ const addExternalImport = (config, compilerCtx, buildCtx, moduleFile, containing
15539
16079
  //#region src/compiler/transformers/static-to-meta/import.ts
15540
16080
  const parseModuleImport = (config, compilerCtx, buildCtx, moduleFile, dirPath, importNode, resolveCollections) => {
15541
16081
  if (importNode.moduleSpecifier && ts$1.isStringLiteral(importNode.moduleSpecifier)) {
15542
- let importPath = importNode.moduleSpecifier.text;
16082
+ const importPath = importNode.moduleSpecifier.text;
15543
16083
  if (!moduleFile.originalImports.includes(importPath)) moduleFile.originalImports.push(importPath);
15544
16084
  if (importPath === "@stencil/core/signals") moduleFile.hasSignalsImport = true;
15545
- if (isAbsolute(importPath)) {
15546
- importPath = normalizePath(importPath);
15547
- moduleFile.localImports.push(importPath);
15548
- } else if (importPath.startsWith(".")) {
15549
- importPath = normalizePath(join$1(dirPath, importPath));
15550
- moduleFile.localImports.push(importPath);
15551
- } else addExternalImport(config, compilerCtx, buildCtx, moduleFile, moduleFile.sourceFilePath, importPath, resolveCollections, !importNode.importClause);
16085
+ const localPath = resolveLocalImportPath(dirPath, importPath);
16086
+ if (localPath) moduleFile.localImports.push(localPath);
16087
+ else addExternalImport(config, compilerCtx, buildCtx, moduleFile, moduleFile.sourceFilePath, importPath, resolveCollections, !importNode.importClause);
15552
16088
  }
15553
16089
  };
16090
+ /**
16091
+ * Record a local `export … from './x'` re-export as a local import, so build conditionals
16092
+ * propagate through barrel files. Bare-specifier re-exports are left alone.
16093
+ *
16094
+ * @param moduleFile the module containing the re-export
16095
+ * @param dirPath the module's (normalized) directory
16096
+ * @param exportNode the export declaration
16097
+ */
16098
+ const parseModuleReExport = (moduleFile, dirPath, exportNode) => {
16099
+ if (exportNode.moduleSpecifier && ts$1.isStringLiteral(exportNode.moduleSpecifier)) {
16100
+ const localPath = resolveLocalImportPath(dirPath, exportNode.moduleSpecifier.text);
16101
+ if (localPath && !moduleFile.localImports.includes(localPath)) moduleFile.localImports.push(localPath);
16102
+ }
16103
+ };
16104
+ const resolveLocalImportPath = (dirPath, importPath) => {
16105
+ if (isAbsolute(importPath)) return normalizePath(importPath);
16106
+ if (importPath.startsWith(".")) return normalizePath(join$1(dirPath, importPath));
16107
+ };
15554
16108
  //#endregion
15555
16109
  //#region src/compiler/transformers/static-to-meta/visitor.ts
15556
16110
  const convertStaticToMeta = (config, compilerCtx, buildCtx, typeChecker, collection, transformOpts) => {
@@ -15560,6 +16114,7 @@ const convertStaticToMeta = (config, compilerCtx, buildCtx, typeChecker, collect
15560
16114
  const visitNode = (node) => {
15561
16115
  if (ts$1.isClassDeclaration(node)) return parseStaticComponentMeta(compilerCtx, typeChecker, node, moduleFile, buildCtx, transformOpts);
15562
16116
  else if (ts$1.isImportDeclaration(node)) parseModuleImport(config, compilerCtx, buildCtx, moduleFile, dirPath, node, !transformOpts.isolatedModules);
16117
+ else if (ts$1.isExportDeclaration(node)) parseModuleReExport(moduleFile, dirPath, node);
15563
16118
  else if (ts$1.isCallExpression(node)) parseCallExpression(moduleFile, node, typeChecker);
15564
16119
  else if (ts$1.isStringLiteral(node)) parseStringLiteral(moduleFile, node);
15565
16120
  return ts$1.visitEachChild(node, visitNode, transformCtx);
@@ -15604,9 +16159,9 @@ const updateStencilCoreImports = (updatedCoreImportPath) => {
15604
16159
  }
15605
16160
  if (moduleSpecifierText === "@stencil/core") {
15606
16161
  if (s.importClause && s.importClause.namedBindings && s.importClause.namedBindings.kind === ts$1.SyntaxKind.NamedImports) {
15607
- const keepImports = s.importClause.namedBindings.elements.map((e) => e.getText()).filter((name) => KEEP_IMPORTS.has(name));
16162
+ const keepImports = s.importClause.namedBindings.elements.filter((e) => KEEP_IMPORTS.has((e.propertyName ?? e.name).text));
15608
16163
  if (keepImports.length > 0) {
15609
- const newImport = ts$1.factory.updateImportDeclaration(s, void 0, ts$1.factory.createImportClause(false, void 0, ts$1.factory.createNamedImports(keepImports.map((name) => ts$1.factory.createImportSpecifier(false, void 0, ts$1.factory.createIdentifier(name))))), ts$1.factory.createStringLiteral(updatedCoreImportPath), void 0);
16164
+ const newImport = ts$1.factory.updateImportDeclaration(s, void 0, ts$1.factory.createImportClause(false, void 0, ts$1.factory.createNamedImports(keepImports.map((e) => ts$1.factory.createImportSpecifier(false, e.propertyName ? ts$1.factory.createIdentifier(e.propertyName.text) : void 0, ts$1.factory.createIdentifier(e.name.text))))), ts$1.factory.createStringLiteral(updatedCoreImportPath), void 0);
15610
16165
  newStatements.push(newImport);
15611
16166
  }
15612
16167
  }
@@ -15666,6 +16221,7 @@ const transpileModule = (config, input, transformOpts) => {
15666
16221
  ...config,
15667
16222
  logger: createNodeLogger()
15668
16223
  };
16224
+ resetDeprecatedApiWarning();
15669
16225
  const compilerCtx = new CompilerContext();
15670
16226
  const buildCtx = new BuildContext(config, compilerCtx);
15671
16227
  const tsCompilerOptions = { ...config.tsCompilerOptions };
@@ -15843,6 +16399,7 @@ const transpileCss = async (transformInput, results) => {
15843
16399
  results.map = cssResults.map;
15844
16400
  results.imports = cssResults.imports.map((p) => ({ path: p.importPath }));
15845
16401
  results.diagnostics.push(...cssResults.diagnostics);
16402
+ if (transformInput.docs) results.styleDocs = cssResults.styleDocs;
15846
16403
  };
15847
16404
  const transpileCssSync = (transformInput, results) => {
15848
16405
  const cssResults = transformCssToEsmSync(transformInput);
@@ -15850,6 +16407,7 @@ const transpileCssSync = (transformInput, results) => {
15850
16407
  results.map = cssResults.map;
15851
16408
  results.imports = cssResults.imports.map((p) => ({ path: p.importPath }));
15852
16409
  results.diagnostics.push(...cssResults.diagnostics);
16410
+ if (transformInput.docs) results.styleDocs = cssResults.styleDocs;
15853
16411
  };
15854
16412
  const transpileJson = (results) => {
15855
16413
  results.code = dataToEsm(JSON.parse(results.code), {
@@ -16280,7 +16838,7 @@ const FORM_ASSOCIATED_ATTRIBUTES = [
16280
16838
  * @param cmp the metadata for the component that a type definition string is generated for
16281
16839
  * @param typeImportData locally/imported/globally used type names, which may be used to prevent naming collisions
16282
16840
  * @param areTypesInternal `true` if types being generated are for a project's internal purposes, `false` otherwise
16283
- * @param signalBacking `true` if the component is using signal backing for its props; includes the signals map on the element interface
16841
+ * @param signalBacking `true` if the component is using signal backing for its props; includes the signals map on the element interface and unions JSX prop types with `ReadonlySignal<T>`
16284
16842
  * @returns the generated types string alongside additional metadata
16285
16843
  */
16286
16844
  const generateComponentTypes = (cmp, typeImportData, areTypesInternal, signalBacking = false) => {
@@ -16297,8 +16855,12 @@ const generateComponentTypes = (cmp, typeImportData, areTypesInternal, signalBac
16297
16855
  const isDep = cmp.isCollectionDependency;
16298
16856
  const propNames = new Set(propAttributes.map((p) => p.name));
16299
16857
  const formAssociatedAttrs = cmp.formAssociated ? FORM_ASSOCIATED_ATTRIBUTES.filter((attr) => !propNames.has(attr.name)) : [];
16858
+ const jsxPropAttributes = signalBacking ? propAttributes.map((attr) => ({
16859
+ ...attr,
16860
+ type: `${attr.type} | ReadonlySignal<${attr.type}>`
16861
+ })) : propAttributes;
16300
16862
  const jsxAttributes = attributesToMultiLineString([
16301
- ...propAttributes,
16863
+ ...jsxPropAttributes,
16302
16864
  ...eventAttributes,
16303
16865
  ...formAssociatedAttrs
16304
16866
  ], true, areTypesInternal);