@stencil/cli 5.0.0-alpha.3 → 5.0.0-alpha.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,7 +1,19 @@
1
1
  import { LOG_LEVELS } from "@stencil/core/compiler";
2
- import { buildError, catchError, hasError, isFunction, isOutputTargetDocs, isOutputTargetHydrate, isOutputTargetWww, isString, normalizePath, readOnlyArrayHasStringMember, result, shouldIgnoreError, toCamelCase, validateComponentTag } from "@stencil/core/compiler/utils";
3
- import { isAbsolute, join, parse, relative } from "path";
2
+ import { buildError, catchError, hasError, isFunction, isOutputTargetDistLazy, isOutputTargetDocs, isOutputTargetSsr, isOutputTargetStandalone, isOutputTargetWww, isString, normalizePath, readOnlyArrayHasStringMember, result, shouldIgnoreError, toCamelCase, validateComponentTag } from "@stencil/core/compiler/utils";
3
+ import { basename, dirname, join, parse, relative, resolve } from "node:path";
4
+ import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
5
+ import * as p from "@clack/prompts";
6
+ import { cancel, isCancel, select } from "@clack/prompts";
7
+ import * as nypm from "nypm";
8
+ import { addDevDependency, detectPackageManager } from "nypm";
9
+ import { isCI } from "std-env";
4
10
  import ts from "typescript";
11
+ import { pathToFileURL } from "node:url";
12
+ import { getPackageInfo } from "local-pkg";
13
+ import { existsSync } from "node:fs";
14
+ import { homedir } from "node:os";
15
+ import { dirname as dirname$1, isAbsolute, join as join$1, relative as relative$1 } from "path";
16
+ import { generateIndexHtml, generatePackageJsonFields, generateStencilConfig, getComponentBoilerplate, getPreviewHtmlBoilerplate, getStyleBoilerplate, getTemplatePath, getUsageExampleBoilerplate, toPascalCase } from "@stencil/templates";
5
17
  import { start } from "@stencil/dev-server";
6
18
  //#region src/config-flags.ts
7
19
  /**
@@ -18,13 +30,11 @@ const BOOLEAN_CLI_FLAGS = [
18
30
  "devtools",
19
31
  "docs",
20
32
  "dryRun",
21
- "esm",
22
33
  "help",
23
34
  "log",
24
35
  "open",
25
36
  "prerender",
26
37
  "prerenderExternal",
27
- "prod",
28
38
  "profile",
29
39
  "serviceWorker",
30
40
  "serve",
@@ -188,8 +198,10 @@ const parseCLITerm = (flags, args) => {
188
198
  const [originalArg, value] = parseEqualsArg(arg);
189
199
  setCLIArg(flags, desugarRawAlias(originalArg), normalizeFlagName(originalArg), value);
190
200
  } else if (CLI_FLAG_REGEX.test(arg)) setCLIArg(flags, desugarRawAlias(arg), normalizeFlagName(arg), parseCLIValue(args));
191
- else if (arg.startsWith("--no-") && arg.length > 5) setCLIArg(flags, arg, normalizeNegativeFlagName(arg), "");
192
- else if (arg.startsWith("--no") && (isNegatedBoolean || isNegatedBooleanOrString)) setCLIArg(flags, arg, normalizeNegativeFlagName(arg), "");
201
+ else if (arg.startsWith("--no-") && arg.length > 5) {
202
+ const normalized = normalizeNegativeFlagName(arg);
203
+ setCLIArg(flags, arg, normalized, "");
204
+ } else if (arg.startsWith("--no") && (isNegatedBoolean || isNegatedBooleanOrString)) setCLIArg(flags, arg, normalizeNegativeFlagName(arg), "");
193
205
  else if (arg.startsWith("--") && arg.length > 2) setCLIArg(flags, arg, normalizeFlagName(arg), parseCLIValue(args));
194
206
  else flags.unknownArgs.push(arg);
195
207
  };
@@ -242,52 +254,58 @@ const setCLIArg = (flags, rawArg, normalizedArg, value) => {
242
254
  flags[normalizedArg] = typeof value === "string" ? value === "true" : true;
243
255
  flags.knownArgs.push(rawArg);
244
256
  if (typeof value === "string" && value !== "") flags.knownArgs.push(value);
245
- } else if (readOnlyArrayHasStringMember(STRING_CLI_FLAGS, normalizedArg)) if (typeof value === "string") {
246
- flags[normalizedArg] = value;
247
- flags.knownArgs.push(rawArg);
248
- flags.knownArgs.push(value);
249
- } else throwCLIParsingError(rawArg, "expected a string argument but received nothing");
250
- else if (STRING_ARRAY_CLI_FLAGS.length > 0 && readOnlyArrayHasStringMember(STRING_ARRAY_CLI_FLAGS, normalizedArg)) if (typeof value === "string") {
251
- const flagsRecord = flags;
252
- if (!Array.isArray(flagsRecord[normalizedArg])) flagsRecord[normalizedArg] = [];
253
- const targetArray = flagsRecord[normalizedArg];
254
- if (Array.isArray(targetArray)) {
255
- targetArray.push(value);
257
+ } else if (readOnlyArrayHasStringMember(STRING_CLI_FLAGS, normalizedArg)) {
258
+ if (typeof value === "string") {
259
+ flags[normalizedArg] = value;
256
260
  flags.knownArgs.push(rawArg);
257
261
  flags.knownArgs.push(value);
258
- }
259
- } else throwCLIParsingError(rawArg, "expected a string argument but received nothing");
260
- else if (readOnlyArrayHasStringMember(NUMBER_CLI_FLAGS, normalizedArg)) if (typeof value === "string") {
261
- const parsed = parseInt(value, 10);
262
- if (isNaN(parsed)) throwNumberParsingError(rawArg, value);
263
- else {
264
- flags[normalizedArg] = parsed;
262
+ } else throwCLIParsingError(rawArg, "expected a string argument but received nothing");
263
+ } else if (STRING_ARRAY_CLI_FLAGS.length > 0 && readOnlyArrayHasStringMember(STRING_ARRAY_CLI_FLAGS, normalizedArg)) {
264
+ if (typeof value === "string") {
265
+ const flagsRecord = flags;
266
+ if (!Array.isArray(flagsRecord[normalizedArg])) flagsRecord[normalizedArg] = [];
267
+ const targetArray = flagsRecord[normalizedArg];
268
+ if (Array.isArray(targetArray)) {
269
+ targetArray.push(value);
270
+ flags.knownArgs.push(rawArg);
271
+ flags.knownArgs.push(value);
272
+ }
273
+ } else throwCLIParsingError(rawArg, "expected a string argument but received nothing");
274
+ } else if (readOnlyArrayHasStringMember(NUMBER_CLI_FLAGS, normalizedArg)) {
275
+ if (typeof value === "string") {
276
+ const parsed = parseInt(value, 10);
277
+ if (isNaN(parsed)) throwNumberParsingError(rawArg, value);
278
+ else {
279
+ flags[normalizedArg] = parsed;
280
+ flags.knownArgs.push(rawArg);
281
+ flags.knownArgs.push(value);
282
+ }
283
+ } else throwCLIParsingError(rawArg, "expected a number argument but received nothing");
284
+ } else if (readOnlyArrayHasStringMember(STRING_NUMBER_CLI_FLAGS, normalizedArg)) {
285
+ if (typeof value === "string") {
286
+ if (CLI_ARG_STRING_REGEX.test(value)) flags[normalizedArg] = value;
287
+ else {
288
+ const parsed = Number(value);
289
+ if (isNaN(parsed)) throwNumberParsingError(rawArg, value);
290
+ else flags[normalizedArg] = parsed;
291
+ }
265
292
  flags.knownArgs.push(rawArg);
266
293
  flags.knownArgs.push(value);
267
- }
268
- } else throwCLIParsingError(rawArg, "expected a number argument but received nothing");
269
- else if (readOnlyArrayHasStringMember(STRING_NUMBER_CLI_FLAGS, normalizedArg)) if (typeof value === "string") {
270
- if (CLI_ARG_STRING_REGEX.test(value)) flags[normalizedArg] = value;
271
- else {
272
- const parsed = Number(value);
273
- if (isNaN(parsed)) throwNumberParsingError(rawArg, value);
274
- else flags[normalizedArg] = parsed;
275
- }
276
- flags.knownArgs.push(rawArg);
277
- flags.knownArgs.push(value);
278
- } else throwCLIParsingError(rawArg, "expected a string or a number but received nothing");
279
- else if (readOnlyArrayHasStringMember(BOOLEAN_STRING_CLI_FLAGS, normalizedArg)) {
294
+ } else throwCLIParsingError(rawArg, "expected a string or a number but received nothing");
295
+ } else if (readOnlyArrayHasStringMember(BOOLEAN_STRING_CLI_FLAGS, normalizedArg)) {
280
296
  const derivedValue = typeof value === "string" ? value ? value : false : true;
281
297
  flags[normalizedArg] = derivedValue;
282
298
  flags.knownArgs.push(rawArg);
283
299
  if (typeof derivedValue === "string" && derivedValue) flags.knownArgs.push(derivedValue);
284
- } else if (readOnlyArrayHasStringMember(LOG_LEVEL_CLI_FLAGS, normalizedArg)) if (typeof value === "string") if (isLogLevel(value)) {
285
- flags[normalizedArg] = value;
286
- flags.knownArgs.push(rawArg);
287
- flags.knownArgs.push(value);
288
- } else throwCLIParsingError(rawArg, `expected to receive a valid log level but received "${String(value)}"`);
289
- else throwCLIParsingError(rawArg, "expected to receive a valid log level but received nothing");
290
- else {
300
+ } else if (readOnlyArrayHasStringMember(LOG_LEVEL_CLI_FLAGS, normalizedArg)) {
301
+ if (typeof value === "string") {
302
+ if (isLogLevel(value)) {
303
+ flags[normalizedArg] = value;
304
+ flags.knownArgs.push(rawArg);
305
+ flags.knownArgs.push(value);
306
+ } else throwCLIParsingError(rawArg, `expected to receive a valid log level but received "${String(value)}"`);
307
+ } else throwCLIParsingError(rawArg, "expected to receive a valid log level but received nothing");
308
+ } else {
291
309
  flags.unknownArgs.push(rawArg);
292
310
  if (typeof value === "string") flags.unknownArgs.push(value);
293
311
  }
@@ -438,11 +456,12 @@ const findConfig = async (opts) => {
438
456
  const cwd = sys.getCurrentDirectory();
439
457
  const rootDir = normalizePath(cwd);
440
458
  let configPath = opts.configPath;
441
- if (isString(configPath)) if (!sys.platformPath.isAbsolute(configPath)) configPath = normalizePath(sys.platformPath.join(cwd, configPath));
442
- else configPath = normalizePath(configPath);
443
- else configPath = rootDir;
459
+ if (isString(configPath)) {
460
+ if (!sys.platformPath.isAbsolute(configPath)) configPath = normalizePath(sys.platformPath.join(cwd, configPath));
461
+ else configPath = normalizePath(configPath);
462
+ } else configPath = rootDir;
444
463
  const results = {
445
- configPath,
464
+ configPath: null,
446
465
  rootDir: normalizePath(cwd)
447
466
  };
448
467
  const stat = await sys.stat(configPath);
@@ -457,12 +476,15 @@ const findConfig = async (opts) => {
457
476
  if (stat.isFile) {
458
477
  results.configPath = configPath;
459
478
  results.rootDir = sys.platformPath.dirname(configPath);
460
- } else if (stat.isDirectory) for (const configName of ["stencil.config.ts", "stencil.config.js"]) {
461
- const testConfigFilePath = sys.platformPath.join(configPath, configName);
462
- if ((await sys.stat(testConfigFilePath)).isFile) {
463
- results.configPath = testConfigFilePath;
464
- results.rootDir = sys.platformPath.dirname(testConfigFilePath);
465
- break;
479
+ } else if (stat.isDirectory) {
480
+ results.rootDir = configPath;
481
+ for (const configName of ["stencil.config.ts", "stencil.config.js"]) {
482
+ const testConfigFilePath = sys.platformPath.join(configPath, configName);
483
+ if ((await sys.stat(testConfigFilePath)).isFile) {
484
+ results.configPath = testConfigFilePath;
485
+ results.rootDir = sys.platformPath.dirname(testConfigFilePath);
486
+ break;
487
+ }
466
488
  }
467
489
  }
468
490
  return result.ok(results);
@@ -561,7 +583,7 @@ const startupCompilerLog = (coreCompiler, config) => {
561
583
  *
562
584
  * This function applies command-line flags to the config, with CLI flags
563
585
  * taking precedence over config file values. This is the canonical place
564
- * where flag values are translated into config properties.?
586
+ * where flag values are translated into config properties.
565
587
  *
566
588
  * @param config The config object (from stencil.config.ts or empty)
567
589
  * @param flags The parsed CLI flags
@@ -569,13 +591,11 @@ const startupCompilerLog = (coreCompiler, config) => {
569
591
  */
570
592
  const mergeFlags = (config, flags) => {
571
593
  const merged = { ...config };
572
- if (flags.prod === true) merged.devMode = false;
573
- else if (flags.dev === true) merged.devMode = true;
594
+ if (flags.dev === true) merged.devMode = true;
574
595
  if (flags.debug === true || flags.verbose === true) merged.logLevel = "debug";
575
596
  else if (flags.logLevel) merged.logLevel = flags.logLevel;
576
597
  if (typeof flags.watch === "boolean") merged.watch = flags.watch;
577
- if (typeof flags.docs === "boolean") merged.buildDocs = flags.docs;
578
- if (typeof flags.esm === "boolean") merged.buildDist = flags.esm;
598
+ if (flags.docs === true) merged._docsFlag = true;
579
599
  if (typeof flags.profile === "boolean") merged.profile = flags.profile;
580
600
  if (typeof flags.log === "boolean") merged.writeLog = flags.log;
581
601
  if (typeof flags.cache === "boolean") merged.enableCache = flags.cache;
@@ -592,6 +612,739 @@ const mergeFlags = (config, flags) => {
592
612
  return merged;
593
613
  };
594
614
  //#endregion
615
+ //#region src/wizard/config-editor.ts
616
+ async function openStencilConfig(configPath) {
617
+ let text = await readFile(configPath, "utf8");
618
+ const parse = () => ts.createSourceFile(configPath, text, ts.ScriptTarget.Latest, true);
619
+ function findArray(sf, propName) {
620
+ let found;
621
+ const visit = (node) => {
622
+ if (!found && ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === propName && ts.isArrayLiteralExpression(node.initializer)) found = node.initializer;
623
+ else ts.forEachChild(node, visit);
624
+ };
625
+ visit(sf);
626
+ return found;
627
+ }
628
+ function findConfigObject(sf) {
629
+ for (const stmt of sf.statements) if (ts.isVariableStatement(stmt)) {
630
+ for (const decl of stmt.declarationList.declarations) if (ts.isIdentifier(decl.name) && decl.name.text === "config" && decl.initializer && ts.isObjectLiteralExpression(decl.initializer)) return decl.initializer;
631
+ }
632
+ let found;
633
+ const visit = (node) => {
634
+ if (found) return;
635
+ if (ts.isObjectLiteralExpression(node)) {
636
+ if (node.properties.some((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "namespace")) {
637
+ found = node;
638
+ return;
639
+ }
640
+ }
641
+ ts.forEachChild(node, visit);
642
+ };
643
+ visit(sf);
644
+ return found;
645
+ }
646
+ function replaceInArray(arr, substring, expression) {
647
+ for (const element of arr.elements) if (text.slice(element.getStart(), element.getEnd()).includes(substring)) {
648
+ const lineStart = text.lastIndexOf("\n", element.getStart()) + 1;
649
+ const indent = text.slice(lineStart, element.getStart()).match(/^\s+/)?.[0] ?? "";
650
+ const indentedExpression = indent ? expression.replace(/\n/g, `\n${indent}`) : expression;
651
+ text = text.slice(0, element.getStart()) + indentedExpression + text.slice(element.getEnd());
652
+ return true;
653
+ }
654
+ return false;
655
+ }
656
+ function removeFromArray(arr, substring) {
657
+ const idx = arr.elements.findIndex((element) => text.slice(element.getStart(), element.getEnd()).includes(substring));
658
+ if (idx === -1) return false;
659
+ const element = arr.elements[idx];
660
+ if (arr.elements.length > 0 && text.slice(arr.getStart(), arr.elements[0].getStart()).includes("\n")) {
661
+ const lineStart = text.lastIndexOf("\n", element.getStart());
662
+ let end = element.getEnd();
663
+ const trailingComma = text.slice(end).match(/^\s*,/);
664
+ if (trailingComma) end += trailingComma[0].length;
665
+ text = text.slice(0, lineStart) + text.slice(end);
666
+ } else {
667
+ let start = element.getStart();
668
+ let end = element.getEnd();
669
+ if (idx < arr.elements.length - 1) {
670
+ const trailingMatch = text.slice(end).match(/^,\s*/);
671
+ if (trailingMatch) end += trailingMatch[0].length;
672
+ } else if (idx > 0) {
673
+ const precedingMatch = text.slice(0, start).match(/,\s*$/);
674
+ if (precedingMatch) start -= precedingMatch[0].length;
675
+ }
676
+ text = text.slice(0, start) + text.slice(end);
677
+ }
678
+ return true;
679
+ }
680
+ function appendToArray(arr, code) {
681
+ if (arr.elements.length === 0) {
682
+ const insertPos = arr.getEnd() - 1;
683
+ text = text.slice(0, insertPos) + code + text.slice(insertPos);
684
+ return;
685
+ }
686
+ let insertPos = arr.elements[arr.elements.length - 1].getEnd();
687
+ const trailingComma = text.slice(insertPos).match(/^\s*,/);
688
+ if (trailingComma) insertPos += trailingComma[0].length;
689
+ const separator = trailingComma ? "" : ",";
690
+ const firstElemStart = arr.elements[0].getStart();
691
+ if (text.slice(arr.getStart(), firstElemStart).includes("\n")) {
692
+ const lineStart = text.lastIndexOf("\n", firstElemStart) + 1;
693
+ const indent = text.slice(lineStart, firstElemStart).match(/^\s+/)?.[0] ?? " ";
694
+ const indentedCode = code.replace(/\n/g, `\n${indent}`);
695
+ text = `${text.slice(0, insertPos)}${separator}\n${indent}${indentedCode}${text.slice(insertPos)}`;
696
+ } else text = `${text.slice(0, insertPos)}${separator} ${code}${text.slice(insertPos)}`;
697
+ }
698
+ function addArrayProp(sf, propName, code) {
699
+ const configObj = findConfigObject(sf);
700
+ if (!configObj) throw new Error("Could not find Stencil config object in stencil.config.ts");
701
+ let propIndent = " ";
702
+ if (configObj.properties.length > 0) {
703
+ const firstPropStart = configObj.properties[0].getStart();
704
+ const lineStart = text.lastIndexOf("\n", firstPropStart) + 1;
705
+ propIndent = text.slice(lineStart, firstPropStart).match(/^\s+/)?.[0] ?? " ";
706
+ }
707
+ const elemIndent = propIndent + " ";
708
+ const newProp = `${propName}: [\n${elemIndent}${code.replace(/\n/g, `\n${elemIndent}`)},\n${propIndent}]`;
709
+ const lastProp = configObj.properties[configObj.properties.length - 1];
710
+ if (lastProp) {
711
+ let insertPos = lastProp.getEnd();
712
+ const trailingComma = text.slice(insertPos).match(/^\s*,/);
713
+ const separator = trailingComma ? "" : ",";
714
+ if (trailingComma) insertPos += trailingComma[0].length;
715
+ text = `${text.slice(0, insertPos)}${separator}\n${propIndent}${newProp}${text.slice(insertPos)}`;
716
+ } else {
717
+ const insertPos = configObj.getEnd() - 1;
718
+ text = `${text.slice(0, insertPos)}\n${propIndent}${newProp},\n${text.slice(insertPos)}`;
719
+ }
720
+ }
721
+ return {
722
+ hasImport(moduleSpecifier) {
723
+ return parse().statements.some((s) => ts.isImportDeclaration(s) && ts.isStringLiteral(s.moduleSpecifier) && s.moduleSpecifier.text === moduleSpecifier);
724
+ },
725
+ addImport(moduleSpecifier, namedImports) {
726
+ const sf = parse();
727
+ if (sf.statements.some((s) => ts.isImportDeclaration(s) && ts.isStringLiteral(s.moduleSpecifier) && s.moduleSpecifier.text === moduleSpecifier)) return;
728
+ let insertPos = 0;
729
+ for (const s of sf.statements) if (ts.isImportDeclaration(s)) insertPos = s.getEnd();
730
+ const decl = `\nimport { ${namedImports.join(", ")} } from '${moduleSpecifier}';`;
731
+ text = insertPos > 0 ? text.slice(0, insertPos) + decl + text.slice(insertPos) : decl + "\n" + text;
732
+ },
733
+ outputTargetsContains(substring) {
734
+ const arr = findArray(parse(), "outputTargets");
735
+ return arr ? text.slice(arr.getStart(), arr.getEnd()).includes(substring) : false;
736
+ },
737
+ addOutputTarget(expression) {
738
+ const sf = parse();
739
+ const arr = findArray(sf, "outputTargets");
740
+ if (arr) appendToArray(arr, expression);
741
+ else addArrayProp(sf, "outputTargets", expression);
742
+ },
743
+ replaceOutputTarget(substring, expression) {
744
+ const arr = findArray(parse(), "outputTargets");
745
+ return arr ? replaceInArray(arr, substring, expression) : false;
746
+ },
747
+ removeOutputTarget(substring) {
748
+ const arr = findArray(parse(), "outputTargets");
749
+ return arr ? removeFromArray(arr, substring) : false;
750
+ },
751
+ pluginsContains(substring) {
752
+ const arr = findArray(parse(), "plugins");
753
+ return arr ? text.slice(arr.getStart(), arr.getEnd()).includes(substring) : false;
754
+ },
755
+ addPlugin(expression) {
756
+ const sf = parse();
757
+ const arr = findArray(sf, "plugins");
758
+ if (arr) appendToArray(arr, expression);
759
+ else addArrayProp(sf, "plugins", expression);
760
+ },
761
+ replacePlugin(substring, expression) {
762
+ const arr = findArray(parse(), "plugins");
763
+ return arr ? replaceInArray(arr, substring, expression) : false;
764
+ },
765
+ removePlugin(substring) {
766
+ const arr = findArray(parse(), "plugins");
767
+ return arr ? removeFromArray(arr, substring) : false;
768
+ },
769
+ async save() {
770
+ await writeFile(configPath, text, "utf8");
771
+ }
772
+ };
773
+ }
774
+ //#endregion
775
+ //#region src/wizard/discover.ts
776
+ function toStringRecord(val) {
777
+ return val !== null && typeof val === "object" ? val : {};
778
+ }
779
+ async function readJson$1(filePath) {
780
+ try {
781
+ return JSON.parse(await readFile(filePath, "utf8"));
782
+ } catch {
783
+ return null;
784
+ }
785
+ }
786
+ async function loadOne(rootDir, packageName, loader) {
787
+ const info = await getPackageInfo(packageName, { paths: [rootDir] });
788
+ if (!info) return null;
789
+ const wizardEntry = info.packageJson.stencil?.wizard;
790
+ if (!wizardEntry) return null;
791
+ const wizardPath = join(info.rootPath, wizardEntry);
792
+ let mod;
793
+ try {
794
+ mod = await loader(pathToFileURL(wizardPath).href);
795
+ } catch {
796
+ console.warn(`[stencil] ${packageName} declares stencil.wizard but the module failed to load: ${wizardPath}`);
797
+ return null;
798
+ }
799
+ const plugin = mod.wizard;
800
+ if (!plugin || typeof plugin !== "object") {
801
+ console.warn(`[stencil] ${packageName} declares stencil.wizard but does not export a 'wizard' object`);
802
+ return null;
803
+ }
804
+ return {
805
+ packageName,
806
+ plugin
807
+ };
808
+ }
809
+ /**
810
+ * Scans the project's declared dependencies for packages that expose a
811
+ * `stencil.wizard` entry in their `package.json` and dynamically imports
812
+ * each matching module.
813
+ *
814
+ * @param rootDir - Absolute path to the project root (where `package.json` lives).
815
+ * @param loader - Module loader; injectable for testing. Defaults to `import()`.
816
+ * @returns Array of successfully loaded plugins, in dependency declaration order.
817
+ */
818
+ async function discoverPlugins(rootDir, loader = (url) => import(url)) {
819
+ const pkg = await readJson$1(join(rootDir, "package.json"));
820
+ if (!pkg) return [];
821
+ const depNames = [.../* @__PURE__ */ new Set([...Object.keys(toStringRecord(pkg.dependencies)), ...Object.keys(toStringRecord(pkg.devDependencies))])];
822
+ const plugins = (await Promise.allSettled(depNames.map((name) => loadOne(rootDir, name, loader)))).filter((r) => r.status === "fulfilled" && r.value !== null).map((r) => r.value);
823
+ const devEnv = process.env.STENCIL_WIZARD_DEV;
824
+ if (devEnv) {
825
+ const devPaths = devEnv.split(",").map((s) => s.trim()).filter(Boolean);
826
+ for (const devPath of devPaths) {
827
+ const devPlugin = await loadDevPlugin(resolve(rootDir, devPath), loader);
828
+ if (devPlugin) {
829
+ const idx = plugins.findIndex((p) => p.packageName === devPlugin.packageName);
830
+ if (idx >= 0) plugins.splice(idx, 1, devPlugin);
831
+ else plugins.unshift(devPlugin);
832
+ }
833
+ }
834
+ }
835
+ return plugins;
836
+ }
837
+ async function findDevPackageName(wizardPath) {
838
+ const dir = dirname(wizardPath);
839
+ for (const candidate of [dir, resolve(dir, "..")]) {
840
+ const pkg = await readJson$1(join(candidate, "package.json"));
841
+ if (typeof pkg?.name === "string") return pkg.name;
842
+ }
843
+ return basename(dir);
844
+ }
845
+ async function loadDevPlugin(wizardPath, loader) {
846
+ const packageName = await findDevPackageName(wizardPath);
847
+ let mod;
848
+ try {
849
+ mod = await loader(pathToFileURL(wizardPath).href);
850
+ } catch {
851
+ console.warn(`[stencil] STENCIL_WIZARD_DEV: failed to load ${wizardPath}`);
852
+ return null;
853
+ }
854
+ const plugin = mod.wizard;
855
+ if (!plugin || typeof plugin !== "object") {
856
+ console.warn(`[stencil] STENCIL_WIZARD_DEV: ${wizardPath} does not export a 'wizard' object`);
857
+ return null;
858
+ }
859
+ return {
860
+ packageName,
861
+ plugin
862
+ };
863
+ }
864
+ //#endregion
865
+ //#region src/wizard/clack.ts
866
+ /**
867
+ * Exits cleanly if the user cancelled a prompt (Ctrl+C).
868
+ * Narrows the type from `T | symbol` to `T` for callers.
869
+ *
870
+ * @param value - Return value from a `@clack/prompts` prompt call.
871
+ */
872
+ function cancelIfAborted(value) {
873
+ if (isCancel(value)) {
874
+ cancel("Cancelled.");
875
+ process.exit(0);
876
+ }
877
+ }
878
+ //#endregion
879
+ //#region src/wizard/init/steps.ts
880
+ /** Well-known integrations the CLI can offer before any packages are installed. */
881
+ const KNOWN_INTEGRATIONS = [
882
+ {
883
+ package: "@stencil/vitest",
884
+ displayName: "Vitest",
885
+ description: "Unit / Spec / Integration / Browser testing",
886
+ group: "Testing"
887
+ },
888
+ {
889
+ package: "@stencil/playwright",
890
+ displayName: "Playwright",
891
+ description: "E2E testing",
892
+ group: "Testing"
893
+ },
894
+ {
895
+ package: "@stencil/sass",
896
+ displayName: "Sass",
897
+ description: "Sass/SCSS styles",
898
+ group: "Styling",
899
+ requiresStencilConfig: true
900
+ },
901
+ {
902
+ package: "@stencil/eslint-plugin",
903
+ displayName: "ESLint Plugin",
904
+ description: "Stencil-aware lint rules (ESLint or oxlint)",
905
+ group: "Tooling"
906
+ },
907
+ {
908
+ package: "@stencil/storybook-plugin",
909
+ displayName: "Storybook",
910
+ description: "Component development & documentation",
911
+ group: "Tooling",
912
+ versionRange: ">=1.0.0-0"
913
+ },
914
+ {
915
+ package: "@stencil/types-output-target",
916
+ displayName: "Types",
917
+ description: "TypeScript types for React, Vue, Solid, Svelte, Preact",
918
+ group: "Framework integrations",
919
+ requiresStencilConfig: true
920
+ },
921
+ {
922
+ package: "@stencil/react-output-target",
923
+ displayName: "React",
924
+ description: "React component wrappers",
925
+ group: "Framework integrations",
926
+ requiresStencilConfig: true,
927
+ needsWorkspace: true
928
+ },
929
+ {
930
+ package: "@stencil/angular-output-target",
931
+ displayName: "Angular",
932
+ description: "Angular component wrappers",
933
+ group: "Framework integrations",
934
+ requiresStencilConfig: true,
935
+ needsWorkspace: true
936
+ },
937
+ {
938
+ package: "@stencil/vue-output-target",
939
+ displayName: "Vue",
940
+ description: "Vue component wrappers",
941
+ group: "Framework integrations",
942
+ requiresStencilConfig: true,
943
+ needsWorkspace: true
944
+ }
945
+ ];
946
+ const versionRangeByPackage = new Map(KNOWN_INTEGRATIONS.filter((i) => i.versionRange).map((i) => [i.package, i.versionRange]));
947
+ function withVersionRanges(packages) {
948
+ return packages.map((pkg) => {
949
+ const range = versionRangeByPackage.get(pkg);
950
+ return range ? `${pkg}@${range}` : pkg;
951
+ });
952
+ }
953
+ async function promptOutputs() {
954
+ const picks = await p.multiselect({
955
+ message: "Outputs:",
956
+ options: [
957
+ {
958
+ value: "loader",
959
+ label: "Loader",
960
+ hint: "performant lazy-loader; browser & bundler ready"
961
+ },
962
+ {
963
+ value: "standalone",
964
+ label: "Standalone",
965
+ hint: "per-component modules, import only what you need"
966
+ },
967
+ {
968
+ value: "ssr",
969
+ label: "SSR",
970
+ hint: "pre-render components in any JS server environment"
971
+ },
972
+ {
973
+ value: "ssr-wasm",
974
+ label: "SSR WASM",
975
+ hint: "experimental: compile SSR to a portable WASM binary"
976
+ },
977
+ {
978
+ value: "www",
979
+ label: "WWW",
980
+ hint: "app mode with dev server and optional PWA support"
981
+ }
982
+ ],
983
+ required: false
984
+ });
985
+ cancelIfAborted(picks);
986
+ return picks;
987
+ }
988
+ async function promptFeatures() {
989
+ const picks = await p.multiselect({
990
+ message: "Features:",
991
+ options: [
992
+ {
993
+ value: "signals",
994
+ label: "Signals",
995
+ hint: "signal-backed @Prop/@State for cross-framework reactive interop"
996
+ },
997
+ {
998
+ value: "globalStyle",
999
+ label: "Global style",
1000
+ hint: "Global stylesheet for font definitions, CSS variables, pre-load styles etc"
1001
+ },
1002
+ {
1003
+ value: "globalScript",
1004
+ label: "Global script",
1005
+ hint: "Global script for initializing application-wide logic before components load"
1006
+ }
1007
+ ],
1008
+ required: false
1009
+ });
1010
+ cancelIfAborted(picks);
1011
+ const set = new Set(picks);
1012
+ return {
1013
+ signals: set.has("signals"),
1014
+ globalStyle: set.has("globalStyle"),
1015
+ globalScript: set.has("globalScript")
1016
+ };
1017
+ }
1018
+ async function promptDocs() {
1019
+ const picks = await p.multiselect({
1020
+ message: "Docs:",
1021
+ options: [
1022
+ {
1023
+ value: "cem",
1024
+ label: "CEM",
1025
+ hint: "custom-elements.json - preferred format for interop with tools like Storybook, Styleguidist, etc"
1026
+ },
1027
+ {
1028
+ value: "json",
1029
+ label: "JSON",
1030
+ hint: "docs.json - Stencil / Ionic centric schema"
1031
+ },
1032
+ {
1033
+ value: "skill",
1034
+ label: "AI Skill",
1035
+ hint: "dist/skill/SKILL.md - Agent Skill (agentskills.io) reference for AI coding agents"
1036
+ },
1037
+ {
1038
+ value: "vscode",
1039
+ label: "VS Code",
1040
+ hint: "vscode-data.json - editor autocomplete for your components"
1041
+ }
1042
+ ],
1043
+ required: false
1044
+ });
1045
+ cancelIfAborted(picks);
1046
+ return picks;
1047
+ }
1048
+ async function promptProjectName() {
1049
+ const name = await p.text({
1050
+ message: "Project name:",
1051
+ defaultValue: "my-stencil-library",
1052
+ validate: (v) => {
1053
+ if (!v?.trim()) return "Project name is required";
1054
+ }
1055
+ });
1056
+ cancelIfAborted(name);
1057
+ return name;
1058
+ }
1059
+ function buildGroupedOptions(integrations) {
1060
+ const groups = {};
1061
+ for (const i of integrations) (groups[i.group] ??= []).push({
1062
+ value: i.package,
1063
+ label: i.displayName,
1064
+ hint: i.description
1065
+ });
1066
+ return groups;
1067
+ }
1068
+ async function promptCustomPackages() {
1069
+ const input = await p.text({
1070
+ message: "Additional packages to install:",
1071
+ placeholder: "e.g. my-plugin another-package (leave blank to skip)"
1072
+ });
1073
+ cancelIfAborted(input);
1074
+ if (typeof input !== "string" || !input.trim()) return [];
1075
+ return input.split(/[\s,]+/).map((s) => s.trim()).filter(Boolean);
1076
+ }
1077
+ async function promptIntegrations() {
1078
+ const picks = await p.groupMultiselect({
1079
+ message: "Add integrations (optional):",
1080
+ options: buildGroupedOptions(KNOWN_INTEGRATIONS),
1081
+ required: false
1082
+ });
1083
+ cancelIfAborted(picks);
1084
+ return KNOWN_INTEGRATIONS.filter((i) => picks.includes(i.package));
1085
+ }
1086
+ function hasFrameworkTargets(integrations) {
1087
+ return integrations.some((i) => i.needsWorkspace);
1088
+ }
1089
+ function needsStencilConfig(integrations) {
1090
+ return integrations.some((i) => i.requiresStencilConfig);
1091
+ }
1092
+ async function promptMonorepo() {
1093
+ const answer = await p.confirm({
1094
+ message: "Set up as a monorepo workspace? (recommended for publishing framework wrappers)",
1095
+ initialValue: true
1096
+ });
1097
+ cancelIfAborted(answer);
1098
+ return answer;
1099
+ }
1100
+ async function promptWorkspaceCoreName() {
1101
+ const name = await p.text({
1102
+ message: "Core package directory name:",
1103
+ defaultValue: "core",
1104
+ placeholder: "core"
1105
+ });
1106
+ cancelIfAborted(name);
1107
+ return name || "core";
1108
+ }
1109
+ /**
1110
+ * Prompt for actions on an existing project: install new integrations and/or
1111
+ * run init wizards for already-installed packages with wizard contributions.
1112
+ *
1113
+ * @param installable - KNOWN_INTEGRATIONS not yet present in the project.
1114
+ * @param configurable - Already-installed plugins that declare an `init` contribution.
1115
+ * @returns Selected integrations to install and plugins to configure.
1116
+ */
1117
+ async function promptAddCapabilities(installable, configurable) {
1118
+ const options = {};
1119
+ if (installable.length > 0) options["Install new integrations"] = installable.map((i) => ({
1120
+ value: `install:${i.package}`,
1121
+ label: i.displayName,
1122
+ hint: i.description
1123
+ }));
1124
+ if (configurable.length > 0) options["Configure existing integrations"] = configurable.map((d) => ({
1125
+ value: `configure:${d.packageName}`,
1126
+ label: d.plugin.init.displayName,
1127
+ hint: d.plugin.init.description
1128
+ }));
1129
+ const picks = await p.groupMultiselect({
1130
+ message: "What would you like to do?",
1131
+ options,
1132
+ required: false
1133
+ });
1134
+ cancelIfAborted(picks);
1135
+ const pickedSet = new Set(picks);
1136
+ return {
1137
+ toInstall: installable.filter((i) => pickedSet.has(`install:${i.package}`)),
1138
+ toConfigure: configurable.filter((d) => pickedSet.has(`configure:${d.packageName}`))
1139
+ };
1140
+ }
1141
+ //#endregion
1142
+ //#region src/wizard/project.ts
1143
+ /**
1144
+ * Extracts the stable, plugin-relevant fields from a fully-resolved compiler config.
1145
+ * @param validated The fully-resolved compiler config.
1146
+ * @returns A ProjectConfig with only the fields relevant to plugins and the wizard.
1147
+ * This is a stable subset of the compiler config that won't change between versions.
1148
+ */
1149
+ function toProjectConfig(validated) {
1150
+ return {
1151
+ rootDir: validated.rootDir,
1152
+ srcDir: validated.srcDir,
1153
+ namespace: validated.namespace,
1154
+ fsNamespace: validated.fsNamespace,
1155
+ outputTargets: validated.outputTargets ?? [],
1156
+ globalScript: validated.globalScript,
1157
+ globalStyle: validated.globalStyle,
1158
+ compat: validated.compat,
1159
+ signalBacking: validated.signalBacking
1160
+ };
1161
+ }
1162
+ /**
1163
+ * Builds a minimal ProjectConfig when no validated config is available (e.g. new project, no compiler).
1164
+ * @param rootDir The root directory of the project.
1165
+ * @param overrides Optional fields to override the defaults.
1166
+ * @returns A ProjectConfig with reasonable defaults for a new project.
1167
+ * */
1168
+ function defaultProjectConfig(rootDir, overrides) {
1169
+ const namespace = overrides?.namespace ?? "";
1170
+ return {
1171
+ rootDir,
1172
+ srcDir: join(rootDir, "src"),
1173
+ namespace,
1174
+ fsNamespace: overrides?.fsNamespace ?? namespace.toLowerCase(),
1175
+ outputTargets: [],
1176
+ ...overrides
1177
+ };
1178
+ }
1179
+ /**
1180
+ * Walk up from `startDir` looking for a monorepo workspace root — a directory
1181
+ * containing `pnpm-workspace.yaml` or a `package.json` with a `workspaces` field.
1182
+ * Stops at the home directory or filesystem root. Returns `undefined` if none found.
1183
+ * @param startDir The directory to start searching from.
1184
+ * @returns A promise that resolves to the workspace root directory, or undefined if none found.
1185
+ */
1186
+ async function detectWorkspaceRoot(startDir) {
1187
+ const home = homedir();
1188
+ let dir = startDir;
1189
+ while (true) {
1190
+ if (existsSync(join(dir, "pnpm-workspace.yaml"))) return dir;
1191
+ try {
1192
+ const pkg = JSON.parse(await readFile(join(dir, "package.json"), "utf8"));
1193
+ if (Array.isArray(pkg.workspaces)) return dir;
1194
+ } catch {}
1195
+ const parent = dirname(dir);
1196
+ if (parent === dir || dir === home) return void 0;
1197
+ dir = parent;
1198
+ }
1199
+ }
1200
+ /**
1201
+ * Returns true if the directory looks like an existing Stencil project:
1202
+ * - has an explicit `stencil.config.ts`, OR
1203
+ * - has `.tsx` files under `src/` (zero-config project).
1204
+ * @param dir The directory to check for an existing Stencil project.
1205
+ * @returns A promise that resolves to true if the directory looks like an existing Stencil project, false otherwise.
1206
+ */
1207
+ async function isExistingStencilProject(dir) {
1208
+ if (existsSync(join(dir, "stencil.config.ts"))) return true;
1209
+ try {
1210
+ return (await readdir(join(dir, "src"), {
1211
+ recursive: true,
1212
+ withFileTypes: true
1213
+ })).some((e) => e.isFile() && e.name.endsWith(".tsx"));
1214
+ } catch {
1215
+ return false;
1216
+ }
1217
+ }
1218
+ //#endregion
1219
+ //#region src/wizard/splash.ts
1220
+ const CLI_VERSION = "5.0.0-alpha.31";
1221
+ const isTTY = process.stdout.isTTY;
1222
+ const noColor = !isTTY || "NO_COLOR" in process.env;
1223
+ const RESET = noColor ? "" : "\x1B[0m";
1224
+ const BOLD = noColor ? "" : "\x1B[1m";
1225
+ const DIM = noColor ? "" : "\x1B[2m";
1226
+ const BLUE = noColor ? "" : "\x1B[38;2;60;44;255m";
1227
+ const RAW = `\
1228
+ .............
1229
+ ...................
1230
+ .........................
1231
+ ..............................
1232
+ .................................
1233
+ ..............████████████.........
1234
+ .............████████████............
1235
+ ............████████████...............
1236
+ ...........*************.................
1237
+ .........████████████████████████████....
1238
+ .......████████████████████████████......
1239
+ .....████████████████████████████........
1240
+ ...████████████████████████████..........
1241
+ ................*************............
1242
+ ..............████████████.............
1243
+ ............████████████..............
1244
+ .........████████████...............
1245
+ .................................
1246
+ ..............................
1247
+ ..........................
1248
+ ......................
1249
+ ................`;
1250
+ function colorize(raw) {
1251
+ if (noColor) return raw;
1252
+ let out = "";
1253
+ let style = "";
1254
+ for (const ch of raw) {
1255
+ const next = ".*".includes(ch) ? BLUE : "";
1256
+ if (next !== style) {
1257
+ if (style) out += RESET;
1258
+ if (next) out += next;
1259
+ style = next;
1260
+ }
1261
+ out += ch;
1262
+ }
1263
+ return style ? out + RESET : out;
1264
+ }
1265
+ const SPLASH = colorize(RAW);
1266
+ function printSplash() {
1267
+ if (!isTTY) return;
1268
+ const header = ` ${BOLD}Stencil${RESET} ${BLUE}v${CLI_VERSION}${RESET}`;
1269
+ const tagline = ` ${DIM}The Custom Element Compiler${RESET}`;
1270
+ process.stdout.write(`\n${SPLASH}\n\n${header}\n${tagline}\n\n`);
1271
+ }
1272
+ //#endregion
1273
+ //#region src/task-add.ts
1274
+ async function getInstalledPackageNames(rootDir) {
1275
+ try {
1276
+ const pkg = JSON.parse(await readFile(join(rootDir, "package.json"), "utf8"));
1277
+ const keys = (v) => Object.keys(v !== null && typeof v === "object" ? v : {});
1278
+ return /* @__PURE__ */ new Set([...keys(pkg.dependencies), ...keys(pkg.devDependencies)]);
1279
+ } catch {
1280
+ return /* @__PURE__ */ new Set();
1281
+ }
1282
+ }
1283
+ async function selectInteractive(cwd) {
1284
+ const discovered = await discoverPlugins(cwd);
1285
+ const installed = await getInstalledPackageNames(cwd);
1286
+ const installable = KNOWN_INTEGRATIONS.filter((i) => !installed.has(i.package));
1287
+ const configurable = discovered.filter((d) => d.plugin.init != null);
1288
+ let toInstall = [];
1289
+ let toConfigure = [];
1290
+ if (installable.length > 0 || configurable.length > 0) {
1291
+ const result = await promptAddCapabilities(installable, configurable);
1292
+ toInstall = result.toInstall;
1293
+ toConfigure = result.toConfigure;
1294
+ } else p.log.info("All known integrations are already installed.");
1295
+ const customPackages = await promptCustomPackages();
1296
+ return {
1297
+ packagesToInstall: [...toInstall.map((i) => i.package), ...customPackages],
1298
+ pluginsToReconfigure: toConfigure
1299
+ };
1300
+ }
1301
+ async function taskAdd(packages, strictConfig) {
1302
+ const cwd = process.cwd();
1303
+ printSplash();
1304
+ p.intro("stencil add");
1305
+ if (isCI) {
1306
+ p.log.warn("Running in CI - non-interactive mode is not yet supported for `stencil add`.");
1307
+ process.exit(1);
1308
+ }
1309
+ let packagesToInstall = packages;
1310
+ let pluginsToReconfigure = [];
1311
+ if (packages.length === 0) ({packagesToInstall, pluginsToReconfigure} = await selectInteractive(cwd));
1312
+ if (packagesToInstall.length === 0 && pluginsToReconfigure.length === 0) {
1313
+ p.outro("Nothing to do.");
1314
+ return;
1315
+ }
1316
+ if (packagesToInstall.length > 0) {
1317
+ if (process.env.STENCIL_WIZARD_DEV) p.log.warn(`Dev mode: skipping install, loading wizard from ${process.env.STENCIL_WIZARD_DEV}`);
1318
+ else {
1319
+ const s = p.spinner();
1320
+ s.start(`Installing ${packagesToInstall.join(", ")}`);
1321
+ await addDevDependency(withVersionRanges(packagesToInstall), {
1322
+ cwd,
1323
+ silent: true
1324
+ });
1325
+ s.stop("Installed");
1326
+ }
1327
+ }
1328
+ const config = strictConfig ? toProjectConfig(strictConfig) : defaultProjectConfig(cwd);
1329
+ const workspaceRoot = await detectWorkspaceRoot(cwd);
1330
+ const context = {
1331
+ isNewProject: false,
1332
+ prompts: p,
1333
+ nypm,
1334
+ config,
1335
+ workspaceRoot,
1336
+ ts,
1337
+ openStencilConfig: () => openStencilConfig(join(config.rootDir, "stencil.config.ts"))
1338
+ };
1339
+ if (packagesToInstall.length > 0) {
1340
+ const discovered = await discoverPlugins(cwd);
1341
+ const installedSet = new Set(packagesToInstall);
1342
+ for (const d of discovered) if (installedSet.has(d.packageName) && d.plugin.init?.run) await d.plugin.init.run(context);
1343
+ }
1344
+ for (const d of pluginsToReconfigure) if (d.plugin.init?.run) await d.plugin.init.run(context);
1345
+ p.outro("Done!");
1346
+ }
1347
+ //#endregion
595
1348
  //#region src/check-version.ts
596
1349
  /**
597
1350
  * Retrieve a reference to the active `CompilerSystem`'s `checkVersion` function
@@ -618,43 +1371,36 @@ const printCheckVersionResults = async (versionChecker) => {
618
1371
  }
619
1372
  };
620
1373
  //#endregion
621
- //#region src/migrations/rules/encapsulation-api.ts
1374
+ //#region src/migrations/rules/build-dist-docs.ts
622
1375
  /**
623
- * Migration rule for the @Component encapsulation API change.
1376
+ * Migration rule for buildDist and buildDocs removal.
624
1377
  *
625
- * Migrates:
626
- * - `shadow: true` → `encapsulation: { type: 'shadow' }`
627
- * - `shadow: { delegatesFocus: true }` → `encapsulation: { type: 'shadow', delegatesFocus: true }`
628
- * - `scoped: true` → `encapsulation: { type: 'scoped' }`
1378
+ * In Stencil v5, these global config options are replaced with per-output-target
1379
+ * `skipInDev` property. This migration:
1380
+ * - Detects `buildDist` or `buildDocs` in stencil.config.ts
1381
+ * - Removes the property
1382
+ * - For `buildDist: true` or `buildDocs: true`, adds `skipInDev: false` to relevant output targets
629
1383
  */
630
- const encapsulationApiRule = {
631
- id: "encapsulation-api",
632
- name: "Encapsulation API",
633
- description: "Migrate shadow/scoped properties to new encapsulation API",
1384
+ const buildDistDocsRule = {
1385
+ id: "build-dist-docs",
1386
+ name: "buildDist/buildDocs Removal",
1387
+ description: "Remove deprecated buildDist and buildDocs config options",
634
1388
  fromVersion: "4.x",
635
1389
  toVersion: "5.x",
636
1390
  detect(sourceFile) {
637
1391
  const matches = [];
638
- const importMap = getStencilCoreImportMap(sourceFile);
639
1392
  const visit = (node) => {
640
- if (ts.isDecorator(node) && ts.isCallExpression(node.expression)) {
641
- const decoratorName = node.expression.expression;
642
- if (ts.isIdentifier(decoratorName) && isStencilDecorator(decoratorName.text, "Component", importMap)) {
643
- const [arg] = node.expression.arguments;
644
- if (arg && ts.isObjectLiteralExpression(arg)) {
645
- for (const prop of arg.properties) if (ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.name)) {
646
- const propName = prop.name.text;
647
- if (propName === "shadow" || propName === "scoped") {
648
- const { line, character } = sourceFile.getLineAndCharacterOfPosition(prop.getStart());
649
- matches.push({
650
- node: prop,
651
- message: `Deprecated '${propName}' property found - migrate to 'encapsulation' API`,
652
- line: line + 1,
653
- column: character + 1
654
- });
655
- }
656
- }
657
- }
1393
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name)) {
1394
+ const propName = node.name.text;
1395
+ if (propName === "buildDist" || propName === "buildDocs") {
1396
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
1397
+ const isTrue = node.initializer.kind === ts.SyntaxKind.TrueKeyword;
1398
+ matches.push({
1399
+ node,
1400
+ message: `Deprecated '${propName}' found${isTrue ? " (set to true)" : ""} - will be removed and skipInDev added to output targets`,
1401
+ line: line + 1,
1402
+ column: character + 1
1403
+ });
658
1404
  }
659
1405
  }
660
1406
  ts.forEachChild(node, visit);
@@ -665,38 +1411,435 @@ const encapsulationApiRule = {
665
1411
  transform(sourceFile, matches) {
666
1412
  if (matches.length === 0) return sourceFile.getFullText();
667
1413
  let text = sourceFile.getFullText();
668
- const sortedMatches = [...matches].sort((a, b) => {
669
- const posA = a.node.getStart();
670
- return b.node.getStart() - posA;
671
- });
672
- for (const match of sortedMatches) {
1414
+ const targetTypesNeedingSkipInDev = [];
1415
+ for (const match of matches) {
673
1416
  const prop = match.node;
674
1417
  const propName = prop.name.text;
675
- const start = prop.getStart();
676
- const end = prop.getEnd();
677
- let replacement;
678
- if (propName === "shadow") if (prop.initializer.kind === ts.SyntaxKind.TrueKeyword) replacement = "encapsulation: { type: 'shadow' }";
679
- else if (ts.isObjectLiteralExpression(prop.initializer)) {
680
- const options = [];
681
- for (const innerProp of prop.initializer.properties) if (ts.isPropertyAssignment(innerProp) && ts.isIdentifier(innerProp.name)) {
682
- const optName = innerProp.name.text;
683
- const optValue = innerProp.initializer.getText();
684
- options.push(`${optName}: ${optValue}`);
1418
+ if (prop.initializer.kind === ts.SyntaxKind.TrueKeyword) {
1419
+ if (propName === "buildDist") targetTypesNeedingSkipInDev.push("dist", "dist-custom-elements", "dist-hydrate-script", "loader-bundle", "standalone", "ssr");
1420
+ else if (propName === "buildDocs") targetTypesNeedingSkipInDev.push("docs-readme", "docs-json", "docs-custom", "docs-vscode", "docs-custom-elements-manifest");
1421
+ }
1422
+ }
1423
+ const outputTargetsToModify = [];
1424
+ const findOutputTargets = (node) => {
1425
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === "outputTargets" && ts.isArrayLiteralExpression(node.initializer)) {
1426
+ for (const element of node.initializer.elements) if (ts.isObjectLiteralExpression(element)) {
1427
+ const typeProp = element.properties.find((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "type");
1428
+ if (typeProp && ts.isStringLiteral(typeProp.initializer)) {
1429
+ const targetType = typeProp.initializer.text;
1430
+ if (targetTypesNeedingSkipInDev.includes(targetType)) {
1431
+ if (!element.properties.some((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "skipInDev")) outputTargetsToModify.push(element);
1432
+ }
1433
+ }
685
1434
  }
686
- if (options.length > 0) replacement = `encapsulation: { type: 'shadow', ${options.join(", ")} }`;
687
- else replacement = "encapsulation: { type: 'shadow' }";
688
- } else replacement = "";
689
- else if (propName === "scoped") if (prop.initializer.kind === ts.SyntaxKind.TrueKeyword) replacement = "encapsulation: { type: 'scoped' }";
690
- else replacement = "";
691
- else continue;
692
- let endPos = end;
1435
+ }
1436
+ ts.forEachChild(node, findOutputTargets);
1437
+ };
1438
+ findOutputTargets(sourceFile);
1439
+ const allModifications = [];
1440
+ for (const match of matches) {
1441
+ const prop = match.node;
1442
+ const start = prop.getStart();
1443
+ let end = prop.getEnd();
693
1444
  const afterProp = text.slice(end).match(/^\s*,/);
694
- if (afterProp && replacement === "") endPos = end + afterProp[0].length;
695
- else if (afterProp && replacement !== "") {} else if (!afterProp && replacement !== "") {}
696
- text = text.slice(0, start) + replacement + text.slice(endPos);
1445
+ if (afterProp) end = end + afterProp[0].length;
1446
+ allModifications.push({
1447
+ type: "remove",
1448
+ start,
1449
+ end,
1450
+ node: prop
1451
+ });
697
1452
  }
698
- return text;
699
- }
1453
+ for (const target of outputTargetsToModify) {
1454
+ const lastProp = target.properties[target.properties.length - 1];
1455
+ if (lastProp) allModifications.push({
1456
+ type: "addSkipInDev",
1457
+ start: lastProp.getEnd(),
1458
+ end: lastProp.getEnd(),
1459
+ node: target
1460
+ });
1461
+ }
1462
+ allModifications.sort((a, b) => b.start - a.start);
1463
+ for (const mod of allModifications) if (mod.type === "remove") text = text.slice(0, mod.start) + text.slice(mod.end);
1464
+ else if (mod.type === "addSkipInDev") {
1465
+ const firstProp = mod.node.properties[0];
1466
+ let indent = " ";
1467
+ if (firstProp) {
1468
+ const propStart = firstProp.getStart();
1469
+ const lineStart = text.lastIndexOf("\n", propStart) + 1;
1470
+ const leadingWhitespace = text.slice(lineStart, propStart);
1471
+ if (/^\s+$/.test(leadingWhitespace)) indent = leadingWhitespace;
1472
+ }
1473
+ const afterLastProp = text.slice(mod.start).match(/^(\s*,)?/);
1474
+ const skipLength = afterLastProp && afterLastProp[1] ? afterLastProp[0].length : 0;
1475
+ text = text.slice(0, mod.start) + `,\n${indent}skipInDev: false,` + text.slice(mod.start + skipLength);
1476
+ }
1477
+ text = text.replace(/,\s*\n\s*\n/g, ",\n");
1478
+ text = text.replace(/{\s*\n\s*\n/g, "{\n");
1479
+ return text;
1480
+ }
1481
+ };
1482
+ //#endregion
1483
+ //#region src/migrations/rules/css-import-query-param.ts
1484
+ /**
1485
+ * Ambient module extensions Stencil declares its own type for. In v5 these
1486
+ * now require a `?stencil` query-param marker (see `stencil-ext-modules.d.ts`)
1487
+ * so the ambient declaration doesn't clash with other `*.css` etc. typings in
1488
+ * a monorepo.
1489
+ */
1490
+ const AMBIENT_ASSET_EXTS = [
1491
+ ".css",
1492
+ ".svg",
1493
+ ".txt",
1494
+ ".frag",
1495
+ ".vert"
1496
+ ];
1497
+ const needsStencilMarker = (specifier) => {
1498
+ if (specifier.includes("?")) return false;
1499
+ const lower = specifier.toLowerCase();
1500
+ return AMBIENT_ASSET_EXTS.some((ext) => lower.endsWith(ext));
1501
+ };
1502
+ /**
1503
+ * Migration rule appending `?stencil` to raw asset import specifiers.
1504
+ *
1505
+ * Migrates:
1506
+ * - `import styles from './my-component.css'` → `import styles from './my-component.css?stencil'`
1507
+ * - `import logo from './logo.svg'` → `import logo from './logo.svg?stencil'`
1508
+ *
1509
+ * Does not touch `styleUrl`/`styleUrls` values in `@Component()` options - those are
1510
+ * compiler-resolved filenames, not import specifiers, and are never typed against the
1511
+ * ambient module declarations.
1512
+ */
1513
+ const cssImportQueryParamRule = {
1514
+ id: "css-import-query-param",
1515
+ name: "Asset Import Query Param",
1516
+ description: "Append '?stencil' to raw *.css/*.svg/*.txt/*.frag/*.vert imports so they match Stencil's ambient module types",
1517
+ fromVersion: "4.x",
1518
+ toVersion: "5.x",
1519
+ detect(sourceFile) {
1520
+ const matches = [];
1521
+ const visit = (node) => {
1522
+ let specifierNode;
1523
+ if ((ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) && node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) specifierNode = node.moduleSpecifier;
1524
+ else if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword && node.arguments.length > 0 && ts.isStringLiteral(node.arguments[0])) specifierNode = node.arguments[0];
1525
+ if (specifierNode && needsStencilMarker(specifierNode.text)) {
1526
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(specifierNode.getStart());
1527
+ matches.push({
1528
+ node: specifierNode,
1529
+ message: `Raw asset import '${specifierNode.text}' needs a '?stencil' suffix to match Stencil's ambient module type`,
1530
+ line: line + 1,
1531
+ column: character + 1
1532
+ });
1533
+ }
1534
+ ts.forEachChild(node, visit);
1535
+ };
1536
+ visit(sourceFile);
1537
+ return matches;
1538
+ },
1539
+ transform(sourceFile, matches) {
1540
+ if (matches.length === 0) return sourceFile.getFullText();
1541
+ let text = sourceFile.getFullText();
1542
+ const sortedMatches = [...matches].sort((a, b) => b.node.getStart() - a.node.getStart());
1543
+ for (const match of sortedMatches) {
1544
+ const node = match.node;
1545
+ const start = node.getStart();
1546
+ const end = node.getEnd();
1547
+ const quote = node.getText(sourceFile)[0];
1548
+ const updated = `${quote}${node.text}?stencil${quote}`;
1549
+ text = text.slice(0, start) + updated + text.slice(end);
1550
+ }
1551
+ return text;
1552
+ }
1553
+ };
1554
+ //#endregion
1555
+ //#region src/migrations/rules/dev-mode.ts
1556
+ /**
1557
+ * Migration rule for `devMode` config option removal.
1558
+ *
1559
+ * In Stencil v5, `devMode` is no longer a user-settable config option in `stencil.config.ts`.
1560
+ * Build mode is controlled exclusively by the `--dev` CLI flag (default is production).
1561
+ * This migration removes `devMode` from the config object.
1562
+ */
1563
+ const devModeRule = {
1564
+ id: "dev-mode",
1565
+ name: "devMode Config Removal",
1566
+ description: "Remove deprecated devMode config option - use --dev CLI flag instead",
1567
+ fromVersion: "4.x",
1568
+ toVersion: "5.x",
1569
+ detect(sourceFile) {
1570
+ const matches = [];
1571
+ const visit = (node) => {
1572
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name)) {
1573
+ if (node.name.text === "devMode") {
1574
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
1575
+ matches.push({
1576
+ node,
1577
+ message: `Deprecated 'devMode' config option found - build mode is now set via the --dev CLI flag (production is the default)`,
1578
+ line: line + 1,
1579
+ column: character + 1
1580
+ });
1581
+ }
1582
+ }
1583
+ ts.forEachChild(node, visit);
1584
+ };
1585
+ visit(sourceFile);
1586
+ return matches;
1587
+ },
1588
+ transform(sourceFile, matches) {
1589
+ if (matches.length === 0) return sourceFile.getFullText();
1590
+ let text = sourceFile.getFullText();
1591
+ for (const match of [...matches].reverse()) {
1592
+ const node = match.node;
1593
+ const start = node.getFullStart();
1594
+ const end = node.getEnd();
1595
+ let removeEnd = end;
1596
+ const trailingComma = text.slice(end).match(/^\s*,/);
1597
+ if (trailingComma) removeEnd = end + trailingComma[0].length;
1598
+ text = text.slice(0, start) + text.slice(removeEnd);
1599
+ }
1600
+ return text;
1601
+ }
1602
+ };
1603
+ //#endregion
1604
+ //#region src/migrations/rules/enable-import-injection-default.ts
1605
+ /**
1606
+ * Migration rule: drop `extras.enableImportInjection: true`.
1607
+ *
1608
+ * In v4 this flag defaulted to `false`, so an explicit `true` was meaningful. In v5 it
1609
+ * defaults to `true`, so an explicit `true` is now a no-op. `false` (opting out) is left alone.
1610
+ */
1611
+ const enableImportInjectionDefaultRule = {
1612
+ id: "enable-import-injection-default",
1613
+ name: "Drop redundant enableImportInjection: true",
1614
+ description: "Remove 'extras.enableImportInjection: true' now that it's the v5 default",
1615
+ fromVersion: "4.x",
1616
+ toVersion: "5.x",
1617
+ detect(sourceFile) {
1618
+ const matches = [];
1619
+ const visit = (node) => {
1620
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === "enableImportInjection" && node.initializer.kind === ts.SyntaxKind.TrueKeyword) {
1621
+ const parent = node.parent;
1622
+ if (ts.isObjectLiteralExpression(parent)) {
1623
+ const grandparent = parent.parent;
1624
+ if (ts.isPropertyAssignment(grandparent) && ts.isIdentifier(grandparent.name) && grandparent.name.text === "extras") {
1625
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
1626
+ matches.push({
1627
+ node,
1628
+ message: "'extras.enableImportInjection: true' is now the default and can be removed",
1629
+ line: line + 1,
1630
+ column: character + 1
1631
+ });
1632
+ }
1633
+ }
1634
+ }
1635
+ ts.forEachChild(node, visit);
1636
+ };
1637
+ visit(sourceFile);
1638
+ return matches;
1639
+ },
1640
+ transform(sourceFile, matches) {
1641
+ if (matches.length === 0) return sourceFile.getFullText();
1642
+ let text = sourceFile.getFullText();
1643
+ const sorted = [...matches].sort((a, b) => b.node.getStart() - a.node.getStart());
1644
+ for (const match of sorted) {
1645
+ const node = match.node;
1646
+ let start = node.getStart();
1647
+ let end = node.getEnd();
1648
+ const trailingComma = text.slice(end).match(/^(\s*,)/);
1649
+ if (trailingComma) end += trailingComma[1].length;
1650
+ else {
1651
+ const leadingComma = text.slice(0, start).match(/,\s*$/);
1652
+ if (leadingComma) start -= leadingComma[0].length;
1653
+ }
1654
+ text = text.slice(0, start) + text.slice(end);
1655
+ }
1656
+ text = cleanupEmptyExtras$2(text);
1657
+ return text;
1658
+ }
1659
+ };
1660
+ function cleanupEmptyExtras$2(text) {
1661
+ return text.replace(/,?\s*extras\s*:\s*\{\s*\},?/g, "");
1662
+ }
1663
+ //#endregion
1664
+ //#region src/migrations/rules/encapsulation-api.ts
1665
+ /**
1666
+ * Migration rule for the @Component encapsulation API change.
1667
+ *
1668
+ * Migrates:
1669
+ * - `shadow: true` → `encapsulation: { type: 'shadow' }`
1670
+ * - `shadow: { delegatesFocus: true }` → `encapsulation: { type: 'shadow', delegatesFocus: true }`
1671
+ * - `scoped: true` → `encapsulation: { type: 'scoped' }`
1672
+ */
1673
+ const encapsulationApiRule = {
1674
+ id: "encapsulation-api",
1675
+ name: "Encapsulation API",
1676
+ description: "Migrate shadow/scoped properties to new encapsulation API",
1677
+ fromVersion: "4.x",
1678
+ toVersion: "5.x",
1679
+ detect(sourceFile) {
1680
+ const matches = [];
1681
+ const importMap = getStencilCoreImportMap(sourceFile);
1682
+ const visit = (node) => {
1683
+ if (ts.isDecorator(node) && ts.isCallExpression(node.expression)) {
1684
+ const decoratorName = node.expression.expression;
1685
+ if (ts.isIdentifier(decoratorName) && isStencilDecorator(decoratorName.text, "Component", importMap)) {
1686
+ const [arg] = node.expression.arguments;
1687
+ if (arg && ts.isObjectLiteralExpression(arg)) {
1688
+ for (const prop of arg.properties) if (ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.name)) {
1689
+ const propName = prop.name.text;
1690
+ if (propName === "shadow" || propName === "scoped") {
1691
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(prop.getStart());
1692
+ matches.push({
1693
+ node: prop,
1694
+ message: `Deprecated '${propName}' property found - migrate to 'encapsulation' API`,
1695
+ line: line + 1,
1696
+ column: character + 1
1697
+ });
1698
+ }
1699
+ }
1700
+ }
1701
+ }
1702
+ }
1703
+ ts.forEachChild(node, visit);
1704
+ };
1705
+ visit(sourceFile);
1706
+ return matches;
1707
+ },
1708
+ transform(sourceFile, matches) {
1709
+ if (matches.length === 0) return sourceFile.getFullText();
1710
+ let text = sourceFile.getFullText();
1711
+ const sortedMatches = [...matches].sort((a, b) => {
1712
+ const posA = a.node.getStart();
1713
+ return b.node.getStart() - posA;
1714
+ });
1715
+ for (const match of sortedMatches) {
1716
+ const prop = match.node;
1717
+ const propName = prop.name.text;
1718
+ const start = prop.getStart();
1719
+ const end = prop.getEnd();
1720
+ let replacement;
1721
+ if (propName === "shadow") {
1722
+ if (prop.initializer.kind === ts.SyntaxKind.TrueKeyword) replacement = "encapsulation: { type: 'shadow' }";
1723
+ else if (ts.isObjectLiteralExpression(prop.initializer)) {
1724
+ const options = [];
1725
+ for (const innerProp of prop.initializer.properties) if (ts.isPropertyAssignment(innerProp) && ts.isIdentifier(innerProp.name)) {
1726
+ const optName = innerProp.name.text;
1727
+ const optValue = innerProp.initializer.getText();
1728
+ options.push(`${optName}: ${optValue}`);
1729
+ }
1730
+ if (options.length > 0) replacement = `encapsulation: { type: 'shadow', ${options.join(", ")} }`;
1731
+ else replacement = "encapsulation: { type: 'shadow' }";
1732
+ } else replacement = "";
1733
+ } else if (propName === "scoped") {
1734
+ if (prop.initializer.kind === ts.SyntaxKind.TrueKeyword) replacement = "encapsulation: { type: 'scoped' }";
1735
+ else replacement = "";
1736
+ } else continue;
1737
+ let endPos = end;
1738
+ const afterProp = text.slice(end).match(/^\s*,/);
1739
+ if (afterProp && replacement === "") endPos = end + afterProp[0].length;
1740
+ else if (afterProp && replacement !== "") {} else if (!afterProp && replacement !== "") {}
1741
+ text = text.slice(0, start) + replacement + text.slice(endPos);
1742
+ }
1743
+ return text;
1744
+ }
1745
+ };
1746
+ //#endregion
1747
+ //#region src/migrations/rules/external-runtime.ts
1748
+ /**
1749
+ * Migration rule for `externalRuntime` on `standalone` output targets.
1750
+ *
1751
+ * In Stencil v5, `externalRuntime` defaults to `false` (was `true` in v4).
1752
+ * Explicit `externalRuntime: false` is now redundant and can be removed.
1753
+ */
1754
+ const externalRuntimeRule = {
1755
+ id: "external-runtime",
1756
+ name: "externalRuntime Default Change",
1757
+ description: "Remove redundant 'externalRuntime: false' from standalone output targets - false is now the default",
1758
+ fromVersion: "4.x",
1759
+ toVersion: "5.x",
1760
+ detect(sourceFile) {
1761
+ const matches = [];
1762
+ const visit = (node) => {
1763
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === "externalRuntime" && node.initializer.kind === ts.SyntaxKind.FalseKeyword) {
1764
+ const parent = node.parent;
1765
+ if (ts.isObjectLiteralExpression(parent)) {
1766
+ if (parent.properties.some((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "type" && ts.isStringLiteral(p.initializer) && p.initializer.text === "standalone")) {
1767
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
1768
+ matches.push({
1769
+ node,
1770
+ message: "'externalRuntime: false' is now the default - this property can be removed",
1771
+ line: line + 1,
1772
+ column: character + 1
1773
+ });
1774
+ }
1775
+ }
1776
+ }
1777
+ ts.forEachChild(node, visit);
1778
+ };
1779
+ visit(sourceFile);
1780
+ return matches;
1781
+ },
1782
+ transform(sourceFile, matches) {
1783
+ if (matches.length === 0) return sourceFile.getFullText();
1784
+ let text = sourceFile.getFullText();
1785
+ for (const match of [...matches].reverse()) {
1786
+ const node = match.node;
1787
+ const start = node.getFullStart();
1788
+ const end = node.getEnd();
1789
+ let removeEnd = end;
1790
+ const trailingComma = text.slice(end).match(/^\s*,/);
1791
+ if (trailingComma) removeEnd = end + trailingComma[0].length;
1792
+ text = text.slice(0, start) + text.slice(removeEnd);
1793
+ }
1794
+ return text;
1795
+ }
1796
+ };
1797
+ //#endregion
1798
+ //#region src/migrations/rules/extras-to-compat.ts
1799
+ /**
1800
+ * Migration rule: rename the top-level `extras` config key to `compat`.
1801
+ *
1802
+ * In v5, `extras` is replaced by `compat` (framework/bundler compatibility flags).
1803
+ */
1804
+ const extrasToCompatRule = {
1805
+ id: "extras-to-compat",
1806
+ name: "Extras → Compat Rename",
1807
+ description: "Rename top-level 'extras' config key to 'compat'",
1808
+ fromVersion: "4.x",
1809
+ toVersion: "5.x",
1810
+ detect(sourceFile) {
1811
+ const matches = [];
1812
+ const visit = (node) => {
1813
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name)) {
1814
+ if (node.name.text === "extras") {
1815
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
1816
+ matches.push({
1817
+ node,
1818
+ message: "'extras' has been renamed to 'compat'",
1819
+ line: line + 1,
1820
+ column: character + 1
1821
+ });
1822
+ }
1823
+ }
1824
+ ts.forEachChild(node, visit);
1825
+ };
1826
+ visit(sourceFile);
1827
+ return matches;
1828
+ },
1829
+ transform(sourceFile, matches) {
1830
+ if (matches.length === 0) return sourceFile.getFullText();
1831
+ let text = sourceFile.getFullText();
1832
+ const sorted = [...matches].sort((a, b) => b.node.getStart() - a.node.getStart());
1833
+ for (const match of sorted) {
1834
+ const node = match.node;
1835
+ if (node.name.text === "extras") {
1836
+ const keyStart = node.name.getStart();
1837
+ const keyEnd = node.name.getEnd();
1838
+ text = text.slice(0, keyStart) + "compat" + text.slice(keyEnd);
1839
+ }
1840
+ }
1841
+ return text;
1842
+ }
700
1843
  };
701
1844
  //#endregion
702
1845
  //#region src/migrations/rules/form-associated.ts
@@ -763,25 +1906,838 @@ const formAssociatedRule = {
763
1906
  ts.forEachChild(node, visit);
764
1907
  return;
765
1908
  }
766
- const classBodyStart = searchStart + braceMatch[0].length;
767
- let indent = " ";
768
- if (node.members.length > 0) {
769
- const memberStart = node.members[0].getStart(sourceFile);
770
- const indentMatch = sourceFile.getFullText().slice(classBodyStart, memberStart).match(/\n(\s+)/);
771
- if (indentMatch) indent = indentMatch[1];
1909
+ const classBodyStart = searchStart + braceMatch[0].length;
1910
+ let indent = " ";
1911
+ if (node.members.length > 0) {
1912
+ const memberStart = node.members[0].getStart(sourceFile);
1913
+ const indentMatch = sourceFile.getFullText().slice(classBodyStart, memberStart).match(/\n(\s+)/);
1914
+ if (indentMatch) indent = indentMatch[1];
1915
+ }
1916
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(formAssociatedProp.getStart());
1917
+ matches.push({
1918
+ node: formAssociatedProp,
1919
+ message: hasAttachInternals ? "Remove 'formAssociated' (already has @AttachInternals)" : "Migrate 'formAssociated' to @AttachInternals decorator",
1920
+ line: line + 1,
1921
+ column: character + 1,
1922
+ classBodyStart,
1923
+ hasAttachInternals,
1924
+ indent,
1925
+ needsImport: !hasAttachInternalsImport && !hasAttachInternals,
1926
+ stencilImportEnd
1927
+ });
1928
+ }
1929
+ }
1930
+ ts.forEachChild(node, visit);
1931
+ };
1932
+ visit(sourceFile);
1933
+ return matches;
1934
+ },
1935
+ transform(sourceFile, matches) {
1936
+ if (matches.length === 0) return sourceFile.getFullText();
1937
+ let text = sourceFile.getFullText();
1938
+ const typedMatches = matches;
1939
+ const sortedMatches = [...typedMatches].sort((a, b) => {
1940
+ return b.classBodyStart - a.classBodyStart;
1941
+ });
1942
+ for (const match of sortedMatches) {
1943
+ if (!match.hasAttachInternals) {
1944
+ const newMember = `\n${match.indent}@AttachInternals() internals: ElementInternals;\n`;
1945
+ text = text.slice(0, match.classBodyStart) + newMember + text.slice(match.classBodyStart);
1946
+ }
1947
+ const prop = match.node;
1948
+ const start = prop.getStart();
1949
+ let end = prop.getEnd();
1950
+ const afterProp = text.slice(end).match(/^\s*,/);
1951
+ if (afterProp) end = end + afterProp[0].length;
1952
+ text = text.slice(0, start) + text.slice(end);
1953
+ }
1954
+ const firstMatch = typedMatches[0];
1955
+ if (firstMatch?.needsImport && firstMatch.stencilImportEnd > 0) {
1956
+ const importMatch = text.match(/import\s*\{([^}]*)\}\s*from\s*['"]@stencil\/core['"]/);
1957
+ if (importMatch) {
1958
+ const newImports = importMatch[1].trimEnd() + ", AttachInternals";
1959
+ text = text.replace(importMatch[0], `import {${newImports}} from '@stencil/core'`);
1960
+ }
1961
+ }
1962
+ return text;
1963
+ }
1964
+ };
1965
+ //#endregion
1966
+ //#region src/migrations/rules/global-style-inject.ts
1967
+ /**
1968
+ * Migration rule for `extras.addGlobalStyleToComponents` → `global-style` output target `inject`.
1969
+ *
1970
+ * In v5, the `addGlobalStyleToComponents` extras option is removed. Instead, configure
1971
+ * the `inject` option on the `global-style` output target.
1972
+ *
1973
+ * Migration mapping:
1974
+ * - `addGlobalStyleToComponents: true` → `inject: 'all'`
1975
+ * - `addGlobalStyleToComponents: 'client'` → `inject: 'client'`
1976
+ * - `addGlobalStyleToComponents: false` → omit (default is 'none')
1977
+ *
1978
+ * Note: This migration only acts on explicitly set `addGlobalStyleToComponents`.
1979
+ * Users who relied on the implicit v4 default ('client') will need to manually
1980
+ * add `inject: 'client'` to their global-style output target if desired.
1981
+ */
1982
+ const globalStyleInjectRule = {
1983
+ id: "global-style-inject",
1984
+ name: "Global Style Inject Migration",
1985
+ description: "Migrate extras.addGlobalStyleToComponents to global-style output target inject option",
1986
+ fromVersion: "4.x",
1987
+ toVersion: "5.x",
1988
+ detect(sourceFile) {
1989
+ const matches = [];
1990
+ const visit = (node) => {
1991
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === "addGlobalStyleToComponents") {
1992
+ const parent = node.parent;
1993
+ if (ts.isObjectLiteralExpression(parent)) {
1994
+ const grandparent = parent.parent;
1995
+ if (ts.isPropertyAssignment(grandparent) && ts.isIdentifier(grandparent.name) && grandparent.name.text === "extras") {
1996
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
1997
+ matches.push({
1998
+ node,
1999
+ message: `extras.addGlobalStyleToComponents is removed. Use 'inject' on global-style output target instead.`,
2000
+ line: line + 1,
2001
+ column: character + 1
2002
+ });
2003
+ }
2004
+ }
2005
+ }
2006
+ ts.forEachChild(node, visit);
2007
+ };
2008
+ visit(sourceFile);
2009
+ return matches;
2010
+ },
2011
+ transform(sourceFile, matches) {
2012
+ if (matches.length === 0) return sourceFile.getFullText();
2013
+ let text = sourceFile.getFullText();
2014
+ const matchNode = matches[0].node;
2015
+ if (!ts.isPropertyAssignment(matchNode)) return text;
2016
+ let injectValue = null;
2017
+ if (matchNode.initializer.kind === ts.SyntaxKind.TrueKeyword) injectValue = "all";
2018
+ else if (ts.isStringLiteral(matchNode.initializer) && matchNode.initializer.text === "client") injectValue = "client";
2019
+ let insertionOffset = 0;
2020
+ if (injectValue) {
2021
+ const result = addGlobalStyleOutputTarget(text, sourceFile, injectValue);
2022
+ insertionOffset = result.length - text.length;
2023
+ text = result;
2024
+ }
2025
+ let start = matchNode.getStart();
2026
+ let end = matchNode.getEnd();
2027
+ const outputTargetsEnd = findOutputTargetsEnd(sourceFile);
2028
+ if (insertionOffset !== 0 && outputTargetsEnd !== null && matchNode.getStart() > outputTargetsEnd) {
2029
+ start += insertionOffset;
2030
+ end += insertionOffset;
2031
+ }
2032
+ const afterProp = text.slice(end).match(/^\s*,/);
2033
+ if (afterProp) end = end + afterProp[0].length;
2034
+ else {
2035
+ const beforeProp = text.slice(0, start).match(/,\s*$/);
2036
+ if (beforeProp) {
2037
+ text = text.slice(0, start - beforeProp[0].length) + text.slice(end);
2038
+ end = -1;
2039
+ }
2040
+ }
2041
+ if (end !== -1) text = text.slice(0, start) + text.slice(end);
2042
+ text = cleanupEmptyExtras$1(text);
2043
+ return text;
2044
+ }
2045
+ };
2046
+ /**
2047
+ * Find the end position of the outputTargets array in the source file.
2048
+ * @param sourceFile The source file to search
2049
+ * @returns The end position of the outputTargets array, or null if not found
2050
+ */
2051
+ function findOutputTargetsEnd(sourceFile) {
2052
+ let endPos = null;
2053
+ const visit = (node) => {
2054
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === "outputTargets") endPos = node.getEnd();
2055
+ ts.forEachChild(node, visit);
2056
+ };
2057
+ visit(sourceFile);
2058
+ return endPos;
2059
+ }
2060
+ /**
2061
+ * Clean up empty extras object after removing addGlobalStyleToComponents.
2062
+ * @param text The source text to clean up
2063
+ * @returns The cleaned up text with empty extras removed
2064
+ */
2065
+ function cleanupEmptyExtras$1(text) {
2066
+ return text.replace(/,?\s*extras\s*:\s*\{\s*\},?/g, "");
2067
+ }
2068
+ /**
2069
+ * Add a global-style output target with the specified inject value.
2070
+ * @param text The source text to modify
2071
+ * @param sourceFile The source file for position info
2072
+ * @param injectValue The inject value to set on the new global-style output target
2073
+ * @returns The modified text with the new global-style output target added
2074
+ */
2075
+ function addGlobalStyleOutputTarget(text, sourceFile, injectValue) {
2076
+ if (text.includes("type: 'global-style'")) return text;
2077
+ let outputTargetsArray = null;
2078
+ const findOutputTargets = (node) => {
2079
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === "outputTargets" && ts.isArrayLiteralExpression(node.initializer)) outputTargetsArray = node.initializer;
2080
+ ts.forEachChild(node, findOutputTargets);
2081
+ };
2082
+ findOutputTargets(sourceFile);
2083
+ if (!outputTargetsArray) return text;
2084
+ const array = outputTargetsArray;
2085
+ let indent = " ";
2086
+ if (array.elements.length > 0) {
2087
+ const elemStart = array.elements[0].getStart();
2088
+ const lineStart = text.lastIndexOf("\n", elemStart) + 1;
2089
+ const leadingWhitespace = text.slice(lineStart, elemStart);
2090
+ if (/^\s+$/.test(leadingWhitespace)) indent = leadingWhitespace;
2091
+ }
2092
+ const lastElement = array.elements[array.elements.length - 1];
2093
+ if (!lastElement) {
2094
+ const arrayStart = array.getStart() + 1;
2095
+ const newTarget = `\n${indent}{\n${indent} type: 'global-style',\n${indent} inject: '${injectValue}',\n${indent}}\n${indent.slice(2)}`;
2096
+ return text.slice(0, arrayStart) + newTarget + text.slice(arrayStart);
2097
+ }
2098
+ let insertPos = lastElement.getEnd();
2099
+ const afterLastElement = text.slice(insertPos).match(/^(\s*,)?/);
2100
+ const hasTrailingComma = afterLastElement && afterLastElement[1];
2101
+ if (hasTrailingComma) insertPos += afterLastElement[0].length;
2102
+ const newTarget = `{\n${indent} type: 'global-style',\n${indent} inject: '${injectValue}',\n${indent}}`;
2103
+ const insertion = (hasTrailingComma ? "" : ",") + "\n" + indent + newTarget;
2104
+ return text.slice(0, insertPos) + insertion + text.slice(insertPos);
2105
+ }
2106
+ //#endregion
2107
+ //#region src/migrations/rules/hash-file-names.ts
2108
+ /**
2109
+ * Migration rule for `hashFileNames` and `hashedFileNameLength` config options.
2110
+ *
2111
+ * In Stencil v5, these are no longer top-level config options. They belong on
2112
+ * the `loader-bundle` and `www` output targets, which are the only outputs that
2113
+ * are served directly in the browser and benefit from content-hash caching.
2114
+ *
2115
+ * This migration:
2116
+ * 1. Removes them from the top-level config
2117
+ * 2. Injects them into any `loader-bundle` and `www` output targets found in the same file
2118
+ */
2119
+ const hashFileNamesRule = {
2120
+ id: "hash-file-names",
2121
+ name: "Hash File Names Config Move",
2122
+ description: "Move hashFileNames and hashedFileNameLength from top-level config to loader-bundle and www output targets",
2123
+ fromVersion: "4.x",
2124
+ toVersion: "5.x",
2125
+ detect(sourceFile) {
2126
+ const matches = [];
2127
+ const visit = (node) => {
2128
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && (node.name.text === "hashFileNames" || node.name.text === "hashedFileNameLength")) {
2129
+ const parent = node.parent;
2130
+ if (ts.isObjectLiteralExpression(parent)) {
2131
+ if (!parent.properties.some((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "type")) {
2132
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
2133
+ matches.push({
2134
+ node,
2135
+ message: `'${node.name.text}' is no longer a top-level config option. Move it to your 'loader-bundle' and/or 'www' output targets.`,
2136
+ line: line + 1,
2137
+ column: character + 1
2138
+ });
2139
+ }
2140
+ }
2141
+ }
2142
+ ts.forEachChild(node, visit);
2143
+ };
2144
+ visit(sourceFile);
2145
+ return matches;
2146
+ },
2147
+ transform(sourceFile, matches) {
2148
+ if (matches.length === 0) return sourceFile.getFullText();
2149
+ const fullText = sourceFile.getFullText();
2150
+ const propsToInject = matches.map((m) => {
2151
+ const node = m.node;
2152
+ return {
2153
+ name: node.name.text,
2154
+ value: node.initializer.getText(sourceFile)
2155
+ };
2156
+ });
2157
+ const TARGET_TYPES = /* @__PURE__ */ new Set(["loader-bundle", "www"]);
2158
+ const insertionsByPos = /* @__PURE__ */ new Map();
2159
+ const visit = (node) => {
2160
+ if (ts.isObjectLiteralExpression(node)) {
2161
+ if (node.properties.find((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "type" && ts.isStringLiteral(p.initializer) && TARGET_TYPES.has(p.initializer.text))) {
2162
+ const existingPropNames = new Set(node.properties.filter((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name)).map((p) => p.name.text));
2163
+ const objStart = node.getStart(sourceFile);
2164
+ const objLineStart = fullText.lastIndexOf("\n", objStart) + 1;
2165
+ const propIndent = (fullText.slice(objLineStart, objStart).match(/^(\s*)/)?.[1] ?? "") + " ";
2166
+ const closingBracePos = node.getEnd() - 1;
2167
+ const isMultiLine = fullText.slice(objStart, node.getEnd()).includes("\n");
2168
+ let insertPos;
2169
+ if (isMultiLine) insertPos = fullText.lastIndexOf("\n", closingBracePos - 1);
2170
+ else {
2171
+ insertPos = closingBracePos;
2172
+ while (insertPos > 0 && fullText[insertPos - 1] === " ") insertPos--;
2173
+ }
2174
+ const existing = insertionsByPos.get(insertPos) ?? [];
2175
+ for (const prop of propsToInject) if (!existingPropNames.has(prop.name)) existing.push(isMultiLine ? `\n${propIndent}${prop.name}: ${prop.value},` : `, ${prop.name}: ${prop.value}`);
2176
+ if (existing.length > 0) insertionsByPos.set(insertPos, existing);
2177
+ }
2178
+ }
2179
+ ts.forEachChild(node, visit);
2180
+ };
2181
+ visit(sourceFile);
2182
+ const edits = [];
2183
+ for (const match of matches) {
2184
+ const node = match.node;
2185
+ const start = node.getFullStart();
2186
+ const end = node.getEnd();
2187
+ let removeEnd = end;
2188
+ const trailingComma = fullText.slice(end).match(/^\s*,/);
2189
+ if (trailingComma) removeEnd = end + trailingComma[0].length;
2190
+ edits.push({
2191
+ start,
2192
+ end: removeEnd,
2193
+ replacement: ""
2194
+ });
2195
+ }
2196
+ for (const [pos, insertions] of insertionsByPos) edits.push({
2197
+ start: pos,
2198
+ end: pos,
2199
+ replacement: insertions.join("")
2200
+ });
2201
+ edits.sort((a, b) => b.start - a.start);
2202
+ let text = fullText;
2203
+ for (const edit of edits) text = text.slice(0, edit.start) + edit.replacement + text.slice(edit.end);
2204
+ return text;
2205
+ }
2206
+ };
2207
+ //#endregion
2208
+ //#region src/migrations/rules/light-dom-patches.ts
2209
+ /**
2210
+ * Migration rule for slot-fix extras → `lightDomPatches`.
2211
+ *
2212
+ * In v5, the individual slot-fix flags and `experimentalSlotFixes` umbrella are replaced
2213
+ * by a single `lightDomPatches` option which defaults to `true`.
2214
+ *
2215
+ * Migration mapping:
2216
+ * - `experimentalSlotFixes: true` → remove (new default is `true`)
2217
+ * - `experimentalSlotFixes: false` → `lightDomPatches: false`
2218
+ * - Individual flags only → `lightDomPatches: { <new names> }`
2219
+ *
2220
+ * Old → new individual key names:
2221
+ * appendChildSlotFix → domMutations
2222
+ * cloneNodeFix → cloneNode
2223
+ * scopedSlotTextContentFix → textContent
2224
+ * slotChildNodesFix → childNodes
2225
+ */
2226
+ const lightDomPatchesRule = {
2227
+ id: "light-dom-patches",
2228
+ name: "Light DOM Patches Migration",
2229
+ description: "Migrate experimentalSlotFixes / individual slot-fix flags to lightDomPatches",
2230
+ fromVersion: "4.x",
2231
+ toVersion: "5.x",
2232
+ detect(sourceFile) {
2233
+ const matches = [];
2234
+ const oldKeys = /* @__PURE__ */ new Set([
2235
+ "experimentalSlotFixes",
2236
+ "appendChildSlotFix",
2237
+ "cloneNodeFix",
2238
+ "scopedSlotTextContentFix",
2239
+ "slotChildNodesFix"
2240
+ ]);
2241
+ const visit = (node) => {
2242
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && oldKeys.has(node.name.text)) {
2243
+ const parent = node.parent;
2244
+ if (ts.isObjectLiteralExpression(parent)) {
2245
+ const grandparent = parent.parent;
2246
+ if (ts.isPropertyAssignment(grandparent) && ts.isIdentifier(grandparent.name) && grandparent.name.text === "extras") {
2247
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
2248
+ matches.push({
2249
+ node,
2250
+ message: `extras.${node.name.text} is removed. Use 'extras.lightDomPatches' instead.`,
2251
+ line: line + 1,
2252
+ column: character + 1
2253
+ });
2254
+ }
2255
+ }
2256
+ }
2257
+ ts.forEachChild(node, visit);
2258
+ };
2259
+ visit(sourceFile);
2260
+ return matches;
2261
+ },
2262
+ transform(sourceFile, matches) {
2263
+ if (matches.length === 0) return sourceFile.getFullText();
2264
+ const oldKeyMap = {};
2265
+ for (const match of matches) {
2266
+ const node = match.node;
2267
+ const key = node.name.text;
2268
+ const init = node.initializer;
2269
+ oldKeyMap[key] = init.kind === ts.SyntaxKind.TrueKeyword ? true : init.kind === ts.SyntaxKind.FalseKeyword ? false : void 0;
2270
+ }
2271
+ const keyRename = {
2272
+ appendChildSlotFix: "domMutations",
2273
+ cloneNodeFix: "cloneNode",
2274
+ scopedSlotTextContentFix: "textContent",
2275
+ slotChildNodesFix: "childNodes"
2276
+ };
2277
+ const experimentalValue = oldKeyMap["experimentalSlotFixes"];
2278
+ const hasIndividualKeys = matches.some((m) => {
2279
+ return m.node.name.text !== "experimentalSlotFixes";
2280
+ });
2281
+ let replacement = null;
2282
+ if (experimentalValue === true && !hasIndividualKeys) replacement = null;
2283
+ else if (experimentalValue === false && !hasIndividualKeys) replacement = "lightDomPatches: false";
2284
+ else if (experimentalValue === true && hasIndividualKeys) replacement = null;
2285
+ else {
2286
+ const parts = [];
2287
+ for (const [oldKey, newKey] of Object.entries(keyRename)) {
2288
+ const val = oldKeyMap[oldKey];
2289
+ if (val === true) parts.push(`${newKey}: true`);
2290
+ else if (val === false) parts.push(`${newKey}: false`);
2291
+ }
2292
+ if (parts.length > 0) replacement = `lightDomPatches: { ${parts.join(", ")} }`;
2293
+ }
2294
+ const sorted = [...matches].sort((a, b) => b.node.getStart() - a.node.getStart());
2295
+ let text = sourceFile.getFullText();
2296
+ let replacementInserted = false;
2297
+ for (const match of sorted) {
2298
+ const node = match.node;
2299
+ let start = node.getStart();
2300
+ let end = node.getEnd();
2301
+ const trailingComma = text.slice(end).match(/^(\s*,)/);
2302
+ if (trailingComma) end += trailingComma[1].length;
2303
+ else {
2304
+ const leadingComma = text.slice(0, start).match(/,\s*$/);
2305
+ if (leadingComma) start -= leadingComma[0].length;
2306
+ }
2307
+ if (!replacementInserted && replacement !== null) {
2308
+ text = text.slice(0, start) + replacement + text.slice(end);
2309
+ replacementInserted = true;
2310
+ } else text = text.slice(0, start) + text.slice(end);
2311
+ }
2312
+ text = cleanupEmptyExtras(text);
2313
+ return text;
2314
+ }
2315
+ };
2316
+ function cleanupEmptyExtras(text) {
2317
+ return text.replace(/,?\s*extras\s*:\s*\{\s*\},?/g, "");
2318
+ }
2319
+ //#endregion
2320
+ //#region src/migrations/rules/output-target-renames.ts
2321
+ /**
2322
+ * Migration rule for output target renames in Stencil v5.
2323
+ *
2324
+ * This migration:
2325
+ * - Renames `dist` → `loader-bundle`
2326
+ * - Renames `dist-custom-elements` → `standalone`
2327
+ * - Renames `dist-hydrate-script` → `ssr`
2328
+ * - Renames `dist-collection` → `collection`
2329
+ * - Renames `dist-types` → `types`
2330
+ * - Extracts `collectionDir` from loader-bundle into separate `collection` output
2331
+ * - Extracts `typesDir` from loader-bundle into separate `types` output
2332
+ * - Renames `esmLoaderPath` → `loaderPath` (applies to all module formats, not just ESM)
2333
+ * - Removes `isPrimaryPackageOutputTarget` (no longer needed, package.json validation auto-detects)
2334
+ * - Removes `generateTypeDeclarations` (types are now auto-generated via the `types` output target)
2335
+ */
2336
+ const outputTargetRenamesRule = {
2337
+ id: "output-target-renames",
2338
+ name: "Output Target Renames",
2339
+ description: "Rename output targets to new v5 names",
2340
+ fromVersion: "4.x",
2341
+ toVersion: "5.x",
2342
+ detect(sourceFile) {
2343
+ const matches = [];
2344
+ const oldToNewNames = {
2345
+ dist: "loader-bundle",
2346
+ "dist-custom-elements": "standalone",
2347
+ "dist-hydrate-script": "ssr",
2348
+ "dist-collection": "collection",
2349
+ "dist-types": "types"
2350
+ };
2351
+ const visit = (node) => {
2352
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === "type" && ts.isStringLiteral(node.initializer)) {
2353
+ const typeValue = node.initializer.text;
2354
+ if (typeValue in oldToNewNames) {
2355
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
2356
+ matches.push({
2357
+ node,
2358
+ message: `Output target type '${typeValue}' → '${oldToNewNames[typeValue]}'`,
2359
+ line: line + 1,
2360
+ column: character + 1
2361
+ });
2362
+ }
2363
+ }
2364
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && (node.name.text === "collectionDir" || node.name.text === "typesDir")) {
2365
+ const parent = node.parent;
2366
+ if (ts.isObjectLiteralExpression(parent)) {
2367
+ if (parent.properties.some((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "type")) {
2368
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
2369
+ const propName = node.name.text;
2370
+ const newType = propName === "collectionDir" ? "collection" : "types";
2371
+ matches.push({
2372
+ node,
2373
+ message: `Property '${propName}' will be extracted to separate '${newType}' output target`,
2374
+ line: line + 1,
2375
+ column: character + 1
2376
+ });
2377
+ }
2378
+ }
2379
+ }
2380
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === "esmLoaderPath") {
2381
+ const parent = node.parent;
2382
+ if (ts.isObjectLiteralExpression(parent)) {
2383
+ if (parent.properties.some((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "type")) {
2384
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
2385
+ matches.push({
2386
+ node,
2387
+ message: `Property 'esmLoaderPath' renamed to 'loaderPath' (applies to all module formats)`,
2388
+ line: line + 1,
2389
+ column: character + 1
2390
+ });
2391
+ }
2392
+ }
2393
+ }
2394
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && (node.name.text === "isPrimaryPackageOutputTarget" || node.name.text === "generateTypeDeclarations")) {
2395
+ const parent = node.parent;
2396
+ if (ts.isObjectLiteralExpression(parent)) {
2397
+ if (parent.properties.some((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "type")) {
2398
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
2399
+ const propName = node.name.text;
2400
+ const reason = propName === "isPrimaryPackageOutputTarget" ? "Package.json validation now auto-detects based on configured outputs" : "Types are now auto-generated via the 'types' output target";
2401
+ matches.push({
2402
+ node,
2403
+ message: `Property '${propName}' is removed in v5. ${reason}`,
2404
+ line: line + 1,
2405
+ column: character + 1
2406
+ });
2407
+ }
2408
+ }
2409
+ }
2410
+ ts.forEachChild(node, visit);
2411
+ };
2412
+ visit(sourceFile);
2413
+ return matches;
2414
+ },
2415
+ transform(sourceFile, matches) {
2416
+ if (matches.length === 0) return sourceFile.getFullText();
2417
+ let text = sourceFile.getFullText();
2418
+ const oldToNewNames = {
2419
+ dist: "loader-bundle",
2420
+ "dist-custom-elements": "standalone",
2421
+ "dist-hydrate-script": "ssr",
2422
+ "dist-collection": "collection",
2423
+ "dist-types": "types"
2424
+ };
2425
+ const outputTargetsToExtract = [];
2426
+ const findOutputTargetsToExtract = (node) => {
2427
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === "outputTargets" && ts.isArrayLiteralExpression(node.initializer)) {
2428
+ for (const element of node.initializer.elements) if (ts.isObjectLiteralExpression(element)) {
2429
+ let collectionDir;
2430
+ let typesDir;
2431
+ for (const prop of element.properties) if (ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.name)) {
2432
+ if (prop.name.text === "collectionDir" && ts.isStringLiteral(prop.initializer)) collectionDir = prop.initializer.text;
2433
+ else if (prop.name.text === "typesDir" && ts.isStringLiteral(prop.initializer)) typesDir = prop.initializer.text;
2434
+ }
2435
+ if (collectionDir || typesDir) outputTargetsToExtract.push({
2436
+ targetNode: element,
2437
+ collectionDir,
2438
+ typesDir
2439
+ });
2440
+ }
2441
+ }
2442
+ ts.forEachChild(node, findOutputTargetsToExtract);
2443
+ };
2444
+ findOutputTargetsToExtract(sourceFile);
2445
+ const modifications = [];
2446
+ for (const match of matches) {
2447
+ const prop = match.node;
2448
+ const propName = prop.name.text;
2449
+ if (propName === "type" && ts.isStringLiteral(prop.initializer)) {
2450
+ const newType = oldToNewNames[prop.initializer.text];
2451
+ if (newType) {
2452
+ const start = prop.initializer.getStart() + 1;
2453
+ const end = prop.initializer.getEnd() - 1;
2454
+ modifications.push({
2455
+ type: "replace",
2456
+ start,
2457
+ end,
2458
+ replacement: newType
2459
+ });
2460
+ }
2461
+ } else if (propName === "esmLoaderPath") {
2462
+ const nameNode = prop.name;
2463
+ modifications.push({
2464
+ type: "replace",
2465
+ start: nameNode.getStart(),
2466
+ end: nameNode.getEnd(),
2467
+ replacement: "loaderPath"
2468
+ });
2469
+ if (ts.isStringLiteral(prop.initializer)) {
2470
+ const newPath = "../" + prop.initializer.text;
2471
+ modifications.push({
2472
+ type: "replace",
2473
+ start: prop.initializer.getStart() + 1,
2474
+ end: prop.initializer.getEnd() - 1,
2475
+ replacement: newPath
2476
+ });
2477
+ }
2478
+ } else if (propName === "collectionDir" || propName === "typesDir" || propName === "isPrimaryPackageOutputTarget" || propName === "generateTypeDeclarations") {
2479
+ const start = prop.getStart();
2480
+ let end = prop.getEnd();
2481
+ const beforeProp = text.slice(0, start).match(/,\s*$/);
2482
+ const afterProp = text.slice(end).match(/^\s*,/);
2483
+ if (afterProp) end = end + afterProp[0].length;
2484
+ else if (beforeProp) {
2485
+ const commaStart = start - beforeProp[0].length;
2486
+ modifications.push({
2487
+ type: "remove",
2488
+ start: commaStart,
2489
+ end
2490
+ });
2491
+ continue;
2492
+ }
2493
+ modifications.push({
2494
+ type: "remove",
2495
+ start,
2496
+ end
2497
+ });
2498
+ }
2499
+ }
2500
+ modifications.sort((a, b) => b.start - a.start);
2501
+ for (const mod of modifications) if (mod.type === "replace") text = text.slice(0, mod.start) + mod.replacement + text.slice(mod.end);
2502
+ else if (mod.type === "remove") text = text.slice(0, mod.start) + text.slice(mod.end);
2503
+ if (outputTargetsToExtract.length > 0) text = addExtractedOutputTargets(text, sourceFile, outputTargetsToExtract);
2504
+ text = text.replace(/,\s*\n\s*\n/g, ",\n");
2505
+ text = text.replace(/{\s*\n\s*\n/g, "{\n");
2506
+ text = text.replace(/,\s*,/g, ",");
2507
+ return text;
2508
+ }
2509
+ };
2510
+ /**
2511
+ * Add new output targets for extracted collectionDir and typesDir.
2512
+ * @param text The original source text
2513
+ * @param sourceFile The TypeScript source file object
2514
+ * @param toExtract An array of objects containing the output target nodes and their collectionDir/typesDir values to extract
2515
+ * @returns The modified source text with new output targets added
2516
+ */
2517
+ function addExtractedOutputTargets(text, sourceFile, toExtract) {
2518
+ let outputTargetsArray = null;
2519
+ const findOutputTargets = (node) => {
2520
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === "outputTargets" && ts.isArrayLiteralExpression(node.initializer)) outputTargetsArray = node.initializer;
2521
+ ts.forEachChild(node, findOutputTargets);
2522
+ };
2523
+ findOutputTargets(sourceFile);
2524
+ if (!outputTargetsArray || toExtract.length === 0) return text;
2525
+ const array = outputTargetsArray;
2526
+ let indent = " ";
2527
+ if (array.elements.length > 0) {
2528
+ const elemStart = array.elements[0].getStart();
2529
+ const lineStart = text.lastIndexOf("\n", elemStart) + 1;
2530
+ const leadingWhitespace = text.slice(lineStart, elemStart);
2531
+ if (/^\s+$/.test(leadingWhitespace)) indent = leadingWhitespace;
2532
+ }
2533
+ const lastElement = array.elements[array.elements.length - 1];
2534
+ if (!lastElement) return text;
2535
+ let insertPos = lastElement.getEnd();
2536
+ const afterLastElement = text.slice(insertPos).match(/^(\s*,)?/);
2537
+ if (afterLastElement && afterLastElement[1]) insertPos += afterLastElement[0].length;
2538
+ const newTargets = [];
2539
+ for (const extracted of toExtract) {
2540
+ if (extracted.collectionDir) newTargets.push(`{\n${indent} type: 'collection',\n${indent} dir: '${extracted.collectionDir}',\n${indent}}`);
2541
+ if (extracted.typesDir) newTargets.push(`{\n${indent} type: 'types',\n${indent} dir: '${extracted.typesDir}',\n${indent}}`);
2542
+ }
2543
+ if (newTargets.length === 0) return text;
2544
+ const insertion = ",\n" + newTargets.map((t) => `${indent}${t}`).join(",\n");
2545
+ text = text.slice(0, insertPos) + insertion + text.slice(insertPos);
2546
+ return text;
2547
+ }
2548
+ //#endregion
2549
+ //#region src/migrations/rules/rolldown-config.ts
2550
+ /**
2551
+ * NodeResolve fields that were valid in @rollup/plugin-node-resolve but don't exist
2552
+ * in rolldown's native resolver and should be removed.
2553
+ */
2554
+ const REMOVED_NODE_RESOLVE_FIELDS = /* @__PURE__ */ new Set([
2555
+ "browser",
2556
+ "modulePaths",
2557
+ "dedupe",
2558
+ "jail",
2559
+ "modulesOnly",
2560
+ "preferBuiltins",
2561
+ "resolveOnly",
2562
+ "rootDir",
2563
+ "allowExportsFolderMapping"
2564
+ ]);
2565
+ /** Fields renamed between @rollup/plugin-node-resolve and rolldown's native resolver. */
2566
+ const RENAMED_NODE_RESOLVE_FIELDS = {
2567
+ exportConditions: "conditionNames",
2568
+ moduleDirectories: "modules"
2569
+ };
2570
+ function isInsideNodeResolve(node) {
2571
+ const parent = node.parent;
2572
+ if (!ts.isObjectLiteralExpression(parent)) return false;
2573
+ const grandParent = parent.parent;
2574
+ return ts.isPropertyAssignment(grandParent) && ts.isIdentifier(grandParent.name) && grandParent.name.text === "nodeResolve";
2575
+ }
2576
+ /**
2577
+ * Migration rule for rolldown-related config changes in Stencil v5.
2578
+ *
2579
+ * Handles:
2580
+ * - `rollupConfig` → `rolldownConfig` (key rename + flatten `inputOptions`)
2581
+ * - `rolldownConfig: { inputOptions: { ... } }` → `rolldownConfig: { ... }` (flatten)
2582
+ * - `rollupPlugins` → `rolldownPlugins`
2583
+ * - `nodeResolve.exportConditions` → `nodeResolve.conditionNames`
2584
+ * - `nodeResolve.moduleDirectories` → `nodeResolve.modules`
2585
+ * - Removes unsupported `nodeResolve` fields (`browser`, `dedupe`, `jail`, etc.)
2586
+ */
2587
+ const rolldownConfigRule = {
2588
+ id: "rolldown-config",
2589
+ name: "Rolldown Config Migration",
2590
+ description: "Migrate rollup/rolldown config options to v5 rolldown-native API",
2591
+ fromVersion: "4.x",
2592
+ toVersion: "5.x",
2593
+ detect(sourceFile) {
2594
+ const matches = [];
2595
+ const visit = (node) => {
2596
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name)) {
2597
+ const name = node.name.text;
2598
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
2599
+ if (name === "rollupPlugins") matches.push({
2600
+ node,
2601
+ message: `'rollupPlugins' renamed to 'rolldownPlugins'`,
2602
+ line: line + 1,
2603
+ column: character + 1
2604
+ });
2605
+ else if (name === "rollupConfig" || name === "rolldownConfig") {
2606
+ const value = node.initializer;
2607
+ if (name === "rollupConfig" || ts.isObjectLiteralExpression(value) && value.properties.some((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "inputOptions")) matches.push({
2608
+ node,
2609
+ message: name === "rollupConfig" ? `'rollupConfig' renamed to 'rolldownConfig'; 'inputOptions' wrapper removed` : `'rolldownConfig.inputOptions' wrapper removed - options are now top-level`,
2610
+ line: line + 1,
2611
+ column: character + 1
2612
+ });
2613
+ } else if (name in RENAMED_NODE_RESOLVE_FIELDS && isInsideNodeResolve(node)) matches.push({
2614
+ node,
2615
+ message: `'nodeResolve.${name}' renamed to 'nodeResolve.${RENAMED_NODE_RESOLVE_FIELDS[name]}'`,
2616
+ line: line + 1,
2617
+ column: character + 1
2618
+ });
2619
+ else if (REMOVED_NODE_RESOLVE_FIELDS.has(name) && isInsideNodeResolve(node)) matches.push({
2620
+ node,
2621
+ message: `'nodeResolve.${name}' is not supported by rolldown's native resolver and will be removed`,
2622
+ line: line + 1,
2623
+ column: character + 1
2624
+ });
2625
+ }
2626
+ ts.forEachChild(node, visit);
2627
+ };
2628
+ visit(sourceFile);
2629
+ return matches;
2630
+ },
2631
+ transform(sourceFile, matches) {
2632
+ if (matches.length === 0) return sourceFile.getFullText();
2633
+ const edits = [];
2634
+ const fullText = sourceFile.getFullText();
2635
+ for (const match of matches) {
2636
+ const node = match.node;
2637
+ const name = node.name.text;
2638
+ if (name === "rollupPlugins") {
2639
+ const nameStart = node.name.getStart(sourceFile);
2640
+ const nameEnd = node.name.getEnd();
2641
+ edits.push({
2642
+ start: nameStart,
2643
+ end: nameEnd,
2644
+ replacement: "rolldownPlugins"
2645
+ });
2646
+ continue;
2647
+ }
2648
+ if (name in RENAMED_NODE_RESOLVE_FIELDS && isInsideNodeResolve(node)) {
2649
+ const nameStart = node.name.getStart(sourceFile);
2650
+ const nameEnd = node.name.getEnd();
2651
+ edits.push({
2652
+ start: nameStart,
2653
+ end: nameEnd,
2654
+ replacement: RENAMED_NODE_RESOLVE_FIELDS[name]
2655
+ });
2656
+ continue;
2657
+ }
2658
+ if (REMOVED_NODE_RESOLVE_FIELDS.has(name) && isInsideNodeResolve(node)) {
2659
+ const start = node.getFullStart();
2660
+ const end = node.getEnd();
2661
+ const trailingComma = fullText.slice(end).match(/^\s*,/);
2662
+ edits.push({
2663
+ start,
2664
+ end: trailingComma ? end + trailingComma[0].length : end,
2665
+ replacement: ""
2666
+ });
2667
+ continue;
2668
+ }
2669
+ if (name === "rollupConfig" || name === "rolldownConfig") {
2670
+ const value = node.initializer;
2671
+ if (!ts.isObjectLiteralExpression(value)) {
2672
+ if (name === "rollupConfig") {
2673
+ const nameStart = node.name.getStart(sourceFile);
2674
+ edits.push({
2675
+ start: nameStart,
2676
+ end: node.name.getEnd(),
2677
+ replacement: "rolldownConfig"
2678
+ });
2679
+ }
2680
+ continue;
2681
+ }
2682
+ const inputOptionsProp = value.properties.find((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "inputOptions");
2683
+ if (!inputOptionsProp) {
2684
+ if (name === "rollupConfig") {
2685
+ const nameStart = node.name.getStart(sourceFile);
2686
+ edits.push({
2687
+ start: nameStart,
2688
+ end: node.name.getEnd(),
2689
+ replacement: "rolldownConfig"
2690
+ });
2691
+ }
2692
+ continue;
2693
+ }
2694
+ const newValueText = inputOptionsProp.initializer.getText(sourceFile);
2695
+ const keyStart = node.name.getStart(sourceFile);
2696
+ edits.push({
2697
+ start: keyStart,
2698
+ end: node.getEnd(),
2699
+ replacement: `rolldownConfig: ${newValueText}`
2700
+ });
2701
+ }
2702
+ }
2703
+ edits.sort((a, b) => b.start - a.start);
2704
+ let text = fullText;
2705
+ for (const edit of edits) text = text.slice(0, edit.start) + edit.replacement + text.slice(edit.end);
2706
+ return text;
2707
+ }
2708
+ };
2709
+ //#endregion
2710
+ //#region src/migrations/rules/service-worker-default.ts
2711
+ /**
2712
+ * Migration rule for `serviceWorker: null` / `serviceWorker: false` on `www` output targets.
2713
+ *
2714
+ * In Stencil v5, `serviceWorker` defaults to `null` (disabled). Explicit `null` or `false`
2715
+ * values on `www` output targets are now redundant and can be removed.
2716
+ */
2717
+ const serviceWorkerDefaultRule = {
2718
+ id: "service-worker-default",
2719
+ name: "Service Worker Default Cleanup",
2720
+ description: "Remove redundant 'serviceWorker: null' / 'serviceWorker: false' from www output targets - null is now the default",
2721
+ fromVersion: "4.x",
2722
+ toVersion: "5.x",
2723
+ detect(sourceFile) {
2724
+ const matches = [];
2725
+ const visit = (node) => {
2726
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === "serviceWorker") {
2727
+ const init = node.initializer;
2728
+ if (init.kind === ts.SyntaxKind.NullKeyword || init.kind === ts.SyntaxKind.FalseKeyword) {
2729
+ const parent = node.parent;
2730
+ if (ts.isObjectLiteralExpression(parent)) {
2731
+ if (parent.properties.some((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "type" && ts.isStringLiteral(p.initializer) && p.initializer.text === "www")) {
2732
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
2733
+ matches.push({
2734
+ node,
2735
+ message: `'serviceWorker: ${init.kind === ts.SyntaxKind.NullKeyword ? "null" : "false"}' is now the default on www output targets and can be removed`,
2736
+ line: line + 1,
2737
+ column: character + 1
2738
+ });
2739
+ }
772
2740
  }
773
- const { line, character } = sourceFile.getLineAndCharacterOfPosition(formAssociatedProp.getStart());
774
- matches.push({
775
- node: formAssociatedProp,
776
- message: hasAttachInternals ? "Remove 'formAssociated' (already has @AttachInternals)" : "Migrate 'formAssociated' to @AttachInternals decorator",
777
- line: line + 1,
778
- column: character + 1,
779
- classBodyStart,
780
- hasAttachInternals,
781
- indent,
782
- needsImport: !hasAttachInternalsImport && !hasAttachInternals,
783
- stencilImportEnd
784
- });
785
2741
  }
786
2742
  }
787
2743
  ts.forEachChild(node, visit);
@@ -792,38 +2748,113 @@ const formAssociatedRule = {
792
2748
  transform(sourceFile, matches) {
793
2749
  if (matches.length === 0) return sourceFile.getFullText();
794
2750
  let text = sourceFile.getFullText();
795
- const typedMatches = matches;
796
- const sortedMatches = [...typedMatches].sort((a, b) => {
797
- return b.classBodyStart - a.classBodyStart;
798
- });
799
- for (const match of sortedMatches) {
800
- if (!match.hasAttachInternals) {
801
- const newMember = `\n${match.indent}@AttachInternals() internals: ElementInternals;\n`;
802
- text = text.slice(0, match.classBodyStart) + newMember + text.slice(match.classBodyStart);
2751
+ for (const match of [...matches].reverse()) {
2752
+ const node = match.node;
2753
+ let start = node.getFullStart();
2754
+ const end = node.getEnd();
2755
+ let removeEnd = end;
2756
+ const trailingComma = text.slice(end).match(/^\s*,/);
2757
+ if (trailingComma) removeEnd = end + trailingComma[0].length;
2758
+ else {
2759
+ const leadingComma = text.slice(0, start).match(/,\s*$/);
2760
+ if (leadingComma) start -= leadingComma[0].length;
803
2761
  }
804
- const prop = match.node;
805
- const start = prop.getStart();
806
- let end = prop.getEnd();
807
- const afterProp = text.slice(end).match(/^\s*,/);
808
- if (afterProp) end = end + afterProp[0].length;
809
- text = text.slice(0, start) + text.slice(end);
2762
+ text = text.slice(0, start) + text.slice(removeEnd);
810
2763
  }
811
- const firstMatch = typedMatches[0];
812
- if (firstMatch?.needsImport && firstMatch.stencilImportEnd > 0) {
813
- const importMatch = text.match(/import\s*\{([^}]*)\}\s*from\s*['"]@stencil\/core['"]/);
814
- if (importMatch) {
815
- const newImports = importMatch[1].trimEnd() + ", AttachInternals";
816
- text = text.replace(importMatch[0], `import {${newImports}} from '@stencil/core'`);
2764
+ return text;
2765
+ }
2766
+ };
2767
+ //#endregion
2768
+ //#region src/migrations/rules/suppress-warnings-to-compat.ts
2769
+ /**
2770
+ * Migration rule: move `suppressReservedPublicNameWarnings` / `suppressReservedEventNameWarnings`
2771
+ * off the top level of the config and into `compat`, dropping `Reserved` from their names.
2772
+ *
2773
+ * In v5:
2774
+ * suppressReservedPublicNameWarnings → compat.suppressPublicNameWarnings
2775
+ * suppressReservedEventNameWarnings → compat.suppressEventNameWarnings
2776
+ */
2777
+ const KEY_RENAME = {
2778
+ suppressReservedPublicNameWarnings: "suppressPublicNameWarnings",
2779
+ suppressReservedEventNameWarnings: "suppressEventNameWarnings"
2780
+ };
2781
+ const suppressWarningsToCompatRule = {
2782
+ id: "suppress-warnings-to-compat",
2783
+ name: "Suppress Warnings → Compat",
2784
+ description: "Move 'suppressReservedPublicNameWarnings' / 'suppressReservedEventNameWarnings' into 'compat'",
2785
+ fromVersion: "4.x",
2786
+ toVersion: "5.x",
2787
+ detect(sourceFile) {
2788
+ const matches = [];
2789
+ const visit = (node) => {
2790
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text in KEY_RENAME) {
2791
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
2792
+ matches.push({
2793
+ node,
2794
+ message: `'${node.name.text}' has moved to 'compat.${KEY_RENAME[node.name.text]}'`,
2795
+ line: line + 1,
2796
+ column: character + 1
2797
+ });
2798
+ }
2799
+ ts.forEachChild(node, visit);
2800
+ };
2801
+ visit(sourceFile);
2802
+ return matches;
2803
+ },
2804
+ transform(sourceFile, matches) {
2805
+ if (matches.length === 0) return sourceFile.getFullText();
2806
+ const text = sourceFile.getFullText();
2807
+ const edits = [];
2808
+ const newProps = [];
2809
+ for (const match of matches) {
2810
+ const node = match.node;
2811
+ const key = node.name.text;
2812
+ newProps.push(`${KEY_RENAME[key]}: ${node.initializer.getText(sourceFile)}`);
2813
+ let start = node.getStart();
2814
+ let end = node.getEnd();
2815
+ const trailingComma = text.slice(end).match(/^(\s*,)/);
2816
+ if (trailingComma) end += trailingComma[1].length;
2817
+ else {
2818
+ const leadingComma = text.slice(0, start).match(/,\s*$/);
2819
+ if (leadingComma) start -= leadingComma[0].length;
817
2820
  }
2821
+ edits.push({
2822
+ start,
2823
+ end,
2824
+ replacement: ""
2825
+ });
818
2826
  }
819
- return text;
2827
+ const parentObject = matches[0].node.parent;
2828
+ const existingCompat = parentObject.properties.find((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "compat" && ts.isObjectLiteralExpression(p.initializer));
2829
+ if (existingCompat) edits.push(insertIntoObjectLiteral(existingCompat.initializer, newProps));
2830
+ else edits.push(insertIntoObjectLiteral(parentObject, [`compat: { ${newProps.join(", ")} }`]));
2831
+ let result = text;
2832
+ for (const edit of edits.sort((a, b) => b.start - a.start)) result = result.slice(0, edit.start) + edit.replacement + result.slice(edit.end);
2833
+ return result;
820
2834
  }
821
2835
  };
2836
+ function insertIntoObjectLiteral(obj, newProps) {
2837
+ if (obj.properties.length === 0) {
2838
+ const pos = obj.getStart() + 1;
2839
+ return {
2840
+ start: pos,
2841
+ end: pos,
2842
+ replacement: ` ${newProps.join(", ")} `
2843
+ };
2844
+ }
2845
+ const last = obj.properties[obj.properties.length - 1];
2846
+ return {
2847
+ start: last.getEnd(),
2848
+ end: last.getEnd(),
2849
+ replacement: `, ${newProps.join(", ")}`
2850
+ };
2851
+ }
822
2852
  //#endregion
823
2853
  //#region src/migrations/index.ts
824
2854
  /**
825
2855
  * Build a map of local import names to their original names from @stencil/core.
826
2856
  * Handles aliased imports like `import { Component as Cmp } from '@stencil/core'`.
2857
+ * Also handles multiple imports from @stencil/core (e.g., separate type and value imports).
827
2858
  *
828
2859
  * @param sourceFile The TypeScript source file to analyze
829
2860
  * @returns Map where keys are local names and values are original imported names
@@ -837,7 +2868,6 @@ const getStencilCoreImportMap = (sourceFile) => {
837
2868
  const originalName = element.propertyName?.text ?? element.name.text;
838
2869
  importMap.set(localName, originalName);
839
2870
  }
840
- break;
841
2871
  }
842
2872
  return importMap;
843
2873
  };
@@ -857,7 +2887,23 @@ const isStencilDecorator = (decoratorName, expectedOriginalName, importMap) => {
857
2887
  * Registry of all available migration rules.
858
2888
  * Rules are applied in order, so add new rules at the end.
859
2889
  */
860
- const migrationRules = [encapsulationApiRule, formAssociatedRule];
2890
+ const migrationRules = [
2891
+ encapsulationApiRule,
2892
+ formAssociatedRule,
2893
+ buildDistDocsRule,
2894
+ outputTargetRenamesRule,
2895
+ devModeRule,
2896
+ globalStyleInjectRule,
2897
+ lightDomPatchesRule,
2898
+ enableImportInjectionDefaultRule,
2899
+ extrasToCompatRule,
2900
+ suppressWarningsToCompatRule,
2901
+ externalRuntimeRule,
2902
+ hashFileNamesRule,
2903
+ rolldownConfigRule,
2904
+ serviceWorkerDefaultRule,
2905
+ cssImportQueryParamRule
2906
+ ];
861
2907
  /**
862
2908
  * Get all migration rules for a specific version upgrade.
863
2909
  * @param fromVersion Source version (e.g., '4')
@@ -905,7 +2951,7 @@ const taskMigrate = async (coreCompiler, config, flags) => {
905
2951
  const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);
906
2952
  const matches = rule.detect(sourceFile);
907
2953
  if (matches.length > 0) {
908
- const relPath = relative(config.rootDir, filePath);
2954
+ const relPath = relative$1(config.rootDir, filePath);
909
2955
  logger.info(`\n${logger.cyan(relPath)}`);
910
2956
  logger.info(` ${logger.yellow(`[${rule.id}]`)} ${rule.name}`);
911
2957
  for (const match of matches) logger.info(` Line ${match.line}: ${match.message}`);
@@ -966,7 +3012,8 @@ const detectMigrations = async (coreCompiler, config) => {
966
3012
  const sys = config.sys;
967
3013
  const logger = config.logger;
968
3014
  const currentMajor = coreCompiler.version.split(".")[0];
969
- const rules = getRulesForVersionUpgrade(String(Number(currentMajor) - 1), currentMajor);
3015
+ const fromVersion = String(Number(currentMajor) - 1);
3016
+ const rules = getRulesForVersionUpgrade(fromVersion, currentMajor);
970
3017
  if (rules.length === 0) return {
971
3018
  hasMigrations: false,
972
3019
  totalMatches: 0,
@@ -1017,8 +3064,8 @@ const detectMigrations = async (coreCompiler, config) => {
1017
3064
  */
1018
3065
  async function getTypeScriptFiles(config, sys, logger) {
1019
3066
  let tsconfigPath;
1020
- if (config.tsconfig) tsconfigPath = isAbsolute(config.tsconfig) ? config.tsconfig : join(config.rootDir, config.tsconfig);
1021
- else tsconfigPath = join(config.rootDir, "tsconfig.json");
3067
+ if (config.tsconfig) tsconfigPath = isAbsolute(config.tsconfig) ? config.tsconfig : join$1(config.rootDir, config.tsconfig);
3068
+ else tsconfigPath = join$1(config.rootDir, "tsconfig.json");
1022
3069
  logger.debug(`Using tsconfig: ${tsconfigPath}`);
1023
3070
  const tsconfigContent = await sys.readFile(tsconfigPath);
1024
3071
  if (!tsconfigContent) {
@@ -1041,27 +3088,49 @@ async function getTypeScriptFiles(config, sys, logger) {
1041
3088
  return [];
1042
3089
  }
1043
3090
  if (results.errors && results.errors.length > 0) for (const err of results.errors) logger.warn(ts.flattenDiagnosticMessageText(err.messageText, "\n"));
1044
- return results.fileNames.filter((f) => (f.endsWith(".ts") || f.endsWith(".tsx")) && !f.endsWith(".d.ts"));
3091
+ const files = results.fileNames.filter((f) => (f.endsWith(".ts") || f.endsWith(".tsx")) && !f.endsWith(".d.ts"));
3092
+ const configFile = config.configPath;
3093
+ if (configFile && (configFile.endsWith(".ts") || configFile.endsWith(".mts"))) {
3094
+ if (!files.includes(configFile)) files.push(configFile);
3095
+ const configContent = await sys.readFile(configFile);
3096
+ if (configContent) {
3097
+ const configSourceFile = ts.createSourceFile(configFile, configContent, ts.ScriptTarget.Latest, true);
3098
+ const configDir = dirname$1(configFile);
3099
+ for (const statement of configSourceFile.statements) if (ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier)) {
3100
+ const specifier = statement.moduleSpecifier.text;
3101
+ if (!specifier.startsWith("./") && !specifier.startsWith("../")) continue;
3102
+ const basePath = join$1(configDir, specifier);
3103
+ const candidates = basePath.endsWith(".ts") || basePath.endsWith(".tsx") ? [basePath] : [`${basePath}.ts`, `${basePath}.tsx`];
3104
+ for (const candidate of candidates) if (!candidate.endsWith(".d.ts") && !files.includes(candidate) && candidate.startsWith(config.rootDir)) {
3105
+ if (await sys.readFile(candidate)) {
3106
+ files.push(candidate);
3107
+ break;
3108
+ }
3109
+ }
3110
+ }
3111
+ }
3112
+ }
3113
+ return files;
1045
3114
  }
1046
3115
  //#endregion
1047
3116
  //#region src/task-prerender.ts
1048
3117
  const taskPrerender = async (coreCompiler, config, flags) => {
1049
3118
  startupCompilerLog(coreCompiler, config);
1050
- const hydrateAppFilePath = flags.unknownArgs[0];
1051
- if (typeof hydrateAppFilePath !== "string") {
3119
+ const ssrAppFilePath = flags.unknownArgs[0];
3120
+ if (typeof ssrAppFilePath !== "string") {
1052
3121
  config.logger.error(`Missing hydrate app script path`);
1053
3122
  return config.sys.exit(1);
1054
3123
  }
1055
3124
  const srcIndexHtmlPath = config.srcIndexHtml;
1056
- const diagnostics = await runPrerenderTask(coreCompiler, config, hydrateAppFilePath, void 0, srcIndexHtmlPath);
3125
+ const diagnostics = await runPrerenderTask(coreCompiler, config, ssrAppFilePath, void 0, srcIndexHtmlPath);
1057
3126
  config.logger.printDiagnostics(diagnostics);
1058
3127
  if (diagnostics.some((d) => d.level === "error")) return config.sys.exit(1);
1059
3128
  };
1060
- const runPrerenderTask = async (coreCompiler, config, hydrateAppFilePath, componentGraph, srcIndexHtmlPath) => {
3129
+ const runPrerenderTask = async (coreCompiler, config, ssrAppFilePath, componentGraph, srcIndexHtmlPath) => {
1061
3130
  const diagnostics = [];
1062
3131
  try {
1063
3132
  const results = await (await coreCompiler.createPrerenderer(config)).start({
1064
- hydrateAppFilePath,
3133
+ ssrAppFilePath,
1065
3134
  componentGraph,
1066
3135
  srcIndexHtmlPath
1067
3136
  });
@@ -1166,8 +3235,8 @@ function hasVerbose(flags) {
1166
3235
  }
1167
3236
  //#endregion
1168
3237
  //#region src/ionic-config.ts
1169
- const isTest$1 = () => process.env.JEST_WORKER_ID !== void 0;
1170
- const defaultConfig = (sys) => sys.resolvePath(`${sys.homeDir()}/.ionic/${isTest$1() ? "tmp-config.json" : "config.json"}`);
3238
+ const isTest = () => process.env.JEST_WORKER_ID !== void 0;
3239
+ const defaultConfig = (sys) => sys.resolvePath(`${sys.homeDir()}/.ionic/${isTest() ? "tmp-config.json" : "config.json"}`);
1171
3240
  const defaultConfigDirectory = (sys) => sys.resolvePath(`${sys.homeDir()}/.ionic`);
1172
3241
  /**
1173
3242
  * Reads an Ionic configuration file from disk, parses it, and performs any necessary corrections to it if certain
@@ -1393,7 +3462,7 @@ const anonymizeConfigForTelemetry = (config) => {
1393
3462
  if (OUTPUT_TARGET_KEYS_TO_KEEP.includes(key)) return value;
1394
3463
  return "omitted";
1395
3464
  }));
1396
- if (isOutputTargetHydrate(target) && target.external) anonymizedOT["external"] = target.external.concat();
3465
+ if (isOutputTargetSsr(target) && target.external) anonymizedOT["external"] = target.external.concat();
1397
3466
  return anonymizedOT;
1398
3467
  });
1399
3468
  for (const prop of CONFIG_PROPS_TO_DELETE) delete anonymizedConfig[prop];
@@ -1587,6 +3656,23 @@ const taskBuild = async (coreCompiler, config, flags) => {
1587
3656
  let exitCode = 0;
1588
3657
  try {
1589
3658
  startupCompilerLog(coreCompiler, config);
3659
+ const preBuildMigrationResult = await detectMigrations(coreCompiler, config);
3660
+ if (preBuildMigrationResult.hasMigrations) {
3661
+ const action = await promptForMigration(config, preBuildMigrationResult, "pre-build");
3662
+ if (action === "run") {
3663
+ await taskMigrate(coreCompiler, config, {
3664
+ ...flags,
3665
+ dryRun: false
3666
+ });
3667
+ config.logger.info("\nMigrations applied. Starting build...\n");
3668
+ } else if (action === "dry-run") {
3669
+ await taskMigrate(coreCompiler, config, {
3670
+ ...flags,
3671
+ dryRun: true
3672
+ });
3673
+ return config.sys.exit(1);
3674
+ } else return config.sys.exit(1);
3675
+ }
1590
3676
  const versionChecker = startCheckVersion(config, coreCompiler.version, flags);
1591
3677
  const compiler = await coreCompiler.createCompiler(config);
1592
3678
  const results = await compiler.build();
@@ -1595,7 +3681,7 @@ const taskBuild = async (coreCompiler, config, flags) => {
1595
3681
  if (results.hasError) {
1596
3682
  const migrationResult = await detectMigrations(coreCompiler, config);
1597
3683
  if (migrationResult.hasMigrations) {
1598
- const action = await promptForMigrationOnBuildError(config, migrationResult);
3684
+ const action = await promptForMigration(config, migrationResult, "post-error");
1599
3685
  if (action === "run") {
1600
3686
  await taskMigrate(coreCompiler, config, {
1601
3687
  ...flags,
@@ -1608,7 +3694,7 @@ const taskBuild = async (coreCompiler, config, flags) => {
1608
3694
  if (!newResults.hasError) {
1609
3695
  exitCode = 0;
1610
3696
  if (flags.prerender) {
1611
- const prerenderDiagnostics = await runPrerenderTask(coreCompiler, config, newResults.hydrateAppFilePath, newResults.componentGraph, void 0);
3697
+ const prerenderDiagnostics = await runPrerenderTask(coreCompiler, config, newResults.ssrAppFilePath, newResults.componentGraph, void 0);
1612
3698
  config.logger.printDiagnostics(prerenderDiagnostics);
1613
3699
  if (prerenderDiagnostics.some((d) => d.level === "error")) exitCode = 1;
1614
3700
  }
@@ -1622,7 +3708,7 @@ const taskBuild = async (coreCompiler, config, flags) => {
1622
3708
  } else exitCode = 1;
1623
3709
  } else exitCode = 1;
1624
3710
  } else if (flags.prerender) {
1625
- const prerenderDiagnostics = await runPrerenderTask(coreCompiler, config, results.hydrateAppFilePath, results.componentGraph, void 0);
3711
+ const prerenderDiagnostics = await runPrerenderTask(coreCompiler, config, results.ssrAppFilePath, results.componentGraph, void 0);
1626
3712
  config.logger.printDiagnostics(prerenderDiagnostics);
1627
3713
  if (prerenderDiagnostics.some((d) => d.level === "error")) exitCode = 1;
1628
3714
  }
@@ -1634,49 +3720,48 @@ const taskBuild = async (coreCompiler, config, flags) => {
1634
3720
  if (exitCode > 0) return config.sys.exit(exitCode);
1635
3721
  };
1636
3722
  /**
1637
- * Prompt the user about available migrations when a build fails.
3723
+ * Prompt the user about available migrations.
1638
3724
  * Shows what migrations are available and lets them choose to run them.
1639
3725
  * @param config the Stencil config
1640
3726
  * @param migrationResult the result of migration detection with available migrations
3727
+ * @param context whether this is a pre-build check or post-error check
1641
3728
  * @returns the user's chosen action for handling migrations
1642
3729
  */
1643
- async function promptForMigrationOnBuildError(config, migrationResult) {
3730
+ async function promptForMigration(config, migrationResult, context) {
1644
3731
  const logger = config.logger;
1645
3732
  logger.info("");
1646
- logger.info(logger.bold(logger.yellow("Migrations Available")));
3733
+ logger.info(logger.bold(logger.yellow("Migrations Required")));
1647
3734
  logger.info("─".repeat(40));
1648
- logger.info(`Found ${migrationResult.totalMatches} item(s) in ${migrationResult.filesAffected} file(s) that can be automatically migrated.`);
3735
+ logger.info(`Found ${migrationResult.totalMatches} item(s) in ${migrationResult.filesAffected} file(s) that need to be migrated for Stencil v5.`);
1649
3736
  for (const migration of migrationResult.migrations) {
1650
- const relPath = relative(config.rootDir, migration.filePath);
3737
+ const relPath = relative$1(config.rootDir, migration.filePath);
1651
3738
  logger.info(` ${logger.cyan(relPath)}: ${migration.matches.length} item(s)`);
1652
3739
  }
1653
3740
  logger.info("");
1654
- logger.info("These migrations may help resolve the build errors above.");
1655
- const { prompt } = await import("prompts");
1656
- const response = await prompt({
1657
- name: "action",
1658
- type: "select",
3741
+ if (context === "pre-build") logger.info("Your config contains deprecated options that must be migrated before building.");
3742
+ else logger.info("These migrations may help resolve the build errors above.");
3743
+ const action = await select({
1659
3744
  message: "What would you like to do?",
1660
- choices: [
3745
+ options: [
1661
3746
  {
1662
- title: "Run migration",
1663
3747
  value: "run",
1664
- description: "Apply migrations and re-run build"
3748
+ label: "Run migration",
3749
+ hint: "Apply migrations and re-run build"
1665
3750
  },
1666
3751
  {
1667
- title: "Dry run",
1668
3752
  value: "dry-run",
1669
- description: "Preview changes without modifying files"
3753
+ label: "Dry run",
3754
+ hint: "Preview changes without modifying files"
1670
3755
  },
1671
3756
  {
1672
- title: "Exit",
1673
3757
  value: "exit",
1674
- description: "Exit without making changes"
3758
+ label: "Exit",
3759
+ hint: "Exit without making changes"
1675
3760
  }
1676
3761
  ]
1677
3762
  });
1678
- if (response.action === void 0) return "exit";
1679
- return response.action;
3763
+ if (isCancel(action)) return "exit";
3764
+ return action;
1680
3765
  }
1681
3766
  //#endregion
1682
3767
  //#region src/task-docs.ts
@@ -1690,277 +3775,180 @@ const taskDocs = async (coreCompiler, config) => {
1690
3775
  await compiler.destroy();
1691
3776
  };
1692
3777
  //#endregion
1693
- //#region src/task-generate.ts
3778
+ //#region src/resolve-entry-script.ts
1694
3779
  /**
1695
- * Task to generate component boilerplate and write it to disk. This task can
1696
- * cause the program to exit with an error under various circumstances, such as
1697
- * being called in an inappropriate place, being asked to overwrite files that
1698
- * already exist, etc.
3780
+ * Resolves the server-relative src for the project's browser entry bundle, from validated
3781
+ * output targets alone (no build required) - the same dev-mode, unhashed filename conventions
3782
+ * the compiler itself uses (see `getAbsoluteBuildDir` in `packages/core/src/compiler/html/html-utils.ts`
3783
+ * and the dev server's `getLoaderUrl` in `packages/dev-server/src/server/dev-preview.ts`, which
3784
+ * this mirrors for use before a build has happened).
1699
3785
  *
1700
- * @param config the user-supplied config, which we need here to access `.sys`.
1701
- * @param flags the CLI flags (owned by CLI, not part of core config)
1702
- * @returns a void promise
3786
+ * Preference order matches what actually gets built:
3787
+ * 1. `www` - always emits its own entry bundle at `{buildDir}/{fsNamespace}.js`, regardless of
3788
+ * `bundleMode`, so it's resolved directly from the `www` target rather than the `dist-lazy` /
3789
+ * `standalone` target it internally synthesizes.
3790
+ * 2. `loader-bundle` (no `www`) - synthesizes a `dist-lazy` build for CDN usage, servable from
3791
+ * the project root when there's no `www` target to claim the server root instead.
3792
+ * 3. `standalone` with `autoLoader` enabled (the default) - falls back to its auto-loader script.
3793
+ *
3794
+ * Returns `null` if the project has no browser-loadable output target at all (e.g. an SSR-only
3795
+ * project) - the caller should omit the script tag in that case.
3796
+ *
3797
+ * @param config - Validated Stencil config.
3798
+ * @returns Server-relative script src, or `null` if none of the configured output targets
3799
+ * produce a browser-loadable entry.
1703
3800
  */
3801
+ function resolveEntryScriptSrc(config) {
3802
+ const outputTargets = config.outputTargets;
3803
+ const wwwTarget = outputTargets.find(isOutputTargetWww);
3804
+ if (wwwTarget?.dir && wwwTarget.buildDir) return toUrl(wwwTarget.dir, wwwTarget.buildDir, `${config.fsNamespace}.js`);
3805
+ const distLazyTarget = outputTargets.find(isOutputTargetDistLazy);
3806
+ const distLazyDir = distLazyTarget?.esmDir ?? distLazyTarget?.dir;
3807
+ if (distLazyDir) return toUrl(config.rootDir, distLazyDir, `${config.fsNamespace}.js`);
3808
+ const standaloneTarget = outputTargets.find(isOutputTargetStandalone);
3809
+ if (standaloneTarget?.dir && standaloneTarget.autoLoader !== false) {
3810
+ const fileName = typeof standaloneTarget.autoLoader === "object" ? standaloneTarget.autoLoader.fileName || "loader" : "loader";
3811
+ return toUrl(config.rootDir, standaloneTarget.dir, `${fileName}.js`);
3812
+ }
3813
+ return null;
3814
+ }
3815
+ function toUrl(base, dir, fileName) {
3816
+ const relativeDir = normalizePath(relative(base, dir), false);
3817
+ return `/${relativeDir ? `${relativeDir}/` : ""}${fileName}`;
3818
+ }
3819
+ //#endregion
3820
+ //#region src/task-generate.ts
3821
+ async function resolveFileTemplates(contrib, ctx) {
3822
+ const { fileTemplates } = contrib;
3823
+ if (!fileTemplates) return [];
3824
+ return typeof fileTemplates === "function" ? fileTemplates(ctx) : fileTemplates;
3825
+ }
1704
3826
  const taskGenerate = async (config, flags) => {
1705
- if (!config.configPath) {
1706
- config.logger.error("Please run this command in your root directory (i. e. the one containing stencil.config.ts).");
3827
+ const srcDir = config.srcDir;
3828
+ if (!srcDir || !existsSync(srcDir)) {
3829
+ config.logger.error("Please run this command in your project root directory.");
1707
3830
  return config.sys.exit(1);
1708
3831
  }
1709
- const absoluteSrcDir = config.srcDir;
1710
- if (!absoluteSrcDir) {
1711
- config.logger.error(`Stencil's srcDir was not specified.`);
1712
- return config.sys.exit(1);
3832
+ const generateContribs = (await discoverPlugins(config.rootDir)).flatMap((d) => d.plugin.generate ? [d.plugin.generate] : []);
3833
+ p.intro("stencil generate");
3834
+ const rawInput = flags.unknownArgs.find((arg) => !arg.startsWith("-"));
3835
+ let input;
3836
+ if (rawInput) input = rawInput;
3837
+ else {
3838
+ const tagName = await p.text({
3839
+ message: "Component tag name (dash-case):",
3840
+ validate: (value) => validateComponentTag(value ?? "")
3841
+ });
3842
+ cancelIfAborted(tagName);
3843
+ input = tagName;
1713
3844
  }
1714
- const { prompt } = await import("prompts");
1715
- const input = flags.unknownArgs.find((arg) => !arg.startsWith("-")) || (await prompt({
1716
- name: "tagName",
1717
- type: "text",
1718
- message: "Component tag name (dash-case):"
1719
- })).tagName;
1720
- if (void 0 === input) return;
1721
3845
  const { dir, base: componentName } = parse(input);
1722
3846
  const tagError = validateComponentTag(componentName);
1723
3847
  if (tagError) {
1724
3848
  config.logger.error(tagError);
1725
3849
  return config.sys.exit(1);
1726
3850
  }
1727
- let cssExtension = "css";
1728
- if (config.plugins?.find((plugin) => plugin.name === "sass")) cssExtension = await chooseSassExtension();
1729
- else if (config.plugins?.find((plugin) => plugin.name === "less")) cssExtension = "less";
1730
- const filesToGenerateExt = await chooseFilesToGenerate(cssExtension);
1731
- if (!filesToGenerateExt) return;
1732
- const extensionsToGenerate = ["tsx", ...filesToGenerateExt];
1733
- const testFolder = extensionsToGenerate.some(isTest) ? "test" : "";
1734
- const outDir = join(absoluteSrcDir, "components", dir, componentName);
1735
- await config.sys.createDir(normalizePath(join(outDir, testFolder)), { recursive: true });
1736
- const filesToGenerate = extensionsToGenerate.map((extension) => ({
1737
- extension,
1738
- path: getFilepathForFile(outDir, componentName, extension)
1739
- }));
1740
- await checkForOverwrite(filesToGenerate, config);
1741
- const writtenFiles = await Promise.all(filesToGenerate.map((file) => getBoilerplateAndWriteFile(config, componentName, extensionsToGenerate.includes("css") || extensionsToGenerate.includes("sass") || extensionsToGenerate.includes("scss") || extensionsToGenerate.includes("less"), file, cssExtension))).catch((error) => config.logger.error(error));
1742
- if (!writtenFiles) return config.sys.exit(1);
1743
- console.log();
1744
- console.log(`${config.logger.gray("$")} stencil generate ${input}`);
1745
- console.log();
1746
- console.log(config.logger.bold("The following files have been generated:"));
1747
- const absoluteRootDir = config.rootDir;
1748
- writtenFiles.map((file) => console.log(` - ${relative(absoluteRootDir, file)}`));
1749
- };
1750
- /**
1751
- * Show a checkbox prompt to select the files to be generated.
1752
- *
1753
- * @param cssExtension the extension of the CSS file to be generated
1754
- * @returns a read-only array of `GeneratableExtension`, the extensions that the user has decided
1755
- * to generate
1756
- */
1757
- const chooseFilesToGenerate = async (cssExtension) => {
1758
- const { prompt } = await import("prompts");
1759
- return (await prompt({
1760
- name: "filesToGenerate",
1761
- type: "multiselect",
1762
- message: "Which additional files do you want to generate?",
1763
- choices: [
3851
+ const styleOptions = [
3852
+ {
3853
+ value: "css",
3854
+ label: "CSS (.css)"
3855
+ },
3856
+ ...[...new Set(generateContribs.flatMap((c) => c.styleExtensions ?? []))].map((ext) => ({
3857
+ value: ext,
3858
+ label: `${ext.toUpperCase()} (.${ext})`
3859
+ })),
3860
+ {
3861
+ value: "",
3862
+ label: "None"
3863
+ }
3864
+ ];
3865
+ const stylePick = await p.select({
3866
+ message: "Stylesheet format:",
3867
+ options: styleOptions
3868
+ });
3869
+ cancelIfAborted(stylePick);
3870
+ const styleExtension = stylePick || void 0;
3871
+ const demoPick = await p.select({
3872
+ message: "Demo:",
3873
+ options: [
1764
3874
  {
1765
- value: cssExtension,
1766
- title: `Stylesheet (.${cssExtension})`,
1767
- selected: true
3875
+ value: "usage",
3876
+ label: "Usage example",
3877
+ hint: "usage/example.md - rendered in docs and the dev server auto-preview"
1768
3878
  },
1769
3879
  {
1770
- value: "spec.tsx",
1771
- title: "Spec Test (.spec.tsx)",
1772
- selected: true
3880
+ value: "preview",
3881
+ label: "Preview page",
3882
+ hint: "index.html - full control, opts out of the dev server auto-preview"
1773
3883
  },
1774
3884
  {
1775
- value: "e2e.ts",
1776
- title: "E2E Test (.e2e.ts)",
1777
- selected: true
3885
+ value: "",
3886
+ label: "None"
1778
3887
  }
1779
3888
  ]
1780
- })).filesToGenerate;
1781
- };
1782
- const chooseSassExtension = async () => {
1783
- const { prompt } = await import("prompts");
1784
- return (await prompt({
1785
- name: "sassFormat",
1786
- type: "select",
1787
- message: "Which Sass format would you like to use? (More info: https://sass-lang.com/documentation/syntax/#the-indented-syntax)",
1788
- choices: [{
1789
- value: "sass",
1790
- title: `*.sass Format`,
1791
- selected: true
1792
- }, {
1793
- value: "scss",
1794
- title: "*.scss Format"
1795
- }]
1796
- })).sassFormat;
1797
- };
1798
- /**
1799
- * Get a filepath for a file we want to generate!
1800
- *
1801
- * The filepath for a given file depends on the path, the user-supplied
1802
- * component name, the extension, and whether we're inside of a test directory.
1803
- *
1804
- * @param filePath path to where we're going to generate the component
1805
- * @param componentName the user-supplied name for the generated component
1806
- * @param extension the file extension
1807
- * @returns the full filepath to the component (with a possible `test` directory
1808
- * added)
1809
- */
1810
- const getFilepathForFile = (filePath, componentName, extension) => isTest(extension) ? normalizePath(join(filePath, "test", `${componentName}.${extension}`)) : normalizePath(join(filePath, `${componentName}.${extension}`));
1811
- /**
1812
- * Get the boilerplate for a file and write it to disk
1813
- *
1814
- * @param config the current config, needed for file operations
1815
- * @param componentName the component name (user-supplied)
1816
- * @param withCss are we generating CSS?
1817
- * @param file the file we want to write
1818
- * @param styleExtension extension used for styles
1819
- * @returns a `Promise<string>` which holds the full filepath we've written to,
1820
- * used to print out a little summary of our activity to the user.
1821
- */
1822
- const getBoilerplateAndWriteFile = async (config, componentName, withCss, file, styleExtension) => {
1823
- const boilerplate = getBoilerplateByExtension(componentName, file.extension, withCss, styleExtension);
1824
- await config.sys.writeFile(normalizePath(file.path), boilerplate);
1825
- return file.path;
1826
- };
1827
- /**
1828
- * Check to see if any of the files we plan to write already exist and would
1829
- * therefore be overwritten if we proceed, because we'd like to not overwrite
1830
- * people's code!
1831
- *
1832
- * This function will check all the filepaths and if it finds any files log an
1833
- * error and exit with an error code. If it doesn't find anything it will just
1834
- * peacefully return `Promise<void>`.
1835
- *
1836
- * @param files the files we want to check
1837
- * @param config the Config object, used here to get access to `sys.readFile`
1838
- */
1839
- const checkForOverwrite = async (files, config) => {
1840
- const alreadyPresent = [];
1841
- await Promise.all(files.map(async ({ path }) => {
1842
- if (await config.sys.readFile(path) !== void 0) alreadyPresent.push(path);
1843
- }));
1844
- if (alreadyPresent.length > 0) {
1845
- config.logger.error("Generating code would overwrite the following files:", ...alreadyPresent.map((path) => " " + normalizePath(path)));
1846
- await config.sys.exit(1);
3889
+ });
3890
+ cancelIfAborted(demoPick);
3891
+ const generateCtx = {
3892
+ tagName: componentName,
3893
+ config: toProjectConfig(config),
3894
+ prompts: p,
3895
+ nypm
3896
+ };
3897
+ const allFileTemplates = [];
3898
+ for (const contrib of generateContribs) allFileTemplates.push(...await resolveFileTemplates(contrib, generateCtx));
3899
+ let pickedExtensions = [];
3900
+ if (allFileTemplates.length > 0) {
3901
+ const filePick = await p.multiselect({
3902
+ message: "Additional files:",
3903
+ options: allFileTemplates.map((ft) => ({
3904
+ value: ft.extension,
3905
+ label: ft.label
3906
+ })),
3907
+ initialValues: allFileTemplates.filter((ft) => ft.selectedByDefault !== false).map((ft) => ft.extension),
3908
+ required: false
3909
+ });
3910
+ cancelIfAborted(filePick);
3911
+ pickedExtensions = filePick;
1847
3912
  }
1848
- };
1849
- /**
1850
- * Check if an extension is for a test
1851
- *
1852
- * @param extension the extension we want to check
1853
- * @returns a boolean indicating whether or not its a test
1854
- */
1855
- const isTest = (extension) => {
1856
- return extension === "e2e.ts" || extension === "spec.tsx";
1857
- };
1858
- /**
1859
- * Get the boilerplate for a file by its extension.
1860
- *
1861
- * @param tagName the name of the component we're generating
1862
- * @param extension the file extension we want boilerplate for (.css, tsx, etc)
1863
- * @param withCss a boolean indicating whether we're generating a CSS file
1864
- * @param styleExtension extension used for styles
1865
- * @returns a string container the file boilerplate for the supplied extension
1866
- */
1867
- const getBoilerplateByExtension = (tagName, extension, withCss, styleExtension) => {
1868
- switch (extension) {
1869
- case "tsx": return getComponentBoilerplate(tagName, withCss, styleExtension);
1870
- case "css":
1871
- case "less":
1872
- case "sass":
1873
- case "scss": return getStyleUrlBoilerplate(styleExtension);
1874
- case "spec.tsx": return getSpecTestBoilerplate(tagName);
1875
- case "e2e.ts": return getE2eTestBoilerplate(tagName);
1876
- default: throw new Error(`Unkown extension "${extension}".`);
3913
+ const outDir = join(srcDir, "components", dir, componentName);
3914
+ const className = toPascalCase(componentName);
3915
+ const filesToWrite = [];
3916
+ filesToWrite.push({
3917
+ absPath: normalizePath(join(outDir, `${componentName}.tsx`)),
3918
+ content: getComponentBoilerplate(componentName, styleExtension)
3919
+ });
3920
+ if (styleExtension) filesToWrite.push({
3921
+ absPath: normalizePath(join(outDir, `${componentName}.${styleExtension}`)),
3922
+ content: getStyleBoilerplate(styleExtension)
3923
+ });
3924
+ for (const ext of pickedExtensions) {
3925
+ const tmpl = allFileTemplates.find((ft) => ft.extension === ext);
3926
+ const absPath = normalizePath(join(outDir, tmpl.subdirectory ?? "", `${componentName}.${ext}`));
3927
+ filesToWrite.push({
3928
+ absPath,
3929
+ content: tmpl.template(componentName, className)
3930
+ });
1877
3931
  }
3932
+ if (demoPick === "usage") filesToWrite.push({
3933
+ absPath: normalizePath(join(outDir, "usage", "example.md")),
3934
+ content: getUsageExampleBoilerplate(componentName)
3935
+ });
3936
+ else if (demoPick === "preview") filesToWrite.push({
3937
+ absPath: normalizePath(join(outDir, "index.html")),
3938
+ content: getPreviewHtmlBoilerplate(componentName, resolveEntryScriptSrc(config))
3939
+ });
3940
+ const wouldOverwrite = (await Promise.all(filesToWrite.map(async ({ absPath }) => await config.sys.readFile(absPath) !== void 0 ? absPath : null))).filter((f) => f !== null);
3941
+ if (wouldOverwrite.length > 0) {
3942
+ config.logger.error("Generating code would overwrite the following files:", ...wouldOverwrite.map((path) => " " + normalizePath(path)));
3943
+ await config.sys.exit(1);
3944
+ return;
3945
+ }
3946
+ const dirs = [...new Set(filesToWrite.map(({ absPath }) => normalizePath(join(absPath, ".."))))];
3947
+ await Promise.all(dirs.map((d) => config.sys.createDir(d, { recursive: true })));
3948
+ await Promise.all(filesToWrite.map(({ absPath, content }) => config.sys.writeFile(absPath, content)));
3949
+ p.note(filesToWrite.map(({ absPath }) => relative(config.rootDir, absPath)).join("\n"), "Generated");
3950
+ p.outro(`stencil generate ${input}`);
1878
3951
  };
1879
- /**
1880
- * Get the boilerplate for a file containing the definition of a component
1881
- * @param tagName the name of the tag to give the component
1882
- * @param hasStyle designates if the component has an external stylesheet or not
1883
- * @param styleExtension extension used for styles
1884
- * @returns the contents of a file that defines a component
1885
- */
1886
- const getComponentBoilerplate = (tagName, hasStyle, styleExtension) => {
1887
- const decorator = [`{`];
1888
- decorator.push(` tag: '${tagName}',`);
1889
- if (hasStyle) decorator.push(` styleUrl: '${tagName}.${styleExtension}',`);
1890
- decorator.push(` shadow: true,`);
1891
- decorator.push(`}`);
1892
- return `import { Component, Host, h } from '@stencil/core';
1893
-
1894
- @Component(${decorator.join("\n")})
1895
- export class ${toPascalCase(tagName)} {
1896
- render() {
1897
- return (
1898
- <Host>
1899
- <slot></slot>
1900
- </Host>
1901
- );
1902
- }
1903
- }
1904
- `;
1905
- };
1906
- /**
1907
- * Get the boilerplate for style for a generated component
1908
- * @param ext extension used for styles
1909
- * @returns a boilerplate CSS block
1910
- */
1911
- const getStyleUrlBoilerplate = (ext) => ext === "sass" ? `:host
1912
- display: block
1913
- ` : `:host {
1914
- display: block;
1915
- }
1916
- `;
1917
- /**
1918
- * Get the boilerplate for a file containing a spec (unit) test for a component
1919
- * @param tagName the name of the tag associated with the component under test
1920
- * @returns the contents of a file that unit tests a component
1921
- */
1922
- const getSpecTestBoilerplate = (tagName) => `import { newSpecPage } from '@stencil/core/testing';
1923
- import { ${toPascalCase(tagName)} } from '../${tagName}';
1924
-
1925
- describe('${tagName}', () => {
1926
- it('renders', async () => {
1927
- const page = await newSpecPage({
1928
- components: [${toPascalCase(tagName)}],
1929
- html: \`<${tagName}></${tagName}>\`,
1930
- });
1931
- expect(page.root).toEqualHtml(\`
1932
- <${tagName}>
1933
- <mock:shadow-root>
1934
- <slot></slot>
1935
- </mock:shadow-root>
1936
- </${tagName}>
1937
- \`);
1938
- });
1939
- });
1940
- `;
1941
- /**
1942
- * Get the boilerplate for a file containing an end-to-end (E2E) test for a component
1943
- * @param tagName the name of the tag associated with the component under test
1944
- * @returns the contents of a file that E2E tests a component
1945
- */
1946
- const getE2eTestBoilerplate = (tagName) => `import { newE2EPage } from '@stencil/core/testing';
1947
-
1948
- describe('${tagName}', () => {
1949
- it('renders', async () => {
1950
- const page = await newE2EPage();
1951
- await page.setContent('<${tagName}></${tagName}>');
1952
-
1953
- const element = await page.find('${tagName}');
1954
- expect(element).toHaveClass('hydrated');
1955
- });
1956
- });
1957
- `;
1958
- /**
1959
- * Convert a dash case string to pascal case.
1960
- * @param str the string to convert
1961
- * @returns the converted input as pascal case
1962
- */
1963
- const toPascalCase = (str) => str.split("-").reduce((res, part) => res + part[0].toUpperCase() + part.slice(1), "");
1964
3952
  //#endregion
1965
3953
  //#region src/task-telemetry.ts
1966
3954
  /**
@@ -2074,6 +4062,415 @@ const taskInfo = (coreCompiler, sys, logger) => {
2074
4062
  console.log(``);
2075
4063
  };
2076
4064
  //#endregion
4065
+ //#region src/wizard/init/apply.ts
4066
+ /**
4067
+ * Copy component-starter template into rootDir, interpolating project name and namespace.
4068
+ *
4069
+ * @param rootDir - Destination directory (typically `process.cwd()`).
4070
+ * @param projectName - Value to substitute for `{{PROJECT_NAME}}` placeholders.
4071
+ * @param namespace - Value to substitute for `{{NAMESPACE}}` placeholders.
4072
+ * @param stencilVersion - Optional version to substitute for `{{STENCIL_VERSION}}` placeholders.
4073
+ */
4074
+ async function copyTemplate(rootDir, projectName, namespace, stencilVersion) {
4075
+ const templateDir = getTemplatePath("component-starter");
4076
+ const entries = await readdir(templateDir, {
4077
+ recursive: true,
4078
+ withFileTypes: true
4079
+ });
4080
+ const resolvedStencilVersion = stencilVersion ?? "^5.0.0";
4081
+ for (const entry of entries) {
4082
+ if (!entry.isFile()) continue;
4083
+ const srcPath = join(entry.parentPath, entry.name);
4084
+ let relPath = relative(templateDir, srcPath);
4085
+ if (relPath === "_gitignore") relPath = ".gitignore";
4086
+ const destPath = join(rootDir, relPath);
4087
+ await mkdir(dirname(destPath), { recursive: true });
4088
+ const content = (await readFile(srcPath, "utf8")).replace(/\{\{PROJECT_NAME\}\}/g, projectName).replace(/\{\{NAMESPACE\}\}/g, namespace).replace(/\{\{STENCIL_VERSION\}\}/g, resolvedStencilVersion);
4089
+ if (relPath === "package.json") await mergePackageJson(destPath, content);
4090
+ else if (relPath === "tsconfig.json") await mergeTsConfig(destPath, content);
4091
+ else if (relPath === ".gitignore") await mergeGitignore(destPath, content);
4092
+ else await writeIfAbsent(destPath, content);
4093
+ }
4094
+ }
4095
+ const PARCEL_WATCHER_BUILD_ALLOWANCES = [
4096
+ `onlyBuiltDependencies:`,
4097
+ ` - '@parcel/watcher'`,
4098
+ ``,
4099
+ `allowBuilds:`,
4100
+ ` '@parcel/watcher': true`
4101
+ ].join("\n");
4102
+ async function mergePnpmWorkspaceYaml(yamlPath) {
4103
+ let existing = null;
4104
+ try {
4105
+ existing = await readFile(yamlPath, "utf8");
4106
+ } catch {}
4107
+ if (existing === null) {
4108
+ await writeFile(yamlPath, [
4109
+ `packages:`,
4110
+ ` - 'packages/*'`,
4111
+ ``,
4112
+ PARCEL_WATCHER_BUILD_ALLOWANCES,
4113
+ ``
4114
+ ].join("\n"), "utf8");
4115
+ return;
4116
+ }
4117
+ let toAppend = "";
4118
+ if (!existing.includes("packages/*")) toAppend += `\npackages:\n - 'packages/*'\n`;
4119
+ if (!existing.includes("onlyBuiltDependencies:")) toAppend += `\nonlyBuiltDependencies:\n - '@parcel/watcher'\n`;
4120
+ if (!existing.includes("allowBuilds:")) toAppend += `\nallowBuilds:\n '@parcel/watcher': true\n`;
4121
+ if (toAppend) {
4122
+ const separator = existing.endsWith("\n") ? "" : "\n";
4123
+ await writeFile(yamlPath, existing + separator + toAppend, "utf8");
4124
+ }
4125
+ }
4126
+ async function writeIfAbsent(destPath, content) {
4127
+ try {
4128
+ await writeFile(destPath, content, {
4129
+ encoding: "utf8",
4130
+ flag: "wx"
4131
+ });
4132
+ } catch (e) {
4133
+ if (e.code !== "EEXIST") throw e;
4134
+ }
4135
+ }
4136
+ async function mergePackageJson(destPath, templateContent) {
4137
+ const template = JSON.parse(templateContent);
4138
+ let existing;
4139
+ try {
4140
+ existing = JSON.parse(await readFile(destPath, "utf8"));
4141
+ } catch {
4142
+ await writeFile(destPath, templateContent, "utf8");
4143
+ return;
4144
+ }
4145
+ const dependencies = mergeStringRecord(template.dependencies, existing.dependencies);
4146
+ const devDependencies = mergeStringRecord(template.devDependencies, existing.devDependencies);
4147
+ for (const pkg of Object.keys(devDependencies)) if (pkg in dependencies) delete devDependencies[pkg];
4148
+ const merged = {
4149
+ ...template,
4150
+ ...existing,
4151
+ scripts: mergeStringRecord(template.scripts, existing.scripts),
4152
+ dependencies,
4153
+ devDependencies
4154
+ };
4155
+ await writeFile(destPath, JSON.stringify(merged, null, 2) + "\n", "utf8");
4156
+ }
4157
+ async function mergeTsConfig(destPath, templateContent) {
4158
+ const template = JSON.parse(templateContent);
4159
+ let existing;
4160
+ try {
4161
+ existing = JSON.parse(await readFile(destPath, "utf8"));
4162
+ } catch {
4163
+ await writeFile(destPath, templateContent, "utf8");
4164
+ return;
4165
+ }
4166
+ const merged = {
4167
+ ...template,
4168
+ ...existing,
4169
+ compilerOptions: mergeStringRecord(template.compilerOptions, existing.compilerOptions)
4170
+ };
4171
+ await writeFile(destPath, JSON.stringify(merged, null, 2) + "\n", "utf8");
4172
+ }
4173
+ async function mergeGitignore(destPath, templateContent) {
4174
+ let existing;
4175
+ try {
4176
+ existing = await readFile(destPath, "utf8");
4177
+ } catch {
4178
+ await writeFile(destPath, templateContent, "utf8");
4179
+ return;
4180
+ }
4181
+ const existingEntries = new Set(existing.split("\n").map((l) => l.trim()).filter(Boolean));
4182
+ const missing = templateContent.split("\n").filter((line) => line.trim() && !existingEntries.has(line.trim()));
4183
+ if (missing.length === 0) return;
4184
+ const separator = existing.endsWith("\n") ? "" : "\n";
4185
+ await writeFile(destPath, existing + separator + missing.join("\n") + "\n", "utf8");
4186
+ }
4187
+ function mergeStringRecord(base, override) {
4188
+ const toObj = (v) => v !== null && typeof v === "object" ? v : {};
4189
+ return {
4190
+ ...toObj(base),
4191
+ ...toObj(override)
4192
+ };
4193
+ }
4194
+ async function writeStencilConfig(rootDir, content) {
4195
+ await writeFile(join(rootDir, "stencil.config.ts"), content, "utf8");
4196
+ }
4197
+ async function writeGlobalStyle(rootDir) {
4198
+ const path = join(rootDir, "src", "global.css");
4199
+ await mkdir(dirname(path), { recursive: true });
4200
+ await writeIfAbsent(path, `@import "stencil-globals";\n@import "stencil-hydrate";\n`);
4201
+ }
4202
+ async function writeGlobalScript(rootDir) {
4203
+ const path = join(rootDir, "src", "global.ts");
4204
+ await mkdir(dirname(path), { recursive: true });
4205
+ await writeIfAbsent(path, `export default function (): void {}\n`);
4206
+ }
4207
+ async function writeIndexHtml(rootDir, content) {
4208
+ const path = join(rootDir, "src", "index.html");
4209
+ await mkdir(dirname(path), { recursive: true });
4210
+ await writeIfAbsent(path, content);
4211
+ }
4212
+ function workspaceBuildScript(pm, coreName) {
4213
+ switch (pm) {
4214
+ case "pnpm": return "pnpm -r build";
4215
+ case "yarn": return "yarn workspaces run build";
4216
+ case "bun": return "bun run --filter \"*\" build";
4217
+ default: return `npm run build -w packages/${coreName} && npm run build --workspaces --if-present`;
4218
+ }
4219
+ }
4220
+ /**
4221
+ * Scaffold a workspace root in `cwd`: creates `packages/`, writes the appropriate
4222
+ * workspace manifest (`pnpm-workspace.yaml` for pnpm, `workspaces` field in
4223
+ * `package.json` for npm / yarn / bun), and ensures a root `package.json` exists.
4224
+ * @param cwd - Absolute path to the workspace root (where `package.json` will be created).
4225
+ * @param projectName - Name to use for the root package.json (typically the project name).
4226
+ * @param coreName - Directory name of the core package under `packages/` (e.g. `core`).
4227
+ * @returns A promise that resolves when the workspace root has been scaffolded.
4228
+ */
4229
+ async function scaffoldWorkspaceRoot(cwd, projectName, coreName) {
4230
+ await mkdir(join(cwd, "packages"), { recursive: true });
4231
+ const pm = await detectPackageManager(cwd);
4232
+ const usePnpmYaml = pm?.name === "pnpm";
4233
+ const pkgPath = join(cwd, "package.json");
4234
+ let pkg;
4235
+ try {
4236
+ pkg = JSON.parse(await readFile(pkgPath, "utf8"));
4237
+ } catch {
4238
+ pkg = {};
4239
+ }
4240
+ pkg.name ??= `${projectName}-workspace`;
4241
+ pkg.version ??= "0.0.1";
4242
+ pkg.private = true;
4243
+ pkg.scripts = {
4244
+ build: workspaceBuildScript(pm?.name, coreName),
4245
+ ...pkg.scripts
4246
+ };
4247
+ if (!usePnpmYaml) pkg.workspaces = ["packages/*"];
4248
+ delete pkg.dependencies;
4249
+ delete pkg.devDependencies;
4250
+ await writeFile(pkgPath, JSON.stringify(pkg, null, 2) + "\n", "utf8");
4251
+ if (usePnpmYaml) await mergePnpmWorkspaceYaml(join(cwd, "pnpm-workspace.yaml"));
4252
+ }
4253
+ /**
4254
+ * Write output-driven distributable fields (type, module, types) into package.json.
4255
+ * These fields depend on which outputs the user selected, so they cannot be static in the template.
4256
+ * Skips if fields is empty (e.g. www-only project).
4257
+ *
4258
+ * @param rootDir - Absolute path to the project root.
4259
+ * @param fields - Fields to write, from generatePackageJsonFields().
4260
+ */
4261
+ async function applyPackageJsonFields(rootDir, fields) {
4262
+ if (Object.keys(fields).length === 0) return;
4263
+ const pkgPath = join(rootDir, "package.json");
4264
+ const pkg = JSON.parse(await readFile(pkgPath, "utf8"));
4265
+ Object.assign(pkg, fields);
4266
+ await writeFile(pkgPath, JSON.stringify(pkg, null, 2) + "\n", "utf8");
4267
+ }
4268
+ //#endregion
4269
+ //#region src/task-init.ts
4270
+ /**
4271
+ * Package managers can report success while silently failing to write to node_modules.
4272
+ * Confirms packages actually landed on disk instead of trusting the install call's exit code.
4273
+ *
4274
+ * @param rootDir - directory to resolve packages from.
4275
+ * @param packageNames - packages that were just supposed to be installed.
4276
+ */
4277
+ async function verifyInstalled(rootDir, packageNames) {
4278
+ const missing = [];
4279
+ for (const name of packageNames) if (!await getPackageInfo(name, { paths: [rootDir] })) missing.push(name);
4280
+ if (missing.length === 0) return;
4281
+ p.log.error(`Install reported success but ${missing.join(", ")} could not be found in ${rootDir}. Your package manager may have silently failed to write to node_modules - check its logs and try again.`);
4282
+ process.exit(1);
4283
+ }
4284
+ /**
4285
+ * npm silently omits devDependencies when this CLI is itself running as a nested child
4286
+ * process (e.g. via `npx create-stencil` / `npm init stencil`). Root cause: npm/exec only
4287
+ * needs @stencil/cli's own regular dependencies to resolve+run it, so that install computes
4288
+ * `omit: ['dev']` - and per npm's own config flattening
4289
+ * (@npmcli/config/lib/definitions/definitions.js), whenever `omit` includes 'dev' npm sets
4290
+ * `process.env.NODE_ENV = 'production'` on itself. We inherit that env var from the outer
4291
+ * npm/npx process, and every child process we (or a wizard plugin) spawn from here would
4292
+ * inherit it right back, causing nested `npm install`s to also compute `omit: ['dev']` and
4293
+ * silently drop (or, worse, actively remove) every devDependency in the scaffolded project.
4294
+ * Clearing it once, up front, fixes every install call transitively - ours and every wizard
4295
+ * plugin's - without needing to special-case npm invocations one by one.
4296
+ */
4297
+ function clearInheritedProductionEnv() {
4298
+ if (process.env.NODE_ENV === "production") delete process.env.NODE_ENV;
4299
+ }
4300
+ function outputKeysToTargets(keys) {
4301
+ const map = {
4302
+ loader: "loader-bundle",
4303
+ standalone: "standalone",
4304
+ ssr: "ssr",
4305
+ "ssr-wasm": "ssr-wasm",
4306
+ www: "www"
4307
+ };
4308
+ return keys.length > 0 ? keys.map((k) => ({ type: map[k] })) : [{ type: "loader-bundle" }];
4309
+ }
4310
+ async function taskInit(coreCompiler, strictConfig, loadProjectConfig) {
4311
+ clearInheritedProductionEnv();
4312
+ const cwd = process.cwd();
4313
+ const isExistingProject = await isExistingStencilProject(cwd);
4314
+ printSplash();
4315
+ p.intro(`stencil init`);
4316
+ if (process.env.STENCIL_WIZARD_DEV) p.log.warn(`Dev mode: loading wizards from ${process.env.STENCIL_WIZARD_DEV}`);
4317
+ if (isCI) {
4318
+ p.log.warn("Running in CI - non-interactive mode is not yet supported for `stencil init`.");
4319
+ process.exit(1);
4320
+ }
4321
+ if (isExistingProject) {
4322
+ await addCapabilities(cwd, strictConfig);
4323
+ return;
4324
+ }
4325
+ const projectName = await promptProjectName();
4326
+ const namespace = toNamespace(projectName);
4327
+ const outputs = await promptOutputs();
4328
+ const features = await promptFeatures();
4329
+ const docs = await promptDocs();
4330
+ const selectedIntegrations = await promptIntegrations();
4331
+ let monorepo = false;
4332
+ let coreName = "";
4333
+ if (hasFrameworkTargets(selectedIntegrations)) {
4334
+ monorepo = await promptMonorepo();
4335
+ if (monorepo) coreName = await promptWorkspaceCoreName();
4336
+ }
4337
+ const configSource = generateStencilConfig({
4338
+ namespace,
4339
+ outputs,
4340
+ signals: features.signals,
4341
+ docs
4342
+ }) ?? (needsStencilConfig(selectedIntegrations) ? `import { Config } from '@stencil/core';\n\nexport const config: Config = {\n namespace: '${namespace}',\n outputTargets: [{ type: 'loader-bundle' }],\n};\n` : null);
4343
+ const summaryLines = [
4344
+ `Template: component-starter`,
4345
+ `Name: ${projectName}`,
4346
+ `Namespace: ${namespace}`,
4347
+ `Config: ${configSource ? "stencil.config.ts" : "zero-config (loader default)"}`
4348
+ ];
4349
+ if (monorepo) {
4350
+ summaryLines.push(`Structure: monorepo workspace`);
4351
+ summaryLines.push(`Core: packages/${coreName}/`);
4352
+ }
4353
+ if (selectedIntegrations.length > 0) summaryLines.push(`Add: ${selectedIntegrations.map((i) => i.displayName).join(", ")}`);
4354
+ p.note(summaryLines.join("\n"), "Summary");
4355
+ const coreDir = monorepo ? join(cwd, "packages", coreName) : cwd;
4356
+ const s1 = p.spinner();
4357
+ s1.start("Scaffolding project files");
4358
+ if (monorepo) await scaffoldWorkspaceRoot(cwd, projectName, coreName);
4359
+ await copyTemplate(coreDir, projectName, namespace, coreCompiler?.version);
4360
+ await applyPackageJsonFields(coreDir, generatePackageJsonFields(outputs));
4361
+ if (configSource) await writeStencilConfig(coreDir, configSource);
4362
+ if (features.globalStyle) await writeGlobalStyle(coreDir);
4363
+ if (features.globalScript) await writeGlobalScript(coreDir);
4364
+ if (outputs.includes("www")) await writeIndexHtml(coreDir, generateIndexHtml({
4365
+ projectName,
4366
+ namespace,
4367
+ globalStyle: features.globalStyle
4368
+ }));
4369
+ s1.stop("Project files created");
4370
+ const s2 = p.spinner();
4371
+ s2.start("Installing dependencies");
4372
+ await nypm.installDependencies({
4373
+ cwd,
4374
+ silent: true
4375
+ });
4376
+ s2.stop("Dependencies installed");
4377
+ await verifyInstalled(coreDir, ["@stencil/core"]);
4378
+ if (selectedIntegrations.length > 0) {
4379
+ const s3 = p.spinner();
4380
+ const pkgs = selectedIntegrations.map((i) => i.package);
4381
+ s3.start(`Installing ${pkgs.join(", ")}`);
4382
+ await nypm.addDevDependency(withVersionRanges(pkgs), {
4383
+ cwd: coreDir,
4384
+ silent: true
4385
+ });
4386
+ s3.stop("Integrations installed");
4387
+ await verifyInstalled(coreDir, pkgs);
4388
+ }
4389
+ if (selectedIntegrations.length > 0) {
4390
+ const discovered = await discoverPlugins(coreDir);
4391
+ const selectedPkgs = new Set(selectedIntegrations.map((i) => i.package));
4392
+ const resolvedValidated = loadProjectConfig && configSource ? await loadProjectConfig(join(coreDir, "stencil.config.ts")) : coreCompiler ? coreCompiler.validateConfig({
4393
+ rootDir: coreDir,
4394
+ outputTargets: outputKeysToTargets(outputs),
4395
+ ...configSource ? { namespace } : {}
4396
+ }, {}).config : null;
4397
+ const projectConfig = resolvedValidated ? {
4398
+ ...toProjectConfig(resolvedValidated),
4399
+ rootDir: coreDir
4400
+ } : defaultProjectConfig(coreDir, { namespace });
4401
+ for (const d of discovered) if (selectedPkgs.has(d.packageName) && d.plugin.init?.run) await d.plugin.init.run({
4402
+ isNewProject: true,
4403
+ prompts: p,
4404
+ nypm,
4405
+ config: projectConfig,
4406
+ workspaceRoot: monorepo ? cwd : void 0,
4407
+ ts,
4408
+ openStencilConfig: () => openStencilConfig(join(projectConfig.rootDir, "stencil.config.ts"))
4409
+ });
4410
+ }
4411
+ const pm = (await nypm.detectPackageManager(cwd))?.name ?? "npm";
4412
+ const devDir = monorepo ? `packages/${coreName}` : null;
4413
+ const devCmd = `${pm} run dev`;
4414
+ p.outro(devDir ? `Your project is ready!\n cd ${devDir}\n ${devCmd}` : `Your project is ready! Run: ${devCmd}`);
4415
+ }
4416
+ async function addCapabilities(cwd, strictConfig) {
4417
+ const workspaceRoot = await detectWorkspaceRoot(cwd);
4418
+ const raw = JSON.parse(await readFile(join(cwd, "package.json"), "utf8"));
4419
+ const installed = /* @__PURE__ */ new Set([...Object.keys(raw.dependencies ?? {}), ...Object.keys(raw.devDependencies ?? {})]);
4420
+ const discovered = await discoverPlugins(cwd);
4421
+ const configurable = discovered.filter((d) => d.plugin.init);
4422
+ const installable = KNOWN_INTEGRATIONS.filter((i) => !installed.has(i.package));
4423
+ if (installable.length === 0 && configurable.length === 0) {
4424
+ p.log.info("All known integrations are already installed and configured.");
4425
+ p.outro("Nothing to do.");
4426
+ return;
4427
+ }
4428
+ const { toInstall, toConfigure } = await promptAddCapabilities(installable, configurable);
4429
+ if (toInstall.length === 0 && toConfigure.length === 0) {
4430
+ p.outro("No changes made.");
4431
+ return;
4432
+ }
4433
+ const summaryLines = [];
4434
+ for (const i of toInstall) summaryLines.push(`Install: ${i.displayName}`);
4435
+ for (const d of toConfigure) summaryLines.push(`Configure: ${d.plugin.init.displayName}`);
4436
+ p.note(summaryLines.join("\n"), "Summary");
4437
+ const confirmed = await p.confirm({ message: "Apply changes?" });
4438
+ cancelIfAborted(confirmed);
4439
+ if (!confirmed) {
4440
+ p.cancel("Cancelled.");
4441
+ process.exit(0);
4442
+ }
4443
+ if (toInstall.length > 0) {
4444
+ const s = p.spinner();
4445
+ const pkgs = toInstall.map((i) => i.package);
4446
+ s.start(`Installing ${pkgs.join(", ")}`);
4447
+ await nypm.addDevDependency(withVersionRanges(pkgs), {
4448
+ cwd,
4449
+ silent: true
4450
+ });
4451
+ s.stop("Dependencies installed");
4452
+ await verifyInstalled(cwd, pkgs);
4453
+ }
4454
+ const allDiscovered = toInstall.length > 0 ? await discoverPlugins(cwd) : discovered;
4455
+ const newlyInstalledPkgs = new Set(toInstall.map((i) => i.package));
4456
+ const toRun = [...allDiscovered.filter((d) => newlyInstalledPkgs.has(d.packageName)), ...toConfigure].filter((d) => d.plugin.init?.run);
4457
+ const projectConfig = strictConfig ? toProjectConfig(strictConfig) : defaultProjectConfig(cwd);
4458
+ for (const d of toRun) await d.plugin.init.run({
4459
+ isNewProject: false,
4460
+ prompts: p,
4461
+ nypm,
4462
+ config: projectConfig,
4463
+ workspaceRoot,
4464
+ ts,
4465
+ openStencilConfig: () => openStencilConfig(join(projectConfig.rootDir, "stencil.config.ts"))
4466
+ });
4467
+ p.outro("Done! Run pnpm run dev to continue.");
4468
+ }
4469
+ function toNamespace(name) {
4470
+ const base = name.replace(/^@[^/]+\//, "");
4471
+ return toPascalCase(base.replace(/[/_]/g, "-"));
4472
+ }
4473
+ //#endregion
2077
4474
  //#region src/task-serve.ts
2078
4475
  const taskServe = async (config, flags) => {
2079
4476
  config.suppressLogs = true;
@@ -2129,6 +4526,41 @@ const run = async (init) => {
2129
4526
  }), logger, sys);
2130
4527
  return;
2131
4528
  }
4529
+ if (task === "add" || task === "init") {
4530
+ const coreCompiler = await loadCoreCompiler(sys);
4531
+ const rootDir = sys.getCurrentDirectory();
4532
+ const findConfigResults = await findConfig({
4533
+ sys,
4534
+ configPath: flags.config
4535
+ });
4536
+ let strictConfig;
4537
+ const foundConfigPath = !findConfigResults.isErr ? result.unwrap(findConfigResults).configPath : null;
4538
+ if (foundConfigPath) {
4539
+ const loaded = await coreCompiler.loadConfig({
4540
+ config: { rootDir: dirname(foundConfigPath) },
4541
+ configPath: foundConfigPath,
4542
+ logger,
4543
+ sys
4544
+ });
4545
+ strictConfig = coreCompiler.validateConfig(loaded.config, {}).config;
4546
+ } else strictConfig = coreCompiler.validateConfig({ rootDir }, {}).config;
4547
+ if (task === "add") await taskAdd(flags.unknownArgs, strictConfig);
4548
+ else {
4549
+ const loadProjectConfig = async (configPath) => {
4550
+ const derivedRootDir = configPath ? dirname(configPath) : rootDir;
4551
+ const loaded = await coreCompiler.loadConfig({
4552
+ config: { rootDir: derivedRootDir },
4553
+ configPath,
4554
+ logger,
4555
+ sys
4556
+ });
4557
+ if (loaded.diagnostics.length > 0) logger.printDiagnostics(loaded.diagnostics);
4558
+ return coreCompiler.validateConfig(loaded.config ?? { rootDir: derivedRootDir }, {}).config;
4559
+ };
4560
+ await taskInit(coreCompiler, strictConfig, loadProjectConfig);
4561
+ }
4562
+ return;
4563
+ }
2132
4564
  startupLog(logger, task);
2133
4565
  const findConfigResults = await findConfig({
2134
4566
  sys,
@@ -2149,7 +4581,7 @@ const run = async (init) => {
2149
4581
  const configWithFlags = mergeFlags({}, flags);
2150
4582
  const validated = await coreCompiler.loadConfig({
2151
4583
  config: configWithFlags,
2152
- configPath: foundConfig.configPath,
4584
+ configPath: foundConfig.configPath ?? void 0,
2153
4585
  logger,
2154
4586
  sys
2155
4587
  });
@@ -2186,6 +4618,9 @@ const runTask = async (coreCompiler, config, task, sys, flags) => {
2186
4618
  if (!configWithFlags.sys) configWithFlags.sys = sys;
2187
4619
  const strictConfig = coreCompiler.validateConfig(configWithFlags, {}).config;
2188
4620
  switch (task) {
4621
+ case "add":
4622
+ await taskAdd(resolvedFlags.unknownArgs ?? [], strictConfig);
4623
+ break;
2189
4624
  case "build":
2190
4625
  await taskBuild(coreCompiler, strictConfig, resolvedFlags);
2191
4626
  break;
@@ -2199,6 +4634,9 @@ const runTask = async (coreCompiler, config, task, sys, flags) => {
2199
4634
  case "help":
2200
4635
  await taskHelp(resolvedFlags, strictConfig.logger, sys);
2201
4636
  break;
4637
+ case "init":
4638
+ await taskInit(coreCompiler, strictConfig);
4639
+ break;
2202
4640
  case "migrate":
2203
4641
  await taskMigrate(coreCompiler, strictConfig, resolvedFlags);
2204
4642
  break;