@stencil/core 5.0.0-rc.14 → 5.0.0-rc.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,9 +1,9 @@
1
1
  import { n as __require } from "./rolldown-runtime-BhDjJH2R.mjs";
2
- import { A as SSR_PROP_REF_PREFIX, D as HYDRATE_ID, E as HYDRATE_CHILD_ID, O as SERVER_BUILD_FLAGS, T as HYDRATED_CSS, k as SSR_PROPS_REGISTRY_KEY, w as CLIENT_BUILD_FLAGS } from "./client-Cpehp9QL.mjs";
2
+ import { A as SSR_PROP_REF_PREFIX, D as HYDRATE_ID, E as HYDRATE_CHILD_ID, O as SERVER_BUILD_FLAGS, T as HYDRATED_CSS, k as SSR_PROPS_REGISTRY_KEY, w as CLIENT_BUILD_FLAGS } from "./client-nVB5tHhh.mjs";
3
3
  import { $ as VALID_CONFIG_OUTPUT_TARGETS, A as DIST_LAZY, D as COPY, E as COLLECTION_MANIFEST_FILE_NAME, J as STANDALONE, L as EVENT_FLAGS, P as DOCS_JSON, Q as TYPES, R as GENERATED_DTS, S as ASSETS, T as COLLECTION_APP_DATA_FILE_NAME, U as LOADER_BUNDLE, X as STYLE_EXT, Y as STATS, a as isBoolean$1, b as unique, c as isFunction, d as isObject, et as WATCH_FLAGS, f as isString$1, g as sortBy, i as fromEntries, l as isIterable, m as noop, p as mergeIntoWith, r as flatOne, t as dashToPascalCase, u as isNumber$1, v as toDashCase, w as COLLECTION, y as toTitleCase, z as GLOBAL_STYLE } from "./helpers-k8xQHE77.mjs";
4
4
  import { C as isRootPath, D as byteSize, E as stringifyRuntimeData, O as escapeRegExpSpecialCharacters, S as splitLineBreaks, _ as createOnWarnFn, a as getRolldownSourceMapOptions, c as relativizeSourceMap, d as map, f as ok, g as loadTypeScriptDiagnostics, h as loadTypeScriptDiagnostic, i as getInlineSourceMappingUrlLinker, l as rolldownToStencilSourceMap, m as augmentDiagnosticWithNode, n as validateComponentTag, o as getSourceMappingUrlForEndOfFile, r as isRemoteUrl, t as validateComponentModes, u as err, v as isRolldownError, w as formatComponentRuntimeMeta, x as normalizeDiagnostics, y as loadRolldownDiagnostics } from "./validation-GfBzquhJ.mjs";
5
5
  import { $ as buildWarn, A as isOutputTargetDocsVscode, B as isValidConfigOutputTarget, C as isOutputTargetDistLazy, D as isOutputTargetDocsCustomElementsManifest, E as isOutputTargetDocsCustom, F as isOutputTargetSsrWasm, G as normalizeFsPath, H as shouldExcludeComponent, I as isOutputTargetStandalone, J as relative$1, K as normalizeFsPathQuery, L as isOutputTargetStats, M as isOutputTargetLoaderBundle, N as isOutputTargetServerRenderer, O as isOutputTargetDocsJson, P as isOutputTargetSsr, Q as buildJsonFileError, R as isOutputTargetTypes, S as isOutputTargetCustom, T as isOutputTargetDocsAgentSkill, U as join$2, V as relativeImport, Y as resolve$2, Z as buildError, a as hasDependency, b as isOutputTargetCollection, d as parsePackageJson, et as catchError, f as readOnlyArrayHasStringMember, g as getComponentsDtsSrcFilePath, h as filterExcludedComponents, i as getTextDocs, it as isGlob, j as isOutputTargetGlobalStyle, k as isOutputTargetDocsReadme, l as isTsFile, m as filterActiveTargets, n as createJsVarName, nt as hasWarning, o as isDtsFile, p as readPackageJson, q as normalizePath, r as generatePreamble, t as addDocBlock, tt as hasError, u as isTsxFile, v as getComponentsFromModules, w as isOutputTargetDocs, x as isOutputTargetCopy, y as isOutputTargetAssets, z as isOutputTargetWww } from "./util-Cj2D3x_h.mjs";
6
- import { i as CustomElementsExportBehaviorOptions, o as buildEvents, r as createNodeLogger, t as createNodeSys } from "./node-C6N23fLr.mjs";
6
+ import { i as CustomElementsExportBehaviorOptions, o as buildEvents, r as createNodeLogger, t as createNodeSys } from "./node-IRt_dGbC.mjs";
7
7
  import ts, { default as ts$1 } from "typescript";
8
8
  import { readFileSync } from "node:fs";
9
9
  import { basename, dirname, isAbsolute, join, resolve } from "node:path";
@@ -217,7 +217,7 @@ const insertPolyfillHostInCssText = (cssText) => {
217
217
  const _colonHostContextRe = createSupportsRuleRe(":host-context");
218
218
  cssText = cssText.replace(_colonHostContextRe, `$1${_polyfillHostContext}`).replace(_colonHostRe, `$1${_polyfillHost}`).replace(_colonSlottedRe, `$1${_polyfillSlotted}`);
219
219
  supportsBlocks.forEach((originalSelector, index) => {
220
- cssText = cssText.replace(`__supports_${index}__`, originalSelector);
220
+ cssText = cssText.replace(`__supports_${index}__`, () => originalSelector);
221
221
  });
222
222
  return cssText;
223
223
  };
@@ -450,20 +450,20 @@ const scopeCss = (cssText, scopeId, commentOriginalSelector) => {
450
450
  const scoped = scopeCssText(cssText, scopeId, hostScopeId, slotScopeId, commentOriginalSelector);
451
451
  cssText = [scoped.cssText, ...commentsWithHash].join("\n");
452
452
  if (commentOriginalSelector) orgSelectors.forEach(({ placeholder, comment }) => {
453
- cssText = cssText.replace(placeholder, comment);
453
+ cssText = cssText.replace(placeholder, () => comment);
454
454
  });
455
455
  scoped.slottedSelectors.forEach((slottedSelector) => {
456
456
  const regex = new RegExp(escapeRegExpSpecialCharacters(slottedSelector.orgSelector) + "(?=\\s*[,{]|$)", "g");
457
- cssText = cssText.replace(regex, slottedSelector.updatedSelector);
457
+ cssText = cssText.replace(regex, () => slottedSelector.updatedSelector);
458
458
  });
459
459
  cssText = expandPartSelectors(cssText);
460
460
  return cssText;
461
461
  };
462
462
  //#endregion
463
463
  //#region src/version.ts
464
- const version = "5.0.0-rc.14";
465
- const buildId = "1795740246";
466
- const vermoji = "🛩";
464
+ const version = "5.0.0-rc.16";
465
+ const buildId = "1796059047";
466
+ const vermoji = "🏆";
467
467
  /**
468
468
  * Get the installed version of a tool/dependency.
469
469
  * Handles packages with exports maps that point to subdirectories.
@@ -692,6 +692,7 @@ const resetModuleLegacy = (moduleFile) => {
692
692
  * the following are derived from the configuration object:
693
693
  *
694
694
  * - if one of the output targets requires type declaration output then we'll set `declaration: true`
695
+ * - the `rootDir` is the user's tsconfig `compilerOptions.rootDir` when set, otherwise {@link d.Config.rootDir}
695
696
  * - the `outDir` is set to the configured cache directory
696
697
  * - the `sourceMap` and `inlineSources` options are set based on the user's
697
698
  * {@link d.Config.sourceMap} configuration
@@ -707,7 +708,7 @@ const getTsOptionsToExtend = (config) => {
707
708
  module: config.tsCompilerOptions?.module || ts.ModuleKind.ESNext,
708
709
  moduleResolution: config.tsCompilerOptions?.moduleResolution === ts.ModuleResolutionKind.NodeJs ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Bundler,
709
710
  noEmitOnError: config.tsCompilerOptions?.noEmitOnError || false,
710
- rootDir: config.rootDir,
711
+ rootDir: config.tsCompilerOptions?.rootDir ?? config.rootDir,
711
712
  outDir: cacheDir,
712
713
  sourceMap: config.sourceMap,
713
714
  inlineSources: config.sourceMap,
@@ -1411,7 +1412,6 @@ const createCssOnlyComponentMeta = (def) => ({
1411
1412
  hasConnectedCallbackFn: false,
1412
1413
  hasDeserializer: false,
1413
1414
  hasDisconnectedCallbackFn: false,
1414
- hasElement: false,
1415
1415
  hasEvent: false,
1416
1416
  hasLifecycle: false,
1417
1417
  hasListener: false,
@@ -2207,7 +2207,6 @@ const getBuildFeatures = (cmps) => {
2207
2207
  allRenderFn: cmps.every((c) => c.hasRenderFn),
2208
2208
  formAssociated: cmps.some((c) => c.formAssociated),
2209
2209
  deserializer: cmps.some((c) => c.hasDeserializer),
2210
- element: cmps.some((c) => c.hasElement),
2211
2210
  event: cmps.some((c) => c.hasEvent),
2212
2211
  hasRenderFn: cmps.some((c) => c.hasRenderFn),
2213
2212
  lifecycle: cmps.some((c) => c.hasLifecycle),
@@ -2396,6 +2395,91 @@ const updateBuildConditionals = (config, b) => {
2396
2395
  }
2397
2396
  };
2398
2397
  //#endregion
2398
+ //#region src/compiler/output-targets/output-paths.ts
2399
+ /**
2400
+ * Output subdirectory for modules that live outside `srcDir`.
2401
+ */
2402
+ const EXTERNAL_DIR = "_external";
2403
+ /**
2404
+ * String-based (not `path.relative`) so Windows-style paths behave the same on any host.
2405
+ *
2406
+ * @param dir the candidate parent directory
2407
+ * @param filePath the path to test
2408
+ * @returns `filePath` relative to `dir`, or `undefined` when it isn't inside `dir`
2409
+ */
2410
+ const childPath = (dir, filePath) => {
2411
+ const parent = normalizePath(dir, false).replace(/\/$/, "") + "/";
2412
+ const child = normalizePath(filePath, false);
2413
+ return child.startsWith(parent) ? child.slice(parent.length) : void 0;
2414
+ };
2415
+ /**
2416
+ * Path of a source (or source-adjacent) file relative to an output target's directory
2417
+ * (`dist/types`, `dist/collection`, ...).
2418
+ *
2419
+ * Files under `srcDir` keep their `srcDir`-relative layout. Files outside it (e.g. shared
2420
+ * monorepo source reached via the tsconfig `rootDir`) go under {@link EXTERNAL_DIR}, keyed by
2421
+ * their path relative to that `rootDir`, so they can't escape the output directory.
2422
+ *
2423
+ * @param config the Stencil config
2424
+ * @param filePath absolute path of the file
2425
+ * @returns the output-relative path
2426
+ */
2427
+ const getOutputRelativePath = (config, filePath) => {
2428
+ const inSrc = childPath(config.srcDir, filePath);
2429
+ if (inSrc !== void 0) return inSrc;
2430
+ const inBase = childPathOfRoot(config, filePath);
2431
+ return inBase !== void 0 ? join$2(EXTERNAL_DIR, inBase) : relative$1(config.srcDir, filePath);
2432
+ };
2433
+ /**
2434
+ * @param config the Stencil config
2435
+ * @param filePath absolute path of the file
2436
+ * @returns whether {@link getOutputRelativePath} places `filePath` inside the output directory
2437
+ */
2438
+ const isInOutputLayout = (config, filePath) => childPath(config.srcDir, filePath) !== void 0 || childPathOfRoot(config, filePath) !== void 0;
2439
+ const childPathOfRoot = (config, filePath) => {
2440
+ const base = config.tsCompilerOptions?.rootDir ?? config.rootDir;
2441
+ return base ? childPath(base, filePath) : void 0;
2442
+ };
2443
+ /**
2444
+ * Rewrite a path written relative to `sourceFilePath` so it still resolves once both files are
2445
+ * laid out by {@link getOutputRelativePath}. Unchanged unless it crosses the `srcDir` boundary.
2446
+ *
2447
+ * @param config the Stencil config
2448
+ * @param sourceFilePath absolute path of the file the path appears in
2449
+ * @param relPath a path relative to `sourceFilePath`
2450
+ * @returns the output-relative path
2451
+ */
2452
+ const rewriteRelativePath = (config, sourceFilePath, relPath) => {
2453
+ const target = join$2(dirname$1(sourceFilePath), relPath);
2454
+ const fromInSrc = childPath(config.srcDir, sourceFilePath) !== void 0;
2455
+ if (childPath(config.srcDir, target) !== void 0 === fromInSrc) return relPath;
2456
+ const fromOutDir = dirname$1(getOutputRelativePath(config, sourceFilePath));
2457
+ const spec = relative$1(fromOutDir, getOutputRelativePath(config, target));
2458
+ return spec.startsWith(".") ? spec : `./${spec}`;
2459
+ };
2460
+ /**
2461
+ * Rewrite the relative module specifiers in `code` with {@link rewriteRelativePath}.
2462
+ *
2463
+ * @param config the Stencil config
2464
+ * @param sourceFilePath absolute path of the source file `code` was produced from
2465
+ * @param code emitted JS or declaration text
2466
+ * @returns `code` with crossing specifiers rewritten
2467
+ */
2468
+ const rewriteExternalImports = (config, sourceFilePath, code) => {
2469
+ let out = "";
2470
+ let last = 0;
2471
+ for (const { fileName, pos } of ts.preProcessFile(code, true, true).importedFiles) {
2472
+ if (!fileName.startsWith("./") && !fileName.startsWith("../")) continue;
2473
+ const spec = rewriteRelativePath(config, sourceFilePath, fileName);
2474
+ if (spec === fileName) continue;
2475
+ const start = code.indexOf(fileName, pos);
2476
+ if (start < last) continue;
2477
+ out += code.slice(last, start) + spec;
2478
+ last = start + fileName.length;
2479
+ }
2480
+ return last === 0 ? code : out + code.slice(last);
2481
+ };
2482
+ //#endregion
2399
2483
  //#region src/compiler/transformers/core-runtime-apis.ts
2400
2484
  const CREATE_EVENT = "__stencil_createEvent";
2401
2485
  const DEFINE_CUSTOM_ELEMENT = "__stencil_defineCustomElement";
@@ -3024,7 +3108,8 @@ const arrayToArrayLiteral = (list, refs) => {
3024
3108
  /**
3025
3109
  * Convert a JavaScript object (i.e. an object existing at runtime) to the
3026
3110
  * corresponding TypeScript Intermediate Representation (IR) for an object literal.
3027
- * Internal fields (prefixed with _) are excluded from serialization.
3111
+ * The compiler-internal `_astNode` field is excluded from serialization. Other `_`-prefixed keys
3112
+ * are kept: they can be user member names (e.g. `@State() _filters`).
3028
3113
  *
3029
3114
  * @param obj the JavaScript object to convert to TypeScript IR
3030
3115
  * @param refs a set of references to objects, used to avoid circular references
@@ -3033,7 +3118,7 @@ const arrayToArrayLiteral = (list, refs) => {
3033
3118
  const objectToObjectLiteral = (obj, refs) => {
3034
3119
  if (refs.has(obj)) return ts.factory.createIdentifier("undefined");
3035
3120
  refs.add(obj);
3036
- const newProperties = Object.keys(obj).filter((key) => !key.startsWith("_")).map((key) => {
3121
+ const newProperties = Object.keys(obj).filter((key) => key !== "_astNode").map((key) => {
3037
3122
  return ts.factory.createPropertyAssignment(ts.factory.createStringLiteral(key), convertValueToLiteral(obj[key], refs));
3038
3123
  });
3039
3124
  return ts.factory.createObjectLiteralExpression(newProperties, true);
@@ -3918,7 +4003,8 @@ const mapImportsToPathAliases = (config, destinationFilePath, outputTarget) => {
3918
4003
  const isModuleFromNodeModules = module.resolvedModule?.isExternalLibraryImport === true;
3919
4004
  if (hasResolvedFileName && !isModuleFromNodeModules) {
3920
4005
  const extensionRegex = new RegExp(Object.values(ts.Extension).map((extension) => `${extension.replace(".", "\\.")}$`).join("|"));
3921
- const resolvePathInDestination = module.resolvedModule.resolvedFileName.replace(config.srcDir, outputTarget.dir);
4006
+ const { resolvedFileName } = module.resolvedModule;
4007
+ const resolvePathInDestination = isInOutputLayout(config, resolvedFileName) ? join$2(outputTarget.dir, getOutputRelativePath(config, resolvedFileName)) : resolvedFileName;
3922
4008
  importPath = normalizePath(relative$1(dirname$1(destinationFilePath), resolvePathInDestination).replace(extensionRegex, ""));
3923
4009
  importPath = importPath.startsWith(".") ? importPath : "./" + importPath;
3924
4010
  }
@@ -3933,6 +4019,45 @@ const mapImportsToPathAliases = (config, destinationFilePath, outputTarget) => {
3933
4019
  };
3934
4020
  };
3935
4021
  //#endregion
4022
+ //#region src/compiler/output-targets/collection/rewrite-collection-paths.ts
4023
+ const STYLE_URL_GETTERS = /* @__PURE__ */ new Set(["styleUrls", "originalStyleUrls"]);
4024
+ const propName = (name) => ts.isIdentifier(name) || ts.isStringLiteral(name) ? name.text : void 0;
4025
+ const stringProp = (obj, name) => obj.properties.find((p) => ts.isPropertyAssignment(p) && propName(p.name) === name && ts.isStringLiteral(p.initializer));
4026
+ /**
4027
+ * Rewrite the relative paths a collection module's static metadata carries - `styleUrls` /
4028
+ * `originalStyleUrls` entries and `complexType.references[*].path` for imported types - so they
4029
+ * still resolve once modules are laid out by `getOutputRelativePath`.
4030
+ *
4031
+ * @param config the Stencil config
4032
+ * @param sourceFilePath absolute path of the module's source file
4033
+ * @returns a transformer factory
4034
+ */
4035
+ const rewriteCollectionPaths = (config, sourceFilePath) => {
4036
+ return (ctx) => {
4037
+ const { factory } = ctx;
4038
+ const rewrite = (lit) => {
4039
+ const next = rewriteRelativePath(config, sourceFilePath, lit.text);
4040
+ return next === lit.text ? lit : factory.createStringLiteral(next);
4041
+ };
4042
+ const visitStyleUrls = (node) => {
4043
+ if (ts.isArrayLiteralExpression(node)) return factory.updateArrayLiteralExpression(node, node.elements.map((el) => ts.isStringLiteral(el) ? rewrite(el) : el));
4044
+ return ts.visitEachChild(node, visitStyleUrls, ctx);
4045
+ };
4046
+ const visitReference = (ref) => {
4047
+ const path = stringProp(ref, "path");
4048
+ if (stringProp(ref, "location")?.initializer.text !== "import" || !path) return ref;
4049
+ if (!path.initializer.text.startsWith(".")) return ref;
4050
+ return factory.updateObjectLiteralExpression(ref, ref.properties.map((p) => p === path ? factory.updatePropertyAssignment(path, path.name, rewrite(path.initializer)) : p));
4051
+ };
4052
+ const visit = (node) => {
4053
+ if (ts.isGetAccessorDeclaration(node) && STYLE_URL_GETTERS.has(propName(node.name) ?? "")) return ts.visitEachChild(node, visitStyleUrls, ctx);
4054
+ if (ts.isPropertyAssignment(node) && propName(node.name) === "references" && ts.isObjectLiteralExpression(node.initializer)) return factory.updatePropertyAssignment(node, node.name, factory.updateObjectLiteralExpression(node.initializer, node.initializer.properties.map((p) => ts.isPropertyAssignment(p) && ts.isObjectLiteralExpression(p.initializer) ? factory.updatePropertyAssignment(p, p.name, visitReference(p.initializer)) : p)));
4055
+ return ts.visitEachChild(node, visit, ctx);
4056
+ };
4057
+ return (sf) => ts.visitEachChild(sf, visit, ctx);
4058
+ };
4059
+ };
4060
+ //#endregion
3936
4061
  //#region src/compiler/output-targets/collection/index.ts
3937
4062
  /**
3938
4063
  * Main output target function for `collection`.
@@ -3962,16 +4087,17 @@ const outputCollection = async (config, compilerCtx, buildCtx, changedModuleFile
3962
4087
  if (config.preamble) code = `${generatePreamble(config)}\n${code}`;
3963
4088
  const mapCode = mod.sourceMapFileText;
3964
4089
  await Promise.all(outputTargets.map(async (target) => {
3965
- const relPath = relative$1(config.srcDir, mod.jsFilePath);
4090
+ const relPath = getOutputRelativePath(config, mod.jsFilePath);
3966
4091
  const filePath = join$2(target.dir, relPath);
3967
- const { outputText } = ts.transpileModule(code, {
4092
+ const { outputText: aliasedText } = ts.transpileModule(code, {
3968
4093
  fileName: mod.sourceFilePath,
3969
4094
  compilerOptions: { target: ts.ScriptTarget.Latest },
3970
- transformers: { after: [mapImportsToPathAliases(config, filePath, target)] }
4095
+ transformers: { after: [mapImportsToPathAliases(config, filePath, target), rewriteCollectionPaths(config, mod.sourceFilePath)] }
3971
4096
  });
4097
+ const outputText = rewriteExternalImports(config, mod.sourceFilePath, aliasedText);
3972
4098
  await compilerCtx.fs.writeFile(filePath, outputText, { outputTargetType: target.type });
3973
4099
  if (mod.sourceMapPath) {
3974
- const relativeSourceMapPath = relative$1(config.srcDir, mod.sourceMapPath);
4100
+ const relativeSourceMapPath = getOutputRelativePath(config, mod.sourceMapPath);
3975
4101
  const sourceMapOutputFilePath = join$2(target.dir, relativeSourceMapPath);
3976
4102
  await compilerCtx.fs.writeFile(sourceMapOutputFilePath, mapCode, { outputTargetType: target.type });
3977
4103
  }
@@ -4026,8 +4152,8 @@ const serializeCollectionManifest = (config, compilerCtx, buildCtx) => {
4026
4152
  buildFlags.constructableCSS = true;
4027
4153
  buildFlags.cssAnnotations = true;
4028
4154
  const collectionManifest = {
4029
- entries: buildCtx.moduleFiles.filter((mod) => !mod.isCollectionDependency && mod.cmps.length > 0 && (config.devMode || !mod.cmps.some((cmp) => shouldExcludeComponent(cmp.tagName, config.excludeComponents)))).map((mod) => relative$1(config.srcDir, mod.jsFilePath)),
4030
- mixins: buildCtx.moduleFiles.filter((mod) => !mod.isCollectionDependency && mod.hasExportableMixins && mod.cmps.length === 0).map((mod) => relative$1(config.srcDir, mod.jsFilePath)),
4155
+ entries: buildCtx.moduleFiles.filter((mod) => !mod.isCollectionDependency && mod.cmps.length > 0 && (config.devMode || !mod.cmps.some((cmp) => shouldExcludeComponent(cmp.tagName, config.excludeComponents)))).map((mod) => getOutputRelativePath(config, mod.jsFilePath)),
4156
+ mixins: buildCtx.moduleFiles.filter((mod) => !mod.isCollectionDependency && mod.hasExportableMixins && mod.cmps.length === 0).map((mod) => getOutputRelativePath(config, mod.jsFilePath)),
4031
4157
  compiler: {
4032
4158
  name: "@stencil/core",
4033
4159
  version,
@@ -4039,7 +4165,7 @@ const serializeCollectionManifest = (config, compilerCtx, buildCtx) => {
4039
4165
  };
4040
4166
  if (config.globalScript) {
4041
4167
  const mod = compilerCtx.moduleMap.get(normalizePath(config.globalScript));
4042
- if (mod) collectionManifest.global = relative$1(config.srcDir, mod.jsFilePath);
4168
+ if (mod) collectionManifest.global = getOutputRelativePath(config, mod.jsFilePath);
4043
4169
  }
4044
4170
  return collectionManifest;
4045
4171
  };
@@ -5539,7 +5665,7 @@ const extTransformsPlugin = (config, compilerCtx, buildCtx) => {
5539
5665
  cmp = buildCtx.components.find((c) => c.tagName === data.tag);
5540
5666
  if (cmp && !cmp.isCollectionDependency && compilerCtx.moduleMap.get(cmp.sourceFilePath)) {
5541
5667
  const collectionDirs = config.outputTargets.filter(isOutputTargetCollection);
5542
- const relPath = relative$1(config.srcDir, cacheEntry.pluginTransformId);
5668
+ const relPath = getOutputRelativePath(config, cacheEntry.pluginTransformId);
5543
5669
  await Promise.all(collectionDirs.map(async (outputTarget) => {
5544
5670
  const collectionPath = join$2(outputTarget.dir, relPath);
5545
5671
  await compilerCtx.fs.writeFile(collectionPath, cacheEntry.pluginTransformCode);
@@ -5623,7 +5749,7 @@ const fileLoadPlugin = (fs) => {
5623
5749
  const base = normalizeFsPath(idBase);
5624
5750
  candidates.push(base, ...RESOLVE_EXTENSIONS.map((ext) => base + ext));
5625
5751
  } else if (idBase.startsWith(".") && importer) {
5626
- const base = join$1(dirname$1(normalizeFsPath(importer)), idBase);
5752
+ const base = normalizePath(join$1(dirname$1(normalizeFsPath(importer)), idBase));
5627
5753
  candidates.push(base, ...RESOLVE_EXTENSIONS.map((ext) => base + ext));
5628
5754
  }
5629
5755
  for (const p of candidates) if (fs.statSync(p)?.isFile) return { id: p + query };
@@ -8698,7 +8824,8 @@ const getLazyEntry = (isBrowser, assetPath, externalRuntime = false) => {
8698
8824
  const platformExports = [
8699
8825
  "setNonce",
8700
8826
  "setRegistry",
8701
- "setTagTransformer"
8827
+ "setTagTransformer",
8828
+ "transformTag"
8702
8829
  ];
8703
8830
  if (assetPath) platformExports.push("setAssetPath");
8704
8831
  s.append(`export { ${platformExports.join(", ")} } from '${STENCIL_CORE_ID}';\n`);
@@ -11708,6 +11835,7 @@ const generateAppTypes = async (config, compilerCtx, buildCtx, destination) => {
11708
11835
  let componentTypesFileContent = generateComponentTypesFile([...buildCtx.components.filter((m) => !m.isCollectionDependency), ...buildCtx.cssOnlyComponents], config, areTypesInternal);
11709
11836
  let componentsDtsFilePath = getComponentsDtsSrcFilePath(config);
11710
11837
  if (!areTypesInternal) {
11838
+ componentTypesFileContent = rewriteExternalImports(config, componentsDtsFilePath, componentTypesFileContent);
11711
11839
  componentsDtsFilePath = resolve$2(destination, GENERATED_DTS);
11712
11840
  componentTypesFileContent = updateStencilTypesImports(destination, componentsDtsFilePath, componentTypesFileContent);
11713
11841
  }
@@ -11868,7 +11996,7 @@ const generateTypesOutput = async (config, compilerCtx, buildCtx, outputTarget)
11868
11996
  const relPath = relative$1(config.srcDir, srcDtsFile.absPath);
11869
11997
  const distPath = join$2(outputTarget.dir, relPath);
11870
11998
  const originalDtsContent = await compilerCtx.fs.readFile(srcDtsFile.absPath);
11871
- const distDtsContent = updateStencilTypesImports(outputTarget.dir, distPath, originalDtsContent);
11999
+ const distDtsContent = updateStencilTypesImports(outputTarget.dir, distPath, rewriteExternalImports(config, srcDtsFile.absPath, originalDtsContent));
11872
12000
  await compilerCtx.fs.writeFile(distPath, distDtsContent);
11873
12001
  return distPath;
11874
12002
  }))).slice(-1)[0];
@@ -11924,6 +12052,12 @@ export type TagTransformer = (tag: string) => string;
11924
12052
  * Useful for namespacing (e.g. \`my-button\` → \`acme-button\`) in multi-library pages.
11925
12053
  */
11926
12054
  export declare function setTagTransformer(transformer: TagTransformer): void;
12055
+
12056
+ /**
12057
+ * Pass a tag name through the installed tag transformer (returns it unchanged if none is set).
12058
+ * Useful for framework wrappers and imperative code that creates components by tag name.
12059
+ */
12060
+ export declare function transformTag(tag: string): string;
11927
12061
  ${hasAssets ? `
11928
12062
  /**
11929
12063
  * Used to manually set the base path where component assets can be found. The
@@ -11975,6 +12109,12 @@ export type TagTransformer = (tag: string) => string;
11975
12109
  */
11976
12110
  export declare const setTagTransformer: (transformer: TagTransformer) => void;
11977
12111
 
12112
+ /**
12113
+ * Pass a tag name through the installed tag transformer (returns it unchanged if none is set).
12114
+ * Useful for framework wrappers and imperative code that creates components by tag name.
12115
+ */
12116
+ export declare const transformTag: (tag: string) => string;
12117
+
11978
12118
  export interface SetPlatformOptions {
11979
12119
  raf?: (c: FrameRequestCallback) => number;
11980
12120
  ael?: (el: EventTarget, eventName: string, listener: EventListenerOrEventListenerObject, options: boolean | AddEventListenerOptions) => void;
@@ -12732,6 +12872,8 @@ var $nativeSetTimeout = (typeof globalThis !== 'undefined' ? globalThis : global
12732
12872
  var $nativeClearTimeout = (typeof globalThis !== 'undefined' ? globalThis : global).clearTimeout;
12733
12873
  // Holds the \`ssrProp()\` registry, which template code writes to outside the factory.
12734
12874
  var $stencilNativeGlobal = typeof globalThis !== 'undefined' ? globalThis : global;
12875
+ // Server-side rewrites of component styles (scoped CSS, ::part expansion), keyed by style text.
12876
+ var $stencilSsrCssCache = new Map();
12735
12877
  // Used to abort in-flight fetch() calls and to call any user defined AbortControllers when ssr times out.
12736
12878
  var $stencilNativeAbortController = AbortController;
12737
12879
 
@@ -13846,8 +13988,8 @@ const defineCustomElement = (tsSourceFile, moduleFile, transformOpts) => {
13846
13988
  return ts.factory.updateSourceFile(tsSourceFile, statements);
13847
13989
  };
13848
13990
  const addDefineCustomElement = (moduleFile, compilerMeta) => {
13849
- if (compilerMeta.isPlain) return ts.factory.createExpressionStatement(ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("customElements"), ts.factory.createIdentifier("define")), [], [ts.factory.createCallExpression(ts.factory.createIdentifier(TRANSFORM_TAG), [], [ts.factory.createStringLiteral(compilerMeta.tagName)]), ts.factory.createIdentifier(compilerMeta.componentClassName)]));
13850
13991
  addCoreRuntimeApi(moduleFile, RUNTIME_APIS.transformTag);
13992
+ if (compilerMeta.isPlain) return ts.factory.createExpressionStatement(ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("customElements"), ts.factory.createIdentifier("define")), [], [ts.factory.createCallExpression(ts.factory.createIdentifier(TRANSFORM_TAG), [], [ts.factory.createStringLiteral(compilerMeta.tagName)]), ts.factory.createIdentifier(compilerMeta.componentClassName)]));
13851
13993
  addCoreRuntimeApi(moduleFile, RUNTIME_APIS.defineCustomElement);
13852
13994
  const compactMeta = formatComponentRuntimeMeta(compilerMeta, true);
13853
13995
  const liternalCmpClassName = ts.factory.createIdentifier(compilerMeta.componentClassName);
@@ -14293,7 +14435,7 @@ const generateLoaderModule = (components, outputTarget, relativeAssetPath) => {
14293
14435
  import { transformTag, getRegistry } from '${STENCIL_INTERNAL_STANDALONE_CLIENT_PLATFORM_ID}';
14294
14436
  // The same platform setters as the output's index.js. With \`autoStart: false\`, call them before
14295
14437
  // start() - e.g. setRegistry() for a scoped registry - without importing every component.
14296
- export { setNonce, setRegistry, setTagTransformer, setPlatformOptions } from '${STENCIL_INTERNAL_STANDALONE_CLIENT_PLATFORM_ID}';
14438
+ export { setNonce, setRegistry, setTagTransformer, transformTag, setPlatformOptions } from '${STENCIL_INTERNAL_STANDALONE_CLIENT_PLATFORM_ID}';
14297
14439
  ${assetPathImport}${assetPathInit}
14298
14440
 
14299
14441
  /**
@@ -14688,7 +14830,7 @@ const generateEntryPoint = (outputTarget, cmpImports = [], cmpExports = [], cmpN
14688
14830
  const body = [];
14689
14831
  const imports = [];
14690
14832
  const exports = [];
14691
- exports.push(`export { setNonce, setRegistry, setTagTransformer, setPlatformOptions } from '${STENCIL_INTERNAL_STANDALONE_CLIENT_PLATFORM_ID}';`, `export * from '${USER_INDEX_ENTRY_ID}';`);
14833
+ exports.push(`export { setNonce, setRegistry, setTagTransformer, transformTag, setPlatformOptions } from '${STENCIL_INTERNAL_STANDALONE_CLIENT_PLATFORM_ID}';`, `export * from '${USER_INDEX_ENTRY_ID}';`);
14692
14834
  if (relativeAssetPath) {
14693
14835
  imports.push(`import { setAssetPath } from '${STENCIL_INTERNAL_STANDALONE_CLIENT_PLATFORM_ID}';`);
14694
14836
  exports.push(`export { setAssetPath };`);
@@ -15184,7 +15326,7 @@ const setComponentBuildConditionals = (cmpMeta) => {
15184
15326
  cmpMeta.hasListenerTargetBody = cmpMeta.listeners.some((l) => l.target === "body");
15185
15327
  cmpMeta.hasListenerTarget = cmpMeta.listeners.some((l) => !!l.target);
15186
15328
  }
15187
- cmpMeta.hasMember = cmpMeta.hasProp || cmpMeta.hasState || cmpMeta.hasElement || cmpMeta.hasMethod || cmpMeta.formAssociated;
15329
+ cmpMeta.hasMember = cmpMeta.hasProp || cmpMeta.hasState || cmpMeta.hasMethod || cmpMeta.formAssociated;
15188
15330
  cmpMeta.isUpdateable = cmpMeta.hasProp || cmpMeta.hasState;
15189
15331
  if (cmpMeta.styles.length > 0) {
15190
15332
  cmpMeta.hasStyle = true;
@@ -15834,6 +15976,14 @@ const MEMBER_DECORATORS_TO_REMOVE = [
15834
15976
  ];
15835
15977
  //#endregion
15836
15978
  //#region src/compiler/transformers/decorators-to-static/element-decorator.ts
15979
+ /**
15980
+ * Adds a static `elementRef` getter for an `@Element()` field.
15981
+ * @param diagnostics for surfacing errors
15982
+ * @param decoratedMembers the class's decorated members
15983
+ * @param newMembers out param: the class's members, receiving the static getter
15984
+ * @param decoratorName the local name `Element` is imported as
15985
+ * @returns the names of the `@Element()` fields
15986
+ */
15837
15987
  const elementDecoratorsToStatic = (diagnostics, decoratedMembers, newMembers, decoratorName) => {
15838
15988
  const elementRefs = decoratedMembers.filter(ts.isPropertyDeclaration).map((prop) => parseElementDecorator(prop, decoratorName)).filter((element) => !!element);
15839
15989
  if (elementRefs.length > 0) {
@@ -15843,6 +15993,7 @@ const elementDecoratorsToStatic = (diagnostics, decoratedMembers, newMembers, de
15843
15993
  error.messageText = `It's not valid to add more than one Element() decorator`;
15844
15994
  }
15845
15995
  }
15996
+ return elementRefs;
15846
15997
  };
15847
15998
  const parseElementDecorator = (prop, decoratorName) => {
15848
15999
  if (retrieveTsDecorators(prop)?.find(isDecoratorNamed(decoratorName)) == null) return null;
@@ -16346,9 +16497,15 @@ const listenDecoratorsToStatic = (diagnostics, typeChecker, decoratedMembers, ne
16346
16497
  const parseListenDecorators = (diagnostics, typeChecker, method, decoratorName) => {
16347
16498
  const listenDecorators = (retrieveTsDecorators(method) ?? []).filter(isDecoratorNamed(decoratorName));
16348
16499
  if (listenDecorators.length === 0) return [];
16349
- return listenDecorators.map((listenDecorator) => {
16500
+ return listenDecorators.flatMap((listenDecorator) => {
16350
16501
  const methodName = method.name.getText();
16351
16502
  const [listenText, listenOptions] = getDecoratorParameters(listenDecorator, typeChecker, diagnostics);
16503
+ if (typeof listenText !== "string") {
16504
+ const err = buildError(diagnostics);
16505
+ err.messageText = `@Listen() expects an event name as a string, received ${JSON.stringify(listenText)}.`;
16506
+ augmentDiagnosticWithNode(err, listenDecorator);
16507
+ return [];
16508
+ }
16352
16509
  const eventNames = listenText.split(",");
16353
16510
  if (eventNames.length > 1) {
16354
16511
  const err = buildError(diagnostics);
@@ -17181,16 +17338,66 @@ const stateDecoratorToStatic = (prop, typeChecker, decoratorName) => {
17181
17338
  return ts.factory.createPropertyAssignment(ts.factory.createStringLiteral(stateName), convertValueToLiteral(meta));
17182
17339
  };
17183
17340
  //#endregion
17341
+ //#region src/compiler/transformers/decorators-to-static/validate-computed-names.ts
17342
+ /** Decorators whose member may have a computed name that resolves to a literal at compile time. */
17343
+ const RESOLVED_COMPUTED_NAME = [
17344
+ "Prop",
17345
+ "State",
17346
+ "AttachInternals"
17347
+ ];
17348
+ /** Decorators whose member must have a plain name. */
17349
+ const NO_COMPUTED_NAME = [
17350
+ "Element",
17351
+ "Event",
17352
+ "Listen",
17353
+ "Method",
17354
+ "Watch"
17355
+ ];
17356
+ /**
17357
+ * Reports Stencil-decorated members whose computed name Stencil can't use.
17358
+ * @param diagnostics for surfacing errors
17359
+ * @param typeChecker used to resolve a computed name to a literal
17360
+ * @param decoratedMembers the class's decorated members
17361
+ * @param importAliasMap local names of the Stencil decorators
17362
+ */
17363
+ const validateComputedMemberNames = (diagnostics, typeChecker, decoratedMembers, importAliasMap) => {
17364
+ for (const member of decoratedMembers) {
17365
+ const name = member.name;
17366
+ if (!name || !ts.isComputedPropertyName(name)) continue;
17367
+ const decorators = retrieveTsDecorators(member) ?? [];
17368
+ const uses = (list) => list.find((dec) => decorators.some(isDecoratorNamed(importAliasMap.get(dec))));
17369
+ const unsupported = uses(NO_COMPUTED_NAME);
17370
+ if (unsupported) {
17371
+ const err = buildError(diagnostics);
17372
+ err.messageText = `@${unsupported}() does not support a computed member name (\`${name.getText()}\`). Use a plain name.`;
17373
+ augmentDiagnosticWithNode(err, name);
17374
+ continue;
17375
+ }
17376
+ const resolved = uses(RESOLVED_COMPUTED_NAME);
17377
+ if (resolved && !typeChecker.getTypeAtLocation(name.expression)?.isLiteral()) {
17378
+ const err = buildError(diagnostics);
17379
+ err.messageText = `The computed name \`${name.getText()}\` of this @${resolved}() can't be resolved at compile time. Use a \`const\` string or enum member.`;
17380
+ augmentDiagnosticWithNode(err, name);
17381
+ }
17382
+ }
17383
+ };
17384
+ //#endregion
17184
17385
  //#region src/compiler/transformers/decorators-to-static/watch-decorator.ts
17185
- const watchDecoratorsToStatic = (typeChecker, decoratedProps, newMembers, decoratorName) => {
17186
- const watchers = decoratedProps.filter(ts.isMethodDeclaration).map((method) => parseWatchDecorator(typeChecker, method, decoratorName));
17386
+ const watchDecoratorsToStatic = (diagnostics, typeChecker, decoratedProps, newMembers, decoratorName) => {
17387
+ const watchers = decoratedProps.filter(ts.isMethodDeclaration).map((method) => parseWatchDecorator(diagnostics, typeChecker, method, decoratorName));
17187
17388
  const flatWatchers = flatOne(watchers);
17188
17389
  if (flatWatchers.length > 0) newMembers.push(createStaticGetter("watchers", convertValueToLiteral(flatWatchers)));
17189
17390
  };
17190
- const parseWatchDecorator = (typeChecker, method, decoratorName) => {
17391
+ const parseWatchDecorator = (diagnostics, typeChecker, method, decoratorName) => {
17191
17392
  const methodName = method.name.getText();
17192
- return (retrieveTsDecorators(method) ?? []).filter(isDecoratorNamed(decoratorName)).map((decorator) => {
17393
+ return (retrieveTsDecorators(method) ?? []).filter(isDecoratorNamed(decoratorName)).flatMap((decorator) => {
17193
17394
  const [propName, handlerOptions] = getDecoratorParameters(decorator, typeChecker);
17395
+ if (typeof propName !== "string") {
17396
+ const err = buildError(diagnostics);
17397
+ err.messageText = `@Watch() expects the name of a member as a string, received ${JSON.stringify(propName)}.`;
17398
+ augmentDiagnosticWithNode(err, decorator);
17399
+ return [];
17400
+ }
17194
17401
  if (handlerOptions) return {
17195
17402
  propName,
17196
17403
  methodName,
@@ -17229,7 +17436,17 @@ const convertDecoratorsToStatic = (config, diagnostics, typeChecker, program, in
17229
17436
  return (transformCtx) => {
17230
17437
  let sourceFile;
17231
17438
  const visit = (node) => {
17232
- if (ts.isClassDeclaration(node) || includeClassExpressions && ts.isClassExpression(node)) return visitClassDeclaration(config, diagnostics, typeChecker, program, node, sourceFile);
17439
+ if (ts.isClassDeclaration(node) || includeClassExpressions && ts.isClassExpression(node)) try {
17440
+ return visitClassDeclaration(config, diagnostics, typeChecker, program, node, sourceFile);
17441
+ } catch (e) {
17442
+ const message = e instanceof Error ? e.message : String(e);
17443
+ if (!diagnostics.some((d) => d.messageText === message)) {
17444
+ const err = buildError(diagnostics);
17445
+ err.messageText = message;
17446
+ augmentDiagnosticWithNode(err, node.name ?? node);
17447
+ }
17448
+ return node;
17449
+ }
17233
17450
  return ts.visitEachChild(node, visit, transformCtx);
17234
17451
  };
17235
17452
  return (tsSourceFile) => {
@@ -17273,6 +17490,7 @@ const visitClassDeclaration = (config, diagnostics, typeChecker, program, classN
17273
17490
  const filteredMethodsAndFields = removeStencilMethodDecorators(Array.from(classMembers), diagnostics, importAliasMap);
17274
17491
  if (componentDecorator && ts.isClassDeclaration(classNode)) componentDecoratorToStatic(config, typeChecker, diagnostics, classNode, filteredMethodsAndFields, componentDecorator);
17275
17492
  if (decoratedMembers.length > 0) {
17493
+ validateComputedMemberNames(diagnostics, typeChecker, decoratedMembers, importAliasMap);
17276
17494
  const handWritten = serializeDecoratorsToStatic(typeChecker, decoratedMembers, [], importAliasMap.get("PropSerialize"), "PropSerialize", importAliasMap.get("Prop")).concat(serializeDecoratorsToStatic(typeChecker, decoratedMembers, [], importAliasMap.get("AttrDeserialize"), "AttrDeserialize", importAliasMap.get("Prop")));
17277
17495
  const jsonProps = getJsonSerializedProps(diagnostics, typeChecker, decoratedMembers, importAliasMap.get("Prop"), handWritten);
17278
17496
  if (jsonProps.length > 0) {
@@ -17291,8 +17509,9 @@ const visitClassDeclaration = (config, diagnostics, typeChecker, program, classN
17291
17509
  stateDecoratorsToStatic(decoratedMembers, filteredMethodsAndFields, typeChecker, importAliasMap.get("State"));
17292
17510
  eventDecoratorsToStatic(config, diagnostics, decoratedMembers, typeChecker, program, filteredMethodsAndFields, importAliasMap.get("Event"));
17293
17511
  methodDecoratorsToStatic(config, diagnostics, classNode, decoratedMembers, typeChecker, program, filteredMethodsAndFields, importAliasMap.get("Method"));
17294
- elementDecoratorsToStatic(diagnostics, decoratedMembers, filteredMethodsAndFields, importAliasMap.get("Element"));
17295
- watchDecoratorsToStatic(typeChecker, decoratedMembers, filteredMethodsAndFields, importAliasMap.get("Watch"));
17512
+ const elementRefs = elementDecoratorsToStatic(diagnostics, decoratedMembers, filteredMethodsAndFields, importAliasMap.get("Element"));
17513
+ if (!componentDecorator && elementRefs.length > 0) removeFields(filteredMethodsAndFields, elementRefs);
17514
+ watchDecoratorsToStatic(diagnostics, typeChecker, decoratedMembers, filteredMethodsAndFields, importAliasMap.get("Watch"));
17296
17515
  listenDecoratorsToStatic(diagnostics, typeChecker, decoratedMembers, filteredMethodsAndFields, importAliasMap.get("Listen"));
17297
17516
  attachInternalsDecoratorsToStatic(diagnostics, decoratedMembers, filteredMethodsAndFields, typeChecker, importAliasMap.get("AttachInternals"));
17298
17517
  }
@@ -17303,6 +17522,17 @@ const visitClassDeclaration = (config, diagnostics, typeChecker, program, classN
17303
17522
  return ts.isClassDeclaration(classNode) ? ts.factory.updateClassDeclaration(classNode, updatedModifiers, classNode.name, classNode.typeParameters, classNode.heritageClauses, updatedClassFields) : ts.factory.updateClassExpression(classNode, updatedModifiers, classNode.name, classNode.typeParameters, classNode.heritageClauses, updatedClassFields);
17304
17523
  };
17305
17524
  /**
17525
+ * Removes the property declarations with the given names, in place.
17526
+ * @param members the class members to filter
17527
+ * @param names the property names to remove
17528
+ */
17529
+ const removeFields = (members, names) => {
17530
+ for (let i = members.length - 1; i >= 0; i--) {
17531
+ const m = members[i];
17532
+ if (ts.isPropertyDeclaration(m) && names.includes(m.name.getText())) members.splice(i, 1);
17533
+ }
17534
+ };
17535
+ /**
17306
17536
  * Take a list of `ClassElement` AST nodes and remove any decorators from
17307
17537
  * method elements which are Stencil-specific decorators. We implement the
17308
17538
  * intended behavior for these Stencil-specific decorators (things like
@@ -17363,6 +17593,13 @@ const filterDecorators = (decorators, excludeList) => {
17363
17593
  return decorators;
17364
17594
  };
17365
17595
  //#endregion
17596
+ //#region src/compiler/transformers/static-to-meta/element-ref.ts
17597
+ const parseStaticElementRef = (staticMembers) => {
17598
+ const parsedElementRef = getStaticValue(staticMembers, "elementRef");
17599
+ if (typeof parsedElementRef === "string") return parsedElementRef;
17600
+ return null;
17601
+ };
17602
+ //#endregion
17366
17603
  //#region src/compiler/transformers/static-to-meta/events.ts
17367
17604
  const parseStaticEvents = (staticMembers) => {
17368
17605
  const parsedEvents = getStaticValue(staticMembers, "events");
@@ -18078,6 +18315,7 @@ function mergeExtendedClassMeta(compilerCtx, typeChecker, buildCtx, cmpNode, sta
18078
18315
  let classMethods = cmpNode.members.filter(ts.isMethodDeclaration).map((m) => ts.isIdentifier(m.name) ? m.name.text : "").filter(Boolean);
18079
18316
  let serializers = parseStaticSerializers(staticMembers, "serializers");
18080
18317
  let deserializers = parseStaticSerializers(staticMembers, "deserializers");
18318
+ let elementRef = parseStaticElementRef(staticMembers);
18081
18319
  tree.forEach((extendedClass) => {
18082
18320
  const extendedStaticMembers = extendedClass.classNode.members.filter(isStaticGetter);
18083
18321
  const mixinProps = reanchorInheritedTypeReferences(parseStaticProps(extendedStaticMembers) ?? [], extendedClass.fileName, moduleFile.sourceFilePath);
@@ -18109,6 +18347,7 @@ function mergeExtendedClassMeta(compilerCtx, typeChecker, buildCtx, cmpNode, sta
18109
18347
  serializers = [...deDupeMembers(parseStaticSerializers(extendedStaticMembers, "serializers") ?? [], serializers), ...serializers];
18110
18348
  deserializers = [...deDupeMembers(parseStaticSerializers(extendedStaticMembers, "deserializers") ?? [], deserializers), ...deserializers];
18111
18349
  classMethods = [...classMethods, ...extendedClass.classNode.members.filter(ts.isMethodDeclaration).map((m) => ts.isIdentifier(m.name) ? m.name.text : "").filter(Boolean)];
18350
+ elementRef ??= parseStaticElementRef(extendedStaticMembers);
18112
18351
  if (isMixin) hasMixin = true;
18113
18352
  });
18114
18353
  return {
@@ -18122,7 +18361,8 @@ function mergeExtendedClassMeta(compilerCtx, typeChecker, buildCtx, cmpNode, sta
18122
18361
  watchers,
18123
18362
  classMethods,
18124
18363
  serializers,
18125
- deserializers
18364
+ deserializers,
18365
+ elementRef
18126
18366
  };
18127
18367
  }
18128
18368
  //#endregion
@@ -18178,7 +18418,8 @@ function extractInheritedMetaFromClass(classDecl) {
18178
18418
  "events",
18179
18419
  "listeners",
18180
18420
  "watchers",
18181
- "methods"
18421
+ "methods",
18422
+ "elementRef"
18182
18423
  ].includes(m.name.text))) return {
18183
18424
  properties: parseStaticProps(staticMembers),
18184
18425
  states: parseStaticStates(staticMembers),
@@ -18186,6 +18427,7 @@ function extractInheritedMetaFromClass(classDecl) {
18186
18427
  events: parseStaticEvents(staticMembers),
18187
18428
  listeners: parseStaticListeners(staticMembers),
18188
18429
  watchers: parseStaticWatchers(staticMembers),
18430
+ elementRef: parseStaticElementRef(staticMembers),
18189
18431
  methodNames
18190
18432
  };
18191
18433
  const properties = [];
@@ -18194,6 +18436,7 @@ function extractInheritedMetaFromClass(classDecl) {
18194
18436
  const events = [];
18195
18437
  const listeners = [];
18196
18438
  const watchers = [];
18439
+ let elementRef = null;
18197
18440
  for (const member of classDecl.members) {
18198
18441
  if (!ts.isPropertyDeclaration(member) && !ts.isMethodDeclaration(member)) continue;
18199
18442
  if (!ts.isIdentifier(member.name)) continue;
@@ -18219,7 +18462,8 @@ function extractInheritedMetaFromClass(classDecl) {
18219
18462
  getter: false,
18220
18463
  setter: false
18221
18464
  });
18222
- } else if (decName === "State" && ts.isPropertyDeclaration(member)) states.push({ name: memberName });
18465
+ } else if (decName === "Element" && ts.isPropertyDeclaration(member)) elementRef ??= memberName;
18466
+ else if (decName === "State" && ts.isPropertyDeclaration(member)) states.push({ name: memberName });
18223
18467
  else if (decName === "Event" && ts.isPropertyDeclaration(member)) {
18224
18468
  const opts = extractDecoratorOptions(args[0]);
18225
18469
  events.push({
@@ -18266,6 +18510,7 @@ function extractInheritedMetaFromClass(classDecl) {
18266
18510
  events,
18267
18511
  listeners,
18268
18512
  watchers,
18513
+ elementRef,
18269
18514
  methodNames
18270
18515
  };
18271
18516
  }
@@ -18505,7 +18750,8 @@ function extractAncestorMeta(ancestor, cmpSourceFile, resolveImport, config) {
18505
18750
  "watchers",
18506
18751
  "serializers",
18507
18752
  "deserializers",
18508
- "methods"
18753
+ "methods",
18754
+ "elementRef"
18509
18755
  ].includes(m.name.text));
18510
18756
  if (!hasUsableStaticMembers && className) {
18511
18757
  const converted = convertInMemorySourceDecorators(parentSf, config);
@@ -18526,6 +18772,7 @@ function extractAncestorMeta(ancestor, cmpSourceFile, resolveImport, config) {
18526
18772
  watchers: parseStaticWatchers(resolvedStaticMembers) ?? [],
18527
18773
  serializers: parseStaticSerializers(resolvedStaticMembers, "serializers") ?? [],
18528
18774
  deserializers: parseStaticSerializers(resolvedStaticMembers, "deserializers") ?? [],
18775
+ elementRef: parseStaticElementRef(resolvedStaticMembers),
18529
18776
  methodNames: resolvedClassNode.members.filter(ts.isMethodDeclaration).map((m) => ts.isIdentifier(m.name) ? m.name.text : "").filter(Boolean)
18530
18777
  };
18531
18778
  }
@@ -18557,6 +18804,7 @@ function mergeExtendedClassMetaWithResolveImport(cmpNode, staticMembers, sourceF
18557
18804
  let classMethods = cmpNode.members.filter(ts.isMethodDeclaration).map((m) => ts.isIdentifier(m.name) ? m.name.text : "").filter(Boolean);
18558
18805
  let serializers = parseStaticSerializers(staticMembers, "serializers");
18559
18806
  let deserializers = parseStaticSerializers(staticMembers, "deserializers");
18807
+ let elementRef = parseStaticElementRef(staticMembers);
18560
18808
  const ancestors = [];
18561
18809
  resolveAncestors(cmpNode, sourceFile, sourceFile.fileName, resolveImport, /* @__PURE__ */ new Set(), ancestors, cmpNode, buildCtx);
18562
18810
  ancestors.forEach((ancestor) => {
@@ -18573,6 +18821,7 @@ function mergeExtendedClassMetaWithResolveImport(cmpNode, staticMembers, sourceF
18573
18821
  serializers = [...deDupeMembers(parentMeta.serializers ?? [], serializers), ...serializers];
18574
18822
  deserializers = [...deDupeMembers(parentMeta.deserializers ?? [], deserializers), ...deserializers];
18575
18823
  classMethods = [...classMethods, ...parentMeta.methodNames];
18824
+ elementRef ??= parentMeta.elementRef;
18576
18825
  });
18577
18826
  return {
18578
18827
  doesExtend,
@@ -18584,7 +18833,8 @@ function mergeExtendedClassMetaWithResolveImport(cmpNode, staticMembers, sourceF
18584
18833
  watchers,
18585
18834
  classMethods,
18586
18835
  serializers,
18587
- deserializers
18836
+ deserializers,
18837
+ elementRef
18588
18838
  };
18589
18839
  }
18590
18840
  //#endregion
@@ -18605,13 +18855,6 @@ const parseClassMethods = (classMethods, cmpMeta) => {
18605
18855
  cmpMeta.hasRenderFn = classMethods.includes("render");
18606
18856
  };
18607
18857
  //#endregion
18608
- //#region src/compiler/transformers/static-to-meta/element-ref.ts
18609
- const parseStaticElementRef = (staticMembers) => {
18610
- const parsedElementRef = getStaticValue(staticMembers, "elementRef");
18611
- if (typeof parsedElementRef === "string") return parsedElementRef;
18612
- return null;
18613
- };
18614
- //#endregion
18615
18858
  //#region src/compiler/transformers/static-to-meta/encapsulation.ts
18616
18859
  /**
18617
18860
  * Find and return the type of encapsulation that a component has based on the return value of its static getter of the
@@ -18891,7 +19134,7 @@ const parseStaticComponentMeta = (compilerCtx, typeChecker, cmpNode, moduleFile,
18891
19134
  const staticMembers = cmpNode.members.filter(isStaticGetter);
18892
19135
  const tagName = getComponentTagName(staticMembers);
18893
19136
  if (tagName == null) return cmpNode;
18894
- const { doesExtend, properties, states, methods, listeners, events, watchers, classMethods, serializers, deserializers } = transformOpts?.resolveImport ? mergeExtendedClassMetaWithResolveImport(cmpNode, staticMembers, moduleFile.staticSourceFile, transformOpts.resolveImport, buildCtx.config, buildCtx) : mergeExtendedClassMeta(compilerCtx, typeChecker, buildCtx, cmpNode, staticMembers, moduleFile);
19137
+ const { doesExtend, properties, states, methods, listeners, events, watchers, classMethods, serializers, deserializers, elementRef } = transformOpts?.resolveImport ? mergeExtendedClassMetaWithResolveImport(cmpNode, staticMembers, moduleFile.staticSourceFile, transformOpts.resolveImport, buildCtx.config, buildCtx) : mergeExtendedClassMeta(compilerCtx, typeChecker, buildCtx, cmpNode, staticMembers, moduleFile);
18895
19138
  const symbol = typeChecker ? typeChecker.getSymbolAtLocation(cmpNode.name) : void 0;
18896
19139
  const docs = serializeSymbol(typeChecker, symbol);
18897
19140
  const isCollectionDependency = moduleFile.isCollectionDependency;
@@ -18904,7 +19147,7 @@ const parseStaticComponentMeta = (compilerCtx, typeChecker, cmpNode, moduleFile,
18904
19147
  excludeFromCollection: moduleFile.excludeFromCollection,
18905
19148
  isCollectionDependency,
18906
19149
  componentClassName: cmpNode.name ? cmpNode.name.text : "",
18907
- elementRef: parseStaticElementRef(staticMembers),
19150
+ elementRef,
18908
19151
  encapsulation,
18909
19152
  shadowDelegatesFocus: !!parseStaticShadowDelegatesFocus(encapsulation, staticMembers),
18910
19153
  shadowClonable: !!parseStaticShadowClonable(encapsulation, staticMembers),
@@ -18943,7 +19186,6 @@ const parseStaticComponentMeta = (compilerCtx, typeChecker, cmpNode, moduleFile,
18943
19186
  hasConnectedCallbackFn: false,
18944
19187
  hasDeserializer: false,
18945
19188
  hasDisconnectedCallbackFn: false,
18946
- hasElement: false,
18947
19189
  hasEvent: false,
18948
19190
  hasLifecycle: false,
18949
19191
  hasListener: false,
@@ -19661,6 +19903,20 @@ const applyDevModeRelaxation = (config, diags) => {
19661
19903
  });
19662
19904
  };
19663
19905
  /**
19906
+ * Whether to report semantic diagnostics for a file in the TS program: files in `srcDir`, plus
19907
+ * files outside the project root (e.g. shared monorepo source reached via the tsconfig `rootDir`).
19908
+ *
19909
+ * @param config - the validated Stencil configuration
19910
+ * @param fileName - the source file's path
19911
+ * @returns `true` if the file's type errors should be reported
19912
+ */
19913
+ const isTypeCheckedFile = (config, fileName) => {
19914
+ const file = normalizePath(fileName);
19915
+ if (file.includes("node_modules") || file.endsWith(".d.ts")) return false;
19916
+ const rootDir = normalizePath(config.rootDir).replace(/\/$/, "");
19917
+ return file.startsWith(normalizePath(config.srcDir)) || !file.startsWith(`${rootDir}/`);
19918
+ };
19919
+ /**
19664
19920
  * Run the TypeScript program to transpile source files.
19665
19921
  *
19666
19922
  * @param config - the validated Stencil configuration
@@ -19686,8 +19942,7 @@ const runTsProgram = async (config, compilerCtx, buildCtx, tsBuilder) => {
19686
19942
  let affected = emitBuilder.getSemanticDiagnosticsOfNextAffectedFile?.();
19687
19943
  while (affected) {
19688
19944
  if ("fileName" in affected.affected) {
19689
- const fileName = normalizePath(affected.affected.fileName);
19690
- if (!fileName.includes("node_modules") && !fileName.endsWith(".d.ts") && fileName.startsWith(normalizePath(config.srcDir))) {
19945
+ if (isTypeCheckedFile(config, affected.affected.fileName)) {
19691
19946
  const tsSemantic = loadTypeScriptDiagnostics(affected.result);
19692
19947
  applyDevModeRelaxation(config, tsSemantic);
19693
19948
  buildCtx.diagnostics.push(...tsSemantic);
@@ -19702,6 +19957,7 @@ const runTsProgram = async (config, compilerCtx, buildCtx, tsBuilder) => {
19702
19957
  else if (emitFilePath.endsWith(".d.ts")) {
19703
19958
  const srcDtsPath = normalizePath(tsSourceFiles[0].fileName);
19704
19959
  const relativeEmitFilepath = getRelativeDts(config, srcDtsPath, emitFilePath);
19960
+ data = rewriteExternalImports(config, srcDtsPath, data);
19705
19961
  emittedDts.push(srcDtsPath);
19706
19962
  typesOutputTarget.forEach((o) => {
19707
19963
  const distPath = normalizePath(join$2(normalizePath(o.dir), normalizePath(relativeEmitFilepath)));
@@ -19749,7 +20005,7 @@ const runTsProgram = async (config, compilerCtx, buildCtx, tsBuilder) => {
19749
20005
  buildCtx.components = filteredComponents;
19750
20006
  if (excludedComponents.length > 0 && typesOutputTarget.length > 0) excludedComponents.forEach((cmp) => {
19751
20007
  const srcPath = normalizePath(cmp.sourceFilePath);
19752
- const dtsRelativePath = relative$1(config.srcDir, srcPath).replace(/\.tsx?$/, ".d.ts");
20008
+ const dtsRelativePath = getOutputRelativePath(config, srcPath).replace(/\.tsx?$/, ".d.ts");
19753
20009
  typesOutputTarget.forEach((outputTarget) => {
19754
20010
  const outputDtsPath = join$2(outputTarget.dir, dtsRelativePath);
19755
20011
  const item = compilerCtx.fs.getItem(outputDtsPath);
@@ -19785,10 +20041,7 @@ const validateTypesAfterGeneration = async (config, compilerCtx, buildCtx, tsBui
19785
20041
  };
19786
20042
  }
19787
20043
  if (config.validateTypes && !buildCtx.isRebuild) {
19788
- const sourceFiles = tsProgram.getSourceFiles().filter((sf) => {
19789
- const fileName = normalizePath(sf.fileName);
19790
- return !fileName.includes("node_modules") && !fileName.endsWith(".d.ts") && fileName.startsWith(normalizePath(config.srcDir));
19791
- });
20044
+ const sourceFiles = tsProgram.getSourceFiles().filter((sf) => isTypeCheckedFile(config, sf.fileName));
19792
20045
  const semanticDiagnostics = [];
19793
20046
  for (const sourceFile of sourceFiles) {
19794
20047
  const tsSemantic = loadTypeScriptDiagnostics(tsProgram.getSemanticDiagnostics(sourceFile));
@@ -19806,10 +20059,11 @@ const validateTypesAfterGeneration = async (config, compilerCtx, buildCtx, tsBui
19806
20059
  const hasTypesChanged = await generateAppTypes(config, compilerCtx, buildCtx, "src");
19807
20060
  if (typesOutputTarget.length > 0) {
19808
20061
  const srcRootDtsFiles = tsProgram.getRootFileNames().filter((f) => f.endsWith(".d.ts") && !f.endsWith("components.d.ts")).map((s) => normalizePath(s)).filter((f) => !emittedDts.includes(f)).map((srcRootDtsFilePath) => {
19809
- const relativeEmitFilepath = relative$1(config.srcDir, srcRootDtsFilePath);
20062
+ const relativeEmitFilepath = getOutputRelativePath(config, srcRootDtsFilePath);
19810
20063
  return Promise.all(typesOutputTarget.map(async (o) => {
19811
20064
  const distPath = join$2(o.dir, relativeEmitFilepath);
19812
20065
  let dtsContent = await compilerCtx.fs.readFile(srcRootDtsFilePath);
20066
+ dtsContent = rewriteExternalImports(config, srcRootDtsFilePath, dtsContent);
19813
20067
  dtsContent = updateStencilTypesImports(o.dir, distPath, dtsContent);
19814
20068
  await compilerCtx.fs.writeFile(distPath, dtsContent);
19815
20069
  }));
@@ -19822,39 +20076,17 @@ const validateTypesAfterGeneration = async (config, compilerCtx, buildCtx, tsBui
19822
20076
  };
19823
20077
  };
19824
20078
  /**
19825
- * Calculate a relative path for a `.d.ts` file, giving the location within
19826
- * the typedef output directory where we'd like to write it to disk.
19827
- *
19828
- * The correct relative path for a `.d.ts` file is basically given by the
19829
- * relative location of the _source_ file associated with the `.d.ts` file
19830
- * within the Stencil project's source directory.
19831
- *
19832
- * Thus, in order to calculate this, we take the path to the source file, the
19833
- * emit path calculated by typescript (which is going to be right next to the
19834
- * emit location for the JavaScript that the compiler emits for the source file)
19835
- * and we do a pairwise walk up the two paths, assembling path components as
19836
- * we go, until the source file path is equal to the configured source
19837
- * directory. Then the path components from the `emitDtsPath` can be reversed
19838
- * and re-assembled into a suitable relative path.
20079
+ * Calculate a relative path for a `.d.ts` file within the typedef output directory: the
20080
+ * output-relative location of its source file (see {@link getOutputRelativePath}), with the
20081
+ * file name TypeScript chose for the declaration.
19839
20082
  *
19840
20083
  * @param config a Stencil configuration object
19841
20084
  * @param srcPath the path to the source file for the `.d.ts` file of interest
19842
- * @param emitDtsPath the emit path for the `.d.ts` file calculated by
19843
- * TypeScript
20085
+ * @param emitDtsPath the emit path for the `.d.ts` file calculated by TypeScript
19844
20086
  * @returns a relative path to a suitable location where the typedef file can be
19845
20087
  * written
19846
20088
  */
19847
- const getRelativeDts = (config, srcPath, emitDtsPath) => {
19848
- const parts = [];
19849
- for (let i = 0; i < 30; i++) {
19850
- if (normalizePath(config.srcDir) === srcPath) break;
19851
- const b = basename$1(emitDtsPath);
19852
- parts.push(b);
19853
- emitDtsPath = normalizePath(join$2(emitDtsPath, ".."));
19854
- srcPath = normalizePath(join$2(normalizePath(srcPath), ".."));
19855
- }
19856
- return normalizePath(join$2(...parts.reverse()));
19857
- };
20089
+ const getRelativeDts = (config, srcPath, emitDtsPath) => normalizePath(join$2(dirname$1(getOutputRelativePath(config, srcPath)), basename$1(emitDtsPath)));
19858
20090
  //#endregion
19859
20091
  //#region src/compiler/build/build-hmr.ts
19860
20092
  /**
@@ -21358,7 +21590,7 @@ function createCachingCompilerHost(options) {
21358
21590
  const fileVersionCache = /* @__PURE__ */ new Map();
21359
21591
  function computeVersion(text) {
21360
21592
  if (text === void 0) return "";
21361
- return `${text.length}-${text.charCodeAt(0) || 0}-${text.charCodeAt(text.length - 1) || 0}`;
21593
+ return ts.sys.createHash?.(text) ?? text;
21362
21594
  }
21363
21595
  host.readFile = (fileName) => {
21364
21596
  if (fileTextCache.has(fileName)) return fileTextCache.get(fileName);
@@ -22930,6 +23162,7 @@ const validatePaths = (config) => {
22930
23162
  };
22931
23163
  if (typeof config.globalScript === "string" && !isAbsolute$1(config.globalScript)) validatedPaths.globalScript = join$2(rootDir, config.globalScript);
22932
23164
  if (typeof config.globalStyle === "string" && !isAbsolute$1(config.globalStyle)) validatedPaths.globalStyle = join$2(rootDir, config.globalStyle);
23165
+ if (Array.isArray(config.watchExternalDirs)) validatedPaths.watchExternalDirs = config.watchExternalDirs.map((dir) => isAbsolute$1(dir) ? normalizePath(dir) : join$2(rootDir, dir));
22933
23166
  if (config.writeLog) {
22934
23167
  validatedPaths.buildLogFilePath = typeof config.buildLogFilePath === "string" ? config.buildLogFilePath : DEFAULT_BUILD_LOG_FILE_NAME;
22935
23168
  if (!isAbsolute$1(validatedPaths.buildLogFilePath)) validatedPaths.buildLogFilePath = join$2(rootDir, config.buildLogFilePath);
@@ -27276,7 +27509,6 @@ const transpileModule = (config, input, transformOpts) => {
27276
27509
  const isAutomaticRuntime = tsCompilerOptions.jsx === ts.JsxEmit.ReactJSX || tsCompilerOptions.jsx === ts.JsxEmit.ReactJSXDev;
27277
27510
  if (tsCompilerOptions.jsx != null && !isAutomaticRuntime && !isString$1(tsCompilerOptions.jsxFactory)) tsCompilerOptions.jsxFactory = "h";
27278
27511
  if (tsCompilerOptions.jsx != null && !isAutomaticRuntime && !isString$1(tsCompilerOptions.jsxFragmentFactory)) tsCompilerOptions.jsxFragmentFactory = "Fragment";
27279
- if (tsCompilerOptions.paths && !isString$1(tsCompilerOptions.baseUrl)) tsCompilerOptions.baseUrl = ".";
27280
27512
  const sourceFile = ts.createSourceFile(sourceFilePath, input, tsCompilerOptions.target);
27281
27513
  const importedSources = /* @__PURE__ */ new Map();
27282
27514
  const resolveImport = input.includes("resolveVar(") ? transformOpts.resolveImport : void 0;
@@ -27297,7 +27529,7 @@ const transpileModule = (config, input, transformOpts) => {
27297
27529
  };
27298
27530
  };
27299
27531
  if (resolveImport) tsCompilerOptions.noResolve = false;
27300
- const compilerHost = {
27532
+ const program = ts.createProgram([sourceFilePath], tsCompilerOptions, {
27301
27533
  getSourceFile: (fileName) => normalizePath(fileName) === normalizePath(sourceFilePath) ? sourceFile : importedSources.get(normalizePath(fileName)),
27302
27534
  writeFile: (name, text) => {
27303
27535
  if (name.endsWith(".js.map") || name.endsWith(".mjs.map")) results.map = text;
@@ -27312,9 +27544,8 @@ const transpileModule = (config, input, transformOpts) => {
27312
27544
  readFile: () => "",
27313
27545
  directoryExists: () => true,
27314
27546
  getDirectories: () => [],
27315
- ...resolveImport ? { resolveModuleNameLiterals: (moduleLiterals, containingFile) => moduleLiterals.map((literal) => ({ resolvedModule: resolveViaCallback(literal.text, containingFile) })) } : {}
27316
- };
27317
- const program = ts.createProgram([sourceFilePath], tsCompilerOptions, compilerHost);
27547
+ resolveModuleNameLiterals: (moduleLiterals, containingFile) => moduleLiterals.map((literal) => ({ resolvedModule: resolveImport ? resolveViaCallback(literal.text, containingFile) : void 0 }))
27548
+ });
27318
27549
  const typeChecker = program.getTypeChecker();
27319
27550
  const transformers = {
27320
27551
  before: [