@stencil/cli 5.0.0-alpha.2 → 5.0.0-alpha.20

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,6 +1,18 @@
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 { join, parse, relative } from "path";
2
+ import { buildError, catchError, hasError, isFunction, isOutputTargetDocs, isOutputTargetSsr, 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, installDependencies } from "nypm";
9
+ import { isCI } from "std-env";
10
+ import ts from "typescript";
11
+ import { pathToFileURL } from "node:url";
12
+ import { existsSync } from "node:fs";
13
+ import { homedir } from "node:os";
14
+ import { dirname as dirname$1, isAbsolute, join as join$1, relative as relative$1 } from "path";
15
+ import { generatePackageJsonFields, generateStencilConfig, getComponentBoilerplate, getStyleBoilerplate, getTemplatePath, toPascalCase } from "@stencil/templates";
4
16
  import { start } from "@stencil/dev-server";
5
17
  //#region src/config-flags.ts
6
18
  /**
@@ -16,75 +28,25 @@ const BOOLEAN_CLI_FLAGS = [
16
28
  "dev",
17
29
  "devtools",
18
30
  "docs",
19
- "e2e",
20
- "es5",
21
- "esm",
31
+ "dryRun",
22
32
  "help",
23
33
  "log",
24
34
  "open",
25
35
  "prerender",
26
36
  "prerenderExternal",
27
- "prod",
28
37
  "profile",
29
38
  "serviceWorker",
30
- "screenshot",
31
39
  "serve",
32
40
  "skipNodeCheck",
33
- "spec",
34
41
  "ssr",
35
- "updateScreenshot",
36
42
  "verbose",
37
43
  "version",
38
- "watch",
39
- "all",
40
- "automock",
41
- "bail",
42
- "changedFilesWithAncestor",
43
- "clearCache",
44
- "clearMocks",
45
- "collectCoverage",
46
- "color",
47
- "colors",
48
- "coverage",
49
- "detectLeaks",
50
- "detectOpenHandles",
51
- "errorOnDeprecated",
52
- "expand",
53
- "findRelatedTests",
54
- "forceExit",
55
- "init",
56
- "injectGlobals",
57
- "json",
58
- "lastCommit",
59
- "listTests",
60
- "logHeapUsage",
61
- "noStackTrace",
62
- "notify",
63
- "onlyChanged",
64
- "onlyFailures",
65
- "passWithNoTests",
66
- "resetMocks",
67
- "resetModules",
68
- "restoreMocks",
69
- "runInBand",
70
- "runTestsByPath",
71
- "showConfig",
72
- "silent",
73
- "skipFilter",
74
- "testLocationInResults",
75
- "updateSnapshot",
76
- "useStderr",
77
- "watchAll",
78
- "watchman"
44
+ "watch"
79
45
  ];
80
46
  /**
81
47
  * All the Number options supported by the Stencil CLI
82
48
  */
83
- const NUMBER_CLI_FLAGS = [
84
- "port",
85
- "maxConcurrency",
86
- "testTimeout"
87
- ];
49
+ const NUMBER_CLI_FLAGS = ["port"];
88
50
  /**
89
51
  * All the String options supported by the Stencil CLI
90
52
  */
@@ -94,72 +56,20 @@ const STRING_CLI_FLAGS = [
94
56
  "docsApi",
95
57
  "docsJson",
96
58
  "emulate",
97
- "root",
98
- "screenshotConnector",
99
- "cacheDirectory",
100
- "changedSince",
101
- "collectCoverageFrom",
102
- "coverageDirectory",
103
- "coverageThreshold",
104
- "env",
105
- "filter",
106
- "globalSetup",
107
- "globalTeardown",
108
- "globals",
109
- "haste",
110
- "moduleNameMapper",
111
- "notifyMode",
112
- "outputFile",
113
- "preset",
114
- "prettierPath",
115
- "resolver",
116
- "rootDir",
117
- "runner",
118
- "testEnvironment",
119
- "testEnvironmentOptions",
120
- "testFailureExitCode",
121
- "testNamePattern",
122
- "testResultsProcessor",
123
- "testRunner",
124
- "testSequencer",
125
- "testURL",
126
- "timers",
127
- "transform"
128
- ];
129
- const STRING_ARRAY_CLI_FLAGS = [
130
- "collectCoverageOnlyFrom",
131
- "coveragePathIgnorePatterns",
132
- "coverageReporters",
133
- "moduleDirectories",
134
- "moduleFileExtensions",
135
- "modulePathIgnorePatterns",
136
- "modulePaths",
137
- "projects",
138
- "reporters",
139
- "roots",
140
- "selectProjects",
141
- "setupFiles",
142
- "setupFilesAfterEnv",
143
- "snapshotSerializers",
144
- "testMatch",
145
- "testPathIgnorePatterns",
146
- "testPathPattern",
147
- "testRegex",
148
- "transformIgnorePatterns",
149
- "unmockedModulePathPatterns",
150
- "watchPathIgnorePatterns"
59
+ "root"
151
60
  ];
61
+ const STRING_ARRAY_CLI_FLAGS = [];
152
62
  /**
153
63
  * All the CLI arguments which may have string or number values
154
64
  *
155
- * `maxWorkers` is an argument which is used both by Stencil _and_ by Jest,
156
- * which means that we need to support parsing both string and number values.
65
+ * `maxWorkers` controls the number of concurrent workers for Stencil builds.
66
+ * Supports both string (e.g., "50%") and number values.
157
67
  */
158
68
  const STRING_NUMBER_CLI_FLAGS = ["maxWorkers"];
159
69
  /**
160
70
  * All the CLI arguments which may have boolean or string values.
161
71
  */
162
- const BOOLEAN_STRING_CLI_FLAGS = ["headless", "stats"];
72
+ const BOOLEAN_STRING_CLI_FLAGS = ["stats"];
163
73
  /**
164
74
  * All the LogLevel-type options supported by the Stencil CLI
165
75
  *
@@ -175,21 +85,13 @@ const CLI_FLAG_ALIASES = {
175
85
  c: "config",
176
86
  h: "help",
177
87
  p: "port",
178
- v: "version",
179
- b: "bail",
180
- e: "expand",
181
- f: "onlyFailures",
182
- i: "runInBand",
183
- o: "onlyChanged",
184
- t: "testNamePattern",
185
- u: "updateSnapshot",
186
- w: "maxWorkers"
88
+ v: "version"
187
89
  };
188
90
  /**
189
91
  * A regular expression which can be used to match a CLI flag for one of our
190
92
  * short aliases.
191
93
  */
192
- const CLI_FLAG_REGEX = new RegExp(`^-[chpvbewofitu]{1}$`);
94
+ const CLI_FLAG_REGEX = new RegExp(`^-[chpv]{1}$`);
193
95
  /**
194
96
  * Helper function for initializing a `ConfigFlags` object. Provide any overrides
195
97
  * for default values and off you go!
@@ -354,9 +256,10 @@ const setCLIArg = (flags, rawArg, normalizedArg, value) => {
354
256
  flags.knownArgs.push(rawArg);
355
257
  flags.knownArgs.push(value);
356
258
  } else throwCLIParsingError(rawArg, "expected a string argument but received nothing");
357
- else if (readOnlyArrayHasStringMember(STRING_ARRAY_CLI_FLAGS, normalizedArg)) if (typeof value === "string") {
358
- if (!Array.isArray(flags[normalizedArg])) flags[normalizedArg] = [];
359
- const targetArray = flags[normalizedArg];
259
+ else if (STRING_ARRAY_CLI_FLAGS.length > 0 && readOnlyArrayHasStringMember(STRING_ARRAY_CLI_FLAGS, normalizedArg)) if (typeof value === "string") {
260
+ const flagsRecord = flags;
261
+ if (!Array.isArray(flagsRecord[normalizedArg])) flagsRecord[normalizedArg] = [];
262
+ const targetArray = flagsRecord[normalizedArg];
360
263
  if (Array.isArray(targetArray)) {
361
264
  targetArray.push(value);
362
265
  flags.knownArgs.push(rawArg);
@@ -548,7 +451,7 @@ const findConfig = async (opts) => {
548
451
  else configPath = normalizePath(configPath);
549
452
  else configPath = rootDir;
550
453
  const results = {
551
- configPath,
454
+ configPath: null,
552
455
  rootDir: normalizePath(cwd)
553
456
  };
554
457
  const stat = await sys.stat(configPath);
@@ -563,12 +466,15 @@ const findConfig = async (opts) => {
563
466
  if (stat.isFile) {
564
467
  results.configPath = configPath;
565
468
  results.rootDir = sys.platformPath.dirname(configPath);
566
- } else if (stat.isDirectory) for (const configName of ["stencil.config.ts", "stencil.config.js"]) {
567
- const testConfigFilePath = sys.platformPath.join(configPath, configName);
568
- if ((await sys.stat(testConfigFilePath)).isFile) {
569
- results.configPath = testConfigFilePath;
570
- results.rootDir = sys.platformPath.dirname(testConfigFilePath);
571
- break;
469
+ } else if (stat.isDirectory) {
470
+ results.rootDir = configPath;
471
+ for (const configName of ["stencil.config.ts", "stencil.config.js"]) {
472
+ const testConfigFilePath = sys.platformPath.join(configPath, configName);
473
+ if ((await sys.stat(testConfigFilePath)).isFile) {
474
+ results.configPath = testConfigFilePath;
475
+ results.rootDir = sys.platformPath.dirname(testConfigFilePath);
476
+ break;
477
+ }
572
478
  }
573
479
  }
574
480
  return result.ok(results);
@@ -642,108 +548,2339 @@ const loadedCompilerLog = (sys, logger, flags, coreCompiler) => {
642
548
  }
643
549
  };
644
550
  /**
645
- * Log various warnings to an output stream
646
- *
647
- * The output stream is determined by the {@link Logger} instance attached to the `config` argument to this function
551
+ * Log various warnings to an output stream
552
+ *
553
+ * The output stream is determined by the {@link Logger} instance attached to the `config` argument to this function
554
+ *
555
+ * @param coreCompiler the compiler instance being used for this invocation of Stencil
556
+ * @param config a validated configuration object to be used for this run of Stencil
557
+ */
558
+ const startupCompilerLog = (coreCompiler, config) => {
559
+ if (config.suppressLogs === true) return;
560
+ const { logger } = config;
561
+ const isDebug = logger.getLevel() === "debug";
562
+ const isPrerelease = coreCompiler.version.includes("-");
563
+ const isDevBuild = coreCompiler.version.includes("-dev.");
564
+ if (isPrerelease && !isDevBuild) logger.warn(logger.yellow(`This is a prerelease build, undocumented changes might happen at any time. Technical support is not available for prereleases, but any assistance testing is appreciated.`));
565
+ if (config.devMode && !isDebug) {
566
+ if (!config.enableCache) logger.warn(`Disabling cache during development will slow down incremental builds.`);
567
+ }
568
+ };
569
+ //#endregion
570
+ //#region src/merge-flags.ts
571
+ /**
572
+ * Merge CLI flags into a Stencil configuration object.
573
+ *
574
+ * This function applies command-line flags to the config, with CLI flags
575
+ * taking precedence over config file values. This is the canonical place
576
+ * where flag values are translated into config properties.
577
+ *
578
+ * @param config The config object (from stencil.config.ts or empty)
579
+ * @param flags The parsed CLI flags
580
+ * @returns The config with flags merged in
581
+ */
582
+ const mergeFlags = (config, flags) => {
583
+ const merged = { ...config };
584
+ if (flags.dev === true) merged.devMode = true;
585
+ if (flags.debug === true || flags.verbose === true) merged.logLevel = "debug";
586
+ else if (flags.logLevel) merged.logLevel = flags.logLevel;
587
+ if (typeof flags.watch === "boolean") merged.watch = flags.watch;
588
+ if (flags.docs === true) merged._docsFlag = true;
589
+ if (typeof flags.profile === "boolean") merged.profile = flags.profile;
590
+ if (typeof flags.log === "boolean") merged.writeLog = flags.log;
591
+ if (typeof flags.cache === "boolean") merged.enableCache = flags.cache;
592
+ if (typeof flags.ci === "boolean") merged.ci = flags.ci;
593
+ if (typeof flags.ssr === "boolean") merged.ssr = flags.ssr;
594
+ if (typeof flags.prerender === "boolean") merged.prerender = flags.prerender;
595
+ if (typeof flags.docsJson === "string") merged.docsJsonPath = flags.docsJson;
596
+ if (flags.stats) merged.statsJsonPath = flags.stats;
597
+ if (typeof flags.serviceWorker === "boolean") merged.generateServiceWorker = flags.serviceWorker;
598
+ if (typeof flags.maxWorkers === "number") merged.maxConcurrentWorkers = flags.maxWorkers;
599
+ if (typeof flags.address === "string") merged.devServerAddress = flags.address;
600
+ if (typeof flags.port === "number") merged.devServerPort = flags.port;
601
+ if (typeof flags.open === "boolean") merged.devServerOpen = flags.open;
602
+ return merged;
603
+ };
604
+ //#endregion
605
+ //#region src/wizard/config-editor.ts
606
+ async function openStencilConfig(configPath) {
607
+ let text = await readFile(configPath, "utf8");
608
+ const parse = () => ts.createSourceFile(configPath, text, ts.ScriptTarget.Latest, true);
609
+ function findArray(sf, propName) {
610
+ let found;
611
+ const visit = (node) => {
612
+ if (!found && ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === propName && ts.isArrayLiteralExpression(node.initializer)) found = node.initializer;
613
+ else ts.forEachChild(node, visit);
614
+ };
615
+ visit(sf);
616
+ return found;
617
+ }
618
+ function findConfigObject(sf) {
619
+ for (const stmt of sf.statements) if (ts.isVariableStatement(stmt)) {
620
+ 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;
621
+ }
622
+ let found;
623
+ const visit = (node) => {
624
+ if (found) return;
625
+ if (ts.isObjectLiteralExpression(node)) {
626
+ if (node.properties.some((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "namespace")) {
627
+ found = node;
628
+ return;
629
+ }
630
+ }
631
+ ts.forEachChild(node, visit);
632
+ };
633
+ visit(sf);
634
+ return found;
635
+ }
636
+ function replaceInArray(arr, substring, expression) {
637
+ for (const element of arr.elements) if (text.slice(element.getStart(), element.getEnd()).includes(substring)) {
638
+ text = text.slice(0, element.getStart()) + expression + text.slice(element.getEnd());
639
+ return true;
640
+ }
641
+ return false;
642
+ }
643
+ function removeFromArray(arr, substring) {
644
+ const idx = arr.elements.findIndex((element) => text.slice(element.getStart(), element.getEnd()).includes(substring));
645
+ if (idx === -1) return false;
646
+ const element = arr.elements[idx];
647
+ if (arr.elements.length > 0 && text.slice(arr.getStart(), arr.elements[0].getStart()).includes("\n")) {
648
+ const lineStart = text.lastIndexOf("\n", element.getStart());
649
+ let end = element.getEnd();
650
+ const trailingComma = text.slice(end).match(/^\s*,/);
651
+ if (trailingComma) end += trailingComma[0].length;
652
+ text = text.slice(0, lineStart) + text.slice(end);
653
+ } else {
654
+ let start = element.getStart();
655
+ let end = element.getEnd();
656
+ if (idx < arr.elements.length - 1) {
657
+ const trailingMatch = text.slice(end).match(/^,\s*/);
658
+ if (trailingMatch) end += trailingMatch[0].length;
659
+ } else if (idx > 0) {
660
+ const precedingMatch = text.slice(0, start).match(/,\s*$/);
661
+ if (precedingMatch) start -= precedingMatch[0].length;
662
+ }
663
+ text = text.slice(0, start) + text.slice(end);
664
+ }
665
+ return true;
666
+ }
667
+ function appendToArray(arr, code) {
668
+ if (arr.elements.length === 0) {
669
+ const insertPos = arr.getEnd() - 1;
670
+ text = text.slice(0, insertPos) + code + text.slice(insertPos);
671
+ return;
672
+ }
673
+ let insertPos = arr.elements[arr.elements.length - 1].getEnd();
674
+ const trailingComma = text.slice(insertPos).match(/^\s*,/);
675
+ if (trailingComma) insertPos += trailingComma[0].length;
676
+ const firstElemStart = arr.elements[0].getStart();
677
+ if (text.slice(arr.getStart(), firstElemStart).includes("\n")) {
678
+ const lineStart = text.lastIndexOf("\n", firstElemStart) + 1;
679
+ const indent = text.slice(lineStart, firstElemStart).match(/^\s+/)?.[0] ?? " ";
680
+ text = `${text.slice(0, insertPos)},\n${indent}${code}${text.slice(insertPos)}`;
681
+ } else text = `${text.slice(0, insertPos)}, ${code}${text.slice(insertPos)}`;
682
+ }
683
+ function addArrayProp(sf, propName, code) {
684
+ const configObj = findConfigObject(sf);
685
+ if (!configObj) throw new Error("Could not find Stencil config object in stencil.config.ts");
686
+ let propIndent = " ";
687
+ if (configObj.properties.length > 0) {
688
+ const firstPropStart = configObj.properties[0].getStart();
689
+ const lineStart = text.lastIndexOf("\n", firstPropStart) + 1;
690
+ propIndent = text.slice(lineStart, firstPropStart).match(/^\s+/)?.[0] ?? " ";
691
+ }
692
+ const newProp = `${propName}: [\n${propIndent + " "}${code},\n${propIndent}]`;
693
+ const lastProp = configObj.properties[configObj.properties.length - 1];
694
+ if (lastProp) {
695
+ let insertPos = lastProp.getEnd();
696
+ const trailingComma = text.slice(insertPos).match(/^\s*,/);
697
+ if (trailingComma) insertPos += trailingComma[0].length;
698
+ text = `${text.slice(0, insertPos)},\n${propIndent}${newProp}${text.slice(insertPos)}`;
699
+ } else {
700
+ const insertPos = configObj.getEnd() - 1;
701
+ text = `${text.slice(0, insertPos)}\n${propIndent}${newProp},\n${text.slice(insertPos)}`;
702
+ }
703
+ }
704
+ return {
705
+ hasImport(moduleSpecifier) {
706
+ return parse().statements.some((s) => ts.isImportDeclaration(s) && ts.isStringLiteral(s.moduleSpecifier) && s.moduleSpecifier.text === moduleSpecifier);
707
+ },
708
+ addImport(moduleSpecifier, namedImports) {
709
+ const sf = parse();
710
+ if (sf.statements.some((s) => ts.isImportDeclaration(s) && ts.isStringLiteral(s.moduleSpecifier) && s.moduleSpecifier.text === moduleSpecifier)) return;
711
+ let insertPos = 0;
712
+ for (const s of sf.statements) if (ts.isImportDeclaration(s)) insertPos = s.getEnd();
713
+ const decl = `\nimport { ${namedImports.join(", ")} } from '${moduleSpecifier}';`;
714
+ text = insertPos > 0 ? text.slice(0, insertPos) + decl + text.slice(insertPos) : decl + "\n" + text;
715
+ },
716
+ outputTargetsContains(substring) {
717
+ const arr = findArray(parse(), "outputTargets");
718
+ return arr ? text.slice(arr.getStart(), arr.getEnd()).includes(substring) : false;
719
+ },
720
+ addOutputTarget(expression) {
721
+ const sf = parse();
722
+ const arr = findArray(sf, "outputTargets");
723
+ if (arr) appendToArray(arr, expression);
724
+ else addArrayProp(sf, "outputTargets", expression);
725
+ },
726
+ replaceOutputTarget(substring, expression) {
727
+ const arr = findArray(parse(), "outputTargets");
728
+ return arr ? replaceInArray(arr, substring, expression) : false;
729
+ },
730
+ removeOutputTarget(substring) {
731
+ const arr = findArray(parse(), "outputTargets");
732
+ return arr ? removeFromArray(arr, substring) : false;
733
+ },
734
+ pluginsContains(substring) {
735
+ const arr = findArray(parse(), "plugins");
736
+ return arr ? text.slice(arr.getStart(), arr.getEnd()).includes(substring) : false;
737
+ },
738
+ addPlugin(expression) {
739
+ const sf = parse();
740
+ const arr = findArray(sf, "plugins");
741
+ if (arr) appendToArray(arr, expression);
742
+ else addArrayProp(sf, "plugins", expression);
743
+ },
744
+ replacePlugin(substring, expression) {
745
+ const arr = findArray(parse(), "plugins");
746
+ return arr ? replaceInArray(arr, substring, expression) : false;
747
+ },
748
+ removePlugin(substring) {
749
+ const arr = findArray(parse(), "plugins");
750
+ return arr ? removeFromArray(arr, substring) : false;
751
+ },
752
+ async save() {
753
+ await writeFile(configPath, text, "utf8");
754
+ }
755
+ };
756
+ }
757
+ //#endregion
758
+ //#region src/wizard/discover.ts
759
+ function toStringRecord(val) {
760
+ return val !== null && typeof val === "object" ? val : {};
761
+ }
762
+ async function readJson$1(filePath) {
763
+ try {
764
+ return JSON.parse(await readFile(filePath, "utf8"));
765
+ } catch {
766
+ return null;
767
+ }
768
+ }
769
+ async function loadOne(rootDir, packageName, loader) {
770
+ const wizardEntry = ((await readJson$1(join(rootDir, "node_modules", packageName, "package.json")))?.stencil)?.wizard;
771
+ if (!wizardEntry) return null;
772
+ const wizardPath = join(rootDir, "node_modules", packageName, wizardEntry);
773
+ let mod;
774
+ try {
775
+ mod = await loader(pathToFileURL(wizardPath).href);
776
+ } catch {
777
+ console.warn(`[stencil] ${packageName} declares stencil.wizard but the module failed to load: ${wizardPath}`);
778
+ return null;
779
+ }
780
+ const plugin = mod.wizard;
781
+ if (!plugin || typeof plugin !== "object") {
782
+ console.warn(`[stencil] ${packageName} declares stencil.wizard but does not export a 'wizard' object`);
783
+ return null;
784
+ }
785
+ return {
786
+ packageName,
787
+ plugin
788
+ };
789
+ }
790
+ /**
791
+ * Scans the project's declared dependencies for packages that expose a
792
+ * `stencil.wizard` entry in their `package.json` and dynamically imports
793
+ * each matching module.
794
+ *
795
+ * @param rootDir - Absolute path to the project root (where `package.json` lives).
796
+ * @param loader - Module loader; injectable for testing. Defaults to `import()`.
797
+ * @returns Array of successfully loaded plugins, in dependency declaration order.
798
+ */
799
+ async function discoverPlugins(rootDir, loader = (url) => import(url)) {
800
+ const pkg = await readJson$1(join(rootDir, "package.json"));
801
+ if (!pkg) return [];
802
+ const depNames = [...new Set([...Object.keys(toStringRecord(pkg.dependencies)), ...Object.keys(toStringRecord(pkg.devDependencies))])];
803
+ const plugins = (await Promise.allSettled(depNames.map((name) => loadOne(rootDir, name, loader)))).filter((r) => r.status === "fulfilled" && r.value !== null).map((r) => r.value);
804
+ const devEnv = process.env.STENCIL_WIZARD_DEV;
805
+ if (devEnv) {
806
+ const devPaths = devEnv.split(",").map((s) => s.trim()).filter(Boolean);
807
+ for (const devPath of devPaths) {
808
+ const devPlugin = await loadDevPlugin(resolve(rootDir, devPath), loader);
809
+ if (devPlugin) {
810
+ const idx = plugins.findIndex((p) => p.packageName === devPlugin.packageName);
811
+ if (idx >= 0) plugins.splice(idx, 1, devPlugin);
812
+ else plugins.unshift(devPlugin);
813
+ }
814
+ }
815
+ }
816
+ return plugins;
817
+ }
818
+ async function findDevPackageName(wizardPath) {
819
+ const dir = dirname(wizardPath);
820
+ for (const candidate of [dir, resolve(dir, "..")]) {
821
+ const pkg = await readJson$1(join(candidate, "package.json"));
822
+ if (typeof pkg?.name === "string") return pkg.name;
823
+ }
824
+ return basename(dir);
825
+ }
826
+ async function loadDevPlugin(wizardPath, loader) {
827
+ const packageName = await findDevPackageName(wizardPath);
828
+ let mod;
829
+ try {
830
+ mod = await loader(pathToFileURL(wizardPath).href);
831
+ } catch {
832
+ console.warn(`[stencil] STENCIL_WIZARD_DEV: failed to load ${wizardPath}`);
833
+ return null;
834
+ }
835
+ const plugin = mod.wizard;
836
+ if (!plugin || typeof plugin !== "object") {
837
+ console.warn(`[stencil] STENCIL_WIZARD_DEV: ${wizardPath} does not export a 'wizard' object`);
838
+ return null;
839
+ }
840
+ return {
841
+ packageName,
842
+ plugin
843
+ };
844
+ }
845
+ //#endregion
846
+ //#region src/wizard/clack.ts
847
+ /**
848
+ * Exits cleanly if the user cancelled a prompt (Ctrl+C).
849
+ * Narrows the type from `T | symbol` to `T` for callers.
850
+ *
851
+ * @param value - Return value from a `@clack/prompts` prompt call.
852
+ */
853
+ function cancelIfAborted(value) {
854
+ if (isCancel(value)) {
855
+ cancel("Cancelled.");
856
+ process.exit(0);
857
+ }
858
+ }
859
+ //#endregion
860
+ //#region src/wizard/init/steps.ts
861
+ /** Well-known integrations the CLI can offer before any packages are installed. */
862
+ const KNOWN_INTEGRATIONS = [
863
+ {
864
+ package: "@stencil/vitest",
865
+ displayName: "Vitest",
866
+ description: "Unit / Spec / Integration / Browser testing",
867
+ group: "Testing"
868
+ },
869
+ {
870
+ package: "@stencil/playwright",
871
+ displayName: "Playwright",
872
+ description: "E2E testing",
873
+ group: "Testing"
874
+ },
875
+ {
876
+ package: "@stencil/sass",
877
+ displayName: "Sass",
878
+ description: "Sass/SCSS styles",
879
+ group: "Styling",
880
+ requiresStencilConfig: true
881
+ },
882
+ {
883
+ package: "@stencil/eslint-plugin",
884
+ displayName: "ESLint Plugin",
885
+ description: "Stencil-aware lint rules (ESLint or oxlint)",
886
+ group: "Tooling"
887
+ },
888
+ {
889
+ package: "@stencil/storybook-plugin",
890
+ displayName: "Storybook",
891
+ description: "Component development & documentation",
892
+ group: "Tooling",
893
+ versionRange: ">=1.0.0-0"
894
+ },
895
+ {
896
+ package: "@stencil/types-output-target",
897
+ displayName: "Types",
898
+ description: "TypeScript types for React, Vue, Solid, Svelte, Preact",
899
+ group: "Framework integrations",
900
+ requiresStencilConfig: true
901
+ },
902
+ {
903
+ package: "@stencil/react-output-target",
904
+ displayName: "React",
905
+ description: "React component wrappers",
906
+ group: "Framework integrations",
907
+ requiresStencilConfig: true,
908
+ needsWorkspace: true
909
+ },
910
+ {
911
+ package: "@stencil/angular-output-target",
912
+ displayName: "Angular",
913
+ description: "Angular component wrappers",
914
+ group: "Framework integrations",
915
+ requiresStencilConfig: true,
916
+ needsWorkspace: true
917
+ },
918
+ {
919
+ package: "@stencil/vue-output-target",
920
+ displayName: "Vue",
921
+ description: "Vue component wrappers",
922
+ group: "Framework integrations",
923
+ requiresStencilConfig: true,
924
+ needsWorkspace: true
925
+ }
926
+ ];
927
+ const versionRangeByPackage = new Map(KNOWN_INTEGRATIONS.filter((i) => i.versionRange).map((i) => [i.package, i.versionRange]));
928
+ function withVersionRanges(packages) {
929
+ return packages.map((pkg) => {
930
+ const range = versionRangeByPackage.get(pkg);
931
+ return range ? `${pkg}@${range}` : pkg;
932
+ });
933
+ }
934
+ async function promptOutputs() {
935
+ const picks = await p.multiselect({
936
+ message: "Outputs:",
937
+ options: [
938
+ {
939
+ value: "loader",
940
+ label: "Loader",
941
+ hint: "performant lazy-loader; browser & bundler ready"
942
+ },
943
+ {
944
+ value: "standalone",
945
+ label: "Standalone",
946
+ hint: "per-component modules, import only what you need"
947
+ },
948
+ {
949
+ value: "ssr",
950
+ label: "SSR",
951
+ hint: "pre-render components in any JS server environment"
952
+ },
953
+ {
954
+ value: "ssr-wasm",
955
+ label: "SSR WASM",
956
+ hint: "experimental: compile SSR to a portable WASM binary"
957
+ },
958
+ {
959
+ value: "www",
960
+ label: "WWW",
961
+ hint: "app mode with dev server and optional PWA support"
962
+ }
963
+ ],
964
+ required: false
965
+ });
966
+ cancelIfAborted(picks);
967
+ return picks;
968
+ }
969
+ async function promptFeatures() {
970
+ const picks = await p.multiselect({
971
+ message: "Features:",
972
+ options: [
973
+ {
974
+ value: "signals",
975
+ label: "Signals",
976
+ hint: "signal-backed @Prop/@State for cross-framework reactive interop"
977
+ },
978
+ {
979
+ value: "globalStyle",
980
+ label: "Global style",
981
+ hint: "Global stylesheet for font definitions, CSS variables, pre-load styles etc"
982
+ },
983
+ {
984
+ value: "globalScript",
985
+ label: "Global script",
986
+ hint: "Global script for initializing application-wide logic before components load"
987
+ }
988
+ ],
989
+ required: false
990
+ });
991
+ cancelIfAborted(picks);
992
+ const set = new Set(picks);
993
+ return {
994
+ signals: set.has("signals"),
995
+ globalStyle: set.has("globalStyle"),
996
+ globalScript: set.has("globalScript")
997
+ };
998
+ }
999
+ async function promptDocs() {
1000
+ const picks = await p.multiselect({
1001
+ message: "Docs:",
1002
+ options: [
1003
+ {
1004
+ value: "cem",
1005
+ label: "CEM",
1006
+ hint: "custom-elements.json - preferred format for interop with tools like Storybook, Styleguidist, etc"
1007
+ },
1008
+ {
1009
+ value: "json",
1010
+ label: "JSON",
1011
+ hint: "docs.json - Stencil / Ionic centric schema"
1012
+ },
1013
+ {
1014
+ value: "vscode",
1015
+ label: "VS Code",
1016
+ hint: "vscode-data.json - editor autocomplete for your components"
1017
+ }
1018
+ ],
1019
+ required: false
1020
+ });
1021
+ cancelIfAborted(picks);
1022
+ return picks;
1023
+ }
1024
+ async function promptProjectName() {
1025
+ const name = await p.text({
1026
+ message: "Project name:",
1027
+ defaultValue: "my-stencil-library",
1028
+ validate: (v) => {
1029
+ if (!v?.trim()) return "Project name is required";
1030
+ }
1031
+ });
1032
+ cancelIfAborted(name);
1033
+ return name;
1034
+ }
1035
+ function buildGroupedOptions(integrations) {
1036
+ const groups = {};
1037
+ for (const i of integrations) (groups[i.group] ??= []).push({
1038
+ value: i.package,
1039
+ label: i.displayName,
1040
+ hint: i.description
1041
+ });
1042
+ return groups;
1043
+ }
1044
+ async function promptCustomPackages() {
1045
+ const input = await p.text({
1046
+ message: "Additional packages to install:",
1047
+ placeholder: "e.g. my-plugin another-package (leave blank to skip)"
1048
+ });
1049
+ cancelIfAborted(input);
1050
+ if (typeof input !== "string" || !input.trim()) return [];
1051
+ return input.split(/[\s,]+/).map((s) => s.trim()).filter(Boolean);
1052
+ }
1053
+ async function promptIntegrations() {
1054
+ const picks = await p.groupMultiselect({
1055
+ message: "Add integrations (optional):",
1056
+ options: buildGroupedOptions(KNOWN_INTEGRATIONS),
1057
+ required: false
1058
+ });
1059
+ cancelIfAborted(picks);
1060
+ return KNOWN_INTEGRATIONS.filter((i) => picks.includes(i.package));
1061
+ }
1062
+ function hasFrameworkTargets(integrations) {
1063
+ return integrations.some((i) => i.needsWorkspace);
1064
+ }
1065
+ function needsStencilConfig(integrations) {
1066
+ return integrations.some((i) => i.requiresStencilConfig);
1067
+ }
1068
+ async function promptMonorepo() {
1069
+ const answer = await p.confirm({
1070
+ message: "Set up as a monorepo workspace? (recommended for publishing framework wrappers)",
1071
+ initialValue: true
1072
+ });
1073
+ cancelIfAborted(answer);
1074
+ return answer;
1075
+ }
1076
+ async function promptWorkspaceCoreName() {
1077
+ const name = await p.text({
1078
+ message: "Core package directory name:",
1079
+ defaultValue: "core",
1080
+ placeholder: "core"
1081
+ });
1082
+ cancelIfAborted(name);
1083
+ return name || "core";
1084
+ }
1085
+ /**
1086
+ * Prompt for actions on an existing project: install new integrations and/or
1087
+ * run init wizards for already-installed packages with wizard contributions.
1088
+ *
1089
+ * @param installable - KNOWN_INTEGRATIONS not yet present in the project.
1090
+ * @param configurable - Already-installed plugins that declare an `init` contribution.
1091
+ * @returns Selected integrations to install and plugins to configure.
1092
+ */
1093
+ async function promptAddCapabilities(installable, configurable) {
1094
+ const options = {};
1095
+ if (installable.length > 0) options["Install new integrations"] = installable.map((i) => ({
1096
+ value: `install:${i.package}`,
1097
+ label: i.displayName,
1098
+ hint: i.description
1099
+ }));
1100
+ if (configurable.length > 0) options["Configure existing integrations"] = configurable.map((d) => ({
1101
+ value: `configure:${d.packageName}`,
1102
+ label: d.plugin.init.displayName,
1103
+ hint: d.plugin.init.description
1104
+ }));
1105
+ const picks = await p.groupMultiselect({
1106
+ message: "What would you like to do?",
1107
+ options,
1108
+ required: false
1109
+ });
1110
+ cancelIfAborted(picks);
1111
+ const pickedSet = new Set(picks);
1112
+ return {
1113
+ toInstall: installable.filter((i) => pickedSet.has(`install:${i.package}`)),
1114
+ toConfigure: configurable.filter((d) => pickedSet.has(`configure:${d.packageName}`))
1115
+ };
1116
+ }
1117
+ //#endregion
1118
+ //#region src/wizard/project.ts
1119
+ /**
1120
+ * Extracts the stable, plugin-relevant fields from a fully-resolved compiler config.
1121
+ * @param validated The fully-resolved compiler config.
1122
+ * @returns A ProjectConfig with only the fields relevant to plugins and the wizard.
1123
+ * This is a stable subset of the compiler config that won't change between versions.
1124
+ */
1125
+ function toProjectConfig(validated) {
1126
+ return {
1127
+ rootDir: validated.rootDir,
1128
+ srcDir: validated.srcDir,
1129
+ namespace: validated.namespace,
1130
+ fsNamespace: validated.fsNamespace,
1131
+ outputTargets: validated.outputTargets ?? [],
1132
+ globalScript: validated.globalScript,
1133
+ globalStyle: validated.globalStyle,
1134
+ compat: validated.compat,
1135
+ signalBacking: validated.signalBacking
1136
+ };
1137
+ }
1138
+ /**
1139
+ * Builds a minimal ProjectConfig when no validated config is available (e.g. new project, no compiler).
1140
+ * @param rootDir The root directory of the project.
1141
+ * @param overrides Optional fields to override the defaults.
1142
+ * @returns A ProjectConfig with reasonable defaults for a new project.
1143
+ * */
1144
+ function defaultProjectConfig(rootDir, overrides) {
1145
+ const namespace = overrides?.namespace ?? "";
1146
+ return {
1147
+ rootDir,
1148
+ srcDir: join(rootDir, "src"),
1149
+ namespace,
1150
+ fsNamespace: overrides?.fsNamespace ?? namespace.toLowerCase(),
1151
+ outputTargets: [],
1152
+ ...overrides
1153
+ };
1154
+ }
1155
+ /**
1156
+ * Walk up from `startDir` looking for a monorepo workspace root — a directory
1157
+ * containing `pnpm-workspace.yaml` or a `package.json` with a `workspaces` field.
1158
+ * Stops at the home directory or filesystem root. Returns `undefined` if none found.
1159
+ * @param startDir The directory to start searching from.
1160
+ * @returns A promise that resolves to the workspace root directory, or undefined if none found.
1161
+ */
1162
+ async function detectWorkspaceRoot(startDir) {
1163
+ const home = homedir();
1164
+ let dir = startDir;
1165
+ while (true) {
1166
+ if (existsSync(join(dir, "pnpm-workspace.yaml"))) return dir;
1167
+ try {
1168
+ const pkg = JSON.parse(await readFile(join(dir, "package.json"), "utf8"));
1169
+ if (Array.isArray(pkg.workspaces)) return dir;
1170
+ } catch {}
1171
+ const parent = dirname(dir);
1172
+ if (parent === dir || dir === home) return void 0;
1173
+ dir = parent;
1174
+ }
1175
+ }
1176
+ /**
1177
+ * Returns true if the directory looks like an existing Stencil project:
1178
+ * - has an explicit `stencil.config.ts`, OR
1179
+ * - has `.tsx` files under `src/` (zero-config project).
1180
+ * @param dir The directory to check for an existing Stencil project.
1181
+ * @returns A promise that resolves to true if the directory looks like an existing Stencil project, false otherwise.
1182
+ */
1183
+ async function isExistingStencilProject(dir) {
1184
+ if (existsSync(join(dir, "stencil.config.ts"))) return true;
1185
+ try {
1186
+ return (await readdir(join(dir, "src"), {
1187
+ recursive: true,
1188
+ withFileTypes: true
1189
+ })).some((e) => e.isFile() && e.name.endsWith(".tsx"));
1190
+ } catch {
1191
+ return false;
1192
+ }
1193
+ }
1194
+ //#endregion
1195
+ //#region src/wizard/splash.ts
1196
+ const CLI_VERSION = "5.0.0-alpha.20";
1197
+ const isTTY = process.stdout.isTTY;
1198
+ const noColor = !isTTY || "NO_COLOR" in process.env;
1199
+ const RESET = noColor ? "" : "\x1B[0m";
1200
+ const BOLD = noColor ? "" : "\x1B[1m";
1201
+ const DIM = noColor ? "" : "\x1B[2m";
1202
+ const BLUE = noColor ? "" : "\x1B[38;2;60;44;255m";
1203
+ const RAW = `\
1204
+ .............
1205
+ ...................
1206
+ .........................
1207
+ ..............................
1208
+ .................................
1209
+ ..............████████████.........
1210
+ .............████████████............
1211
+ ............████████████...............
1212
+ ...........*************.................
1213
+ .........████████████████████████████....
1214
+ .......████████████████████████████......
1215
+ .....████████████████████████████........
1216
+ ...████████████████████████████..........
1217
+ ................*************............
1218
+ ..............████████████.............
1219
+ ............████████████..............
1220
+ .........████████████...............
1221
+ .................................
1222
+ ..............................
1223
+ ..........................
1224
+ ......................
1225
+ ................`;
1226
+ function colorize(raw) {
1227
+ if (noColor) return raw;
1228
+ let out = "";
1229
+ let style = "";
1230
+ for (const ch of raw) {
1231
+ const next = ".*".includes(ch) ? BLUE : "";
1232
+ if (next !== style) {
1233
+ if (style) out += RESET;
1234
+ if (next) out += next;
1235
+ style = next;
1236
+ }
1237
+ out += ch;
1238
+ }
1239
+ return style ? out + RESET : out;
1240
+ }
1241
+ const SPLASH = colorize(RAW);
1242
+ function printSplash() {
1243
+ if (!isTTY) return;
1244
+ const header = ` ${BOLD}Stencil${RESET} ${BLUE}v${CLI_VERSION}${RESET}`;
1245
+ const tagline = ` ${DIM}The Custom Element Compiler${RESET}`;
1246
+ process.stdout.write(`\n${SPLASH}\n\n${header}\n${tagline}\n\n`);
1247
+ }
1248
+ //#endregion
1249
+ //#region src/task-add.ts
1250
+ async function getInstalledPackageNames(rootDir) {
1251
+ try {
1252
+ const pkg = JSON.parse(await readFile(join(rootDir, "package.json"), "utf8"));
1253
+ const keys = (v) => Object.keys(v !== null && typeof v === "object" ? v : {});
1254
+ return new Set([...keys(pkg.dependencies), ...keys(pkg.devDependencies)]);
1255
+ } catch {
1256
+ return /* @__PURE__ */ new Set();
1257
+ }
1258
+ }
1259
+ async function selectInteractive(cwd) {
1260
+ const discovered = await discoverPlugins(cwd);
1261
+ const installed = await getInstalledPackageNames(cwd);
1262
+ const installable = KNOWN_INTEGRATIONS.filter((i) => !installed.has(i.package));
1263
+ const configurable = discovered.filter((d) => d.plugin.init != null);
1264
+ let toInstall = [];
1265
+ let toConfigure = [];
1266
+ if (installable.length > 0 || configurable.length > 0) {
1267
+ const result = await promptAddCapabilities(installable, configurable);
1268
+ toInstall = result.toInstall;
1269
+ toConfigure = result.toConfigure;
1270
+ } else p.log.info("All known integrations are already installed.");
1271
+ const customPackages = await promptCustomPackages();
1272
+ return {
1273
+ packagesToInstall: [...toInstall.map((i) => i.package), ...customPackages],
1274
+ pluginsToReconfigure: toConfigure
1275
+ };
1276
+ }
1277
+ async function taskAdd(packages, strictConfig) {
1278
+ const cwd = process.cwd();
1279
+ printSplash();
1280
+ p.intro("stencil add");
1281
+ if (isCI) {
1282
+ p.log.warn("Running in CI - non-interactive mode is not yet supported for `stencil add`.");
1283
+ process.exit(1);
1284
+ }
1285
+ let packagesToInstall = packages;
1286
+ let pluginsToReconfigure = [];
1287
+ if (packages.length === 0) ({packagesToInstall, pluginsToReconfigure} = await selectInteractive(cwd));
1288
+ if (packagesToInstall.length === 0 && pluginsToReconfigure.length === 0) {
1289
+ p.outro("Nothing to do.");
1290
+ return;
1291
+ }
1292
+ if (packagesToInstall.length > 0) if (process.env.STENCIL_WIZARD_DEV) p.log.warn(`Dev mode: skipping install, loading wizard from ${process.env.STENCIL_WIZARD_DEV}`);
1293
+ else {
1294
+ const s = p.spinner();
1295
+ s.start(`Installing ${packagesToInstall.join(", ")}`);
1296
+ await addDevDependency(withVersionRanges(packagesToInstall), {
1297
+ cwd,
1298
+ silent: true
1299
+ });
1300
+ s.stop("Installed");
1301
+ }
1302
+ const config = strictConfig ? toProjectConfig(strictConfig) : defaultProjectConfig(cwd);
1303
+ const context = {
1304
+ isNewProject: false,
1305
+ prompts: p,
1306
+ nypm,
1307
+ config,
1308
+ workspaceRoot: await detectWorkspaceRoot(cwd),
1309
+ ts,
1310
+ openStencilConfig: () => openStencilConfig(join(config.rootDir, "stencil.config.ts"))
1311
+ };
1312
+ if (packagesToInstall.length > 0) {
1313
+ const discovered = await discoverPlugins(cwd);
1314
+ const installedSet = new Set(packagesToInstall);
1315
+ for (const d of discovered) if (installedSet.has(d.packageName) && d.plugin.init?.run) await d.plugin.init.run(context);
1316
+ }
1317
+ for (const d of pluginsToReconfigure) if (d.plugin.init?.run) await d.plugin.init.run(context);
1318
+ p.outro("Done!");
1319
+ }
1320
+ //#endregion
1321
+ //#region src/check-version.ts
1322
+ /**
1323
+ * Retrieve a reference to the active `CompilerSystem`'s `checkVersion` function
1324
+ * @param config the Stencil configuration associated with the currently compiled project
1325
+ * @param currentVersion the Stencil compiler's version string
1326
+ * @param flags the CLI flags (owned by CLI, not part of core config)
1327
+ * @returns a reference to `checkVersion`, or `null` if one does not exist on the current `CompilerSystem`
1328
+ */
1329
+ const startCheckVersion = async (config, currentVersion, flags) => {
1330
+ if (config.devMode && !flags.ci && !currentVersion.includes("-dev.") && isFunction(config.sys.checkVersion)) return config.sys.checkVersion(config.logger, currentVersion);
1331
+ return null;
1332
+ };
1333
+ /**
1334
+ * Print the results of running the provided `versionChecker`.
1335
+ *
1336
+ * Does not print if no `versionChecker` is provided.
1337
+ *
1338
+ * @param versionChecker the function to invoke.
1339
+ */
1340
+ const printCheckVersionResults = async (versionChecker) => {
1341
+ if (versionChecker) {
1342
+ const checkVersionResults = await versionChecker;
1343
+ if (isFunction(checkVersionResults)) checkVersionResults();
1344
+ }
1345
+ };
1346
+ //#endregion
1347
+ //#region src/migrations/rules/build-dist-docs.ts
1348
+ /**
1349
+ * Migration rule for buildDist and buildDocs removal.
1350
+ *
1351
+ * In Stencil v5, these global config options are replaced with per-output-target
1352
+ * `skipInDev` property. This migration:
1353
+ * - Detects `buildDist` or `buildDocs` in stencil.config.ts
1354
+ * - Removes the property
1355
+ * - For `buildDist: true` or `buildDocs: true`, adds `skipInDev: false` to relevant output targets
1356
+ */
1357
+ const buildDistDocsRule = {
1358
+ id: "build-dist-docs",
1359
+ name: "buildDist/buildDocs Removal",
1360
+ description: "Remove deprecated buildDist and buildDocs config options",
1361
+ fromVersion: "4.x",
1362
+ toVersion: "5.x",
1363
+ detect(sourceFile) {
1364
+ const matches = [];
1365
+ const visit = (node) => {
1366
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name)) {
1367
+ const propName = node.name.text;
1368
+ if (propName === "buildDist" || propName === "buildDocs") {
1369
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
1370
+ const isTrue = node.initializer.kind === ts.SyntaxKind.TrueKeyword;
1371
+ matches.push({
1372
+ node,
1373
+ message: `Deprecated '${propName}' found${isTrue ? " (set to true)" : ""} - will be removed and skipInDev added to output targets`,
1374
+ line: line + 1,
1375
+ column: character + 1
1376
+ });
1377
+ }
1378
+ }
1379
+ ts.forEachChild(node, visit);
1380
+ };
1381
+ visit(sourceFile);
1382
+ return matches;
1383
+ },
1384
+ transform(sourceFile, matches) {
1385
+ if (matches.length === 0) return sourceFile.getFullText();
1386
+ let text = sourceFile.getFullText();
1387
+ const targetTypesNeedingSkipInDev = [];
1388
+ for (const match of matches) {
1389
+ const prop = match.node;
1390
+ const propName = prop.name.text;
1391
+ if (prop.initializer.kind === ts.SyntaxKind.TrueKeyword) {
1392
+ if (propName === "buildDist") targetTypesNeedingSkipInDev.push("dist", "dist-custom-elements", "dist-hydrate-script", "loader-bundle", "standalone", "ssr");
1393
+ else if (propName === "buildDocs") targetTypesNeedingSkipInDev.push("docs-readme", "docs-json", "docs-custom", "docs-vscode", "docs-custom-elements-manifest");
1394
+ }
1395
+ }
1396
+ const outputTargetsToModify = [];
1397
+ const findOutputTargets = (node) => {
1398
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === "outputTargets" && ts.isArrayLiteralExpression(node.initializer)) {
1399
+ for (const element of node.initializer.elements) if (ts.isObjectLiteralExpression(element)) {
1400
+ const typeProp = element.properties.find((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "type");
1401
+ if (typeProp && ts.isStringLiteral(typeProp.initializer)) {
1402
+ const targetType = typeProp.initializer.text;
1403
+ if (targetTypesNeedingSkipInDev.includes(targetType)) {
1404
+ if (!element.properties.some((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "skipInDev")) outputTargetsToModify.push(element);
1405
+ }
1406
+ }
1407
+ }
1408
+ }
1409
+ ts.forEachChild(node, findOutputTargets);
1410
+ };
1411
+ findOutputTargets(sourceFile);
1412
+ const allModifications = [];
1413
+ for (const match of matches) {
1414
+ const prop = match.node;
1415
+ const start = prop.getStart();
1416
+ let end = prop.getEnd();
1417
+ const afterProp = text.slice(end).match(/^\s*,/);
1418
+ if (afterProp) end = end + afterProp[0].length;
1419
+ allModifications.push({
1420
+ type: "remove",
1421
+ start,
1422
+ end,
1423
+ node: prop
1424
+ });
1425
+ }
1426
+ for (const target of outputTargetsToModify) {
1427
+ const lastProp = target.properties[target.properties.length - 1];
1428
+ if (lastProp) allModifications.push({
1429
+ type: "addSkipInDev",
1430
+ start: lastProp.getEnd(),
1431
+ end: lastProp.getEnd(),
1432
+ node: target
1433
+ });
1434
+ }
1435
+ allModifications.sort((a, b) => b.start - a.start);
1436
+ for (const mod of allModifications) if (mod.type === "remove") text = text.slice(0, mod.start) + text.slice(mod.end);
1437
+ else if (mod.type === "addSkipInDev") {
1438
+ const firstProp = mod.node.properties[0];
1439
+ let indent = " ";
1440
+ if (firstProp) {
1441
+ const propStart = firstProp.getStart();
1442
+ const lineStart = text.lastIndexOf("\n", propStart) + 1;
1443
+ const leadingWhitespace = text.slice(lineStart, propStart);
1444
+ if (/^\s+$/.test(leadingWhitespace)) indent = leadingWhitespace;
1445
+ }
1446
+ const afterLastProp = text.slice(mod.start).match(/^(\s*,)?/);
1447
+ const skipLength = afterLastProp && afterLastProp[1] ? afterLastProp[0].length : 0;
1448
+ text = text.slice(0, mod.start) + `,\n${indent}skipInDev: false,` + text.slice(mod.start + skipLength);
1449
+ }
1450
+ text = text.replace(/,\s*\n\s*\n/g, ",\n");
1451
+ text = text.replace(/{\s*\n\s*\n/g, "{\n");
1452
+ return text;
1453
+ }
1454
+ };
1455
+ //#endregion
1456
+ //#region src/migrations/rules/dev-mode.ts
1457
+ /**
1458
+ * Migration rule for `devMode` config option removal.
1459
+ *
1460
+ * In Stencil v5, `devMode` is no longer a user-settable config option in `stencil.config.ts`.
1461
+ * Build mode is controlled exclusively by the `--dev` CLI flag (default is production).
1462
+ * This migration removes `devMode` from the config object.
1463
+ */
1464
+ const devModeRule = {
1465
+ id: "dev-mode",
1466
+ name: "devMode Config Removal",
1467
+ description: "Remove deprecated devMode config option - use --dev CLI flag instead",
1468
+ fromVersion: "4.x",
1469
+ toVersion: "5.x",
1470
+ detect(sourceFile) {
1471
+ const matches = [];
1472
+ const visit = (node) => {
1473
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name)) {
1474
+ if (node.name.text === "devMode") {
1475
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
1476
+ matches.push({
1477
+ node,
1478
+ message: `Deprecated 'devMode' config option found - build mode is now set via the --dev CLI flag (production is the default)`,
1479
+ line: line + 1,
1480
+ column: character + 1
1481
+ });
1482
+ }
1483
+ }
1484
+ ts.forEachChild(node, visit);
1485
+ };
1486
+ visit(sourceFile);
1487
+ return matches;
1488
+ },
1489
+ transform(sourceFile, matches) {
1490
+ if (matches.length === 0) return sourceFile.getFullText();
1491
+ let text = sourceFile.getFullText();
1492
+ for (const match of [...matches].reverse()) {
1493
+ const node = match.node;
1494
+ const start = node.getFullStart();
1495
+ const end = node.getEnd();
1496
+ let removeEnd = end;
1497
+ const trailingComma = text.slice(end).match(/^\s*,/);
1498
+ if (trailingComma) removeEnd = end + trailingComma[0].length;
1499
+ text = text.slice(0, start) + text.slice(removeEnd);
1500
+ }
1501
+ return text;
1502
+ }
1503
+ };
1504
+ //#endregion
1505
+ //#region src/migrations/rules/encapsulation-api.ts
1506
+ /**
1507
+ * Migration rule for the @Component encapsulation API change.
1508
+ *
1509
+ * Migrates:
1510
+ * - `shadow: true` → `encapsulation: { type: 'shadow' }`
1511
+ * - `shadow: { delegatesFocus: true }` → `encapsulation: { type: 'shadow', delegatesFocus: true }`
1512
+ * - `scoped: true` → `encapsulation: { type: 'scoped' }`
1513
+ */
1514
+ const encapsulationApiRule = {
1515
+ id: "encapsulation-api",
1516
+ name: "Encapsulation API",
1517
+ description: "Migrate shadow/scoped properties to new encapsulation API",
1518
+ fromVersion: "4.x",
1519
+ toVersion: "5.x",
1520
+ detect(sourceFile) {
1521
+ const matches = [];
1522
+ const importMap = getStencilCoreImportMap(sourceFile);
1523
+ const visit = (node) => {
1524
+ if (ts.isDecorator(node) && ts.isCallExpression(node.expression)) {
1525
+ const decoratorName = node.expression.expression;
1526
+ if (ts.isIdentifier(decoratorName) && isStencilDecorator(decoratorName.text, "Component", importMap)) {
1527
+ const [arg] = node.expression.arguments;
1528
+ if (arg && ts.isObjectLiteralExpression(arg)) {
1529
+ for (const prop of arg.properties) if (ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.name)) {
1530
+ const propName = prop.name.text;
1531
+ if (propName === "shadow" || propName === "scoped") {
1532
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(prop.getStart());
1533
+ matches.push({
1534
+ node: prop,
1535
+ message: `Deprecated '${propName}' property found - migrate to 'encapsulation' API`,
1536
+ line: line + 1,
1537
+ column: character + 1
1538
+ });
1539
+ }
1540
+ }
1541
+ }
1542
+ }
1543
+ }
1544
+ ts.forEachChild(node, visit);
1545
+ };
1546
+ visit(sourceFile);
1547
+ return matches;
1548
+ },
1549
+ transform(sourceFile, matches) {
1550
+ if (matches.length === 0) return sourceFile.getFullText();
1551
+ let text = sourceFile.getFullText();
1552
+ const sortedMatches = [...matches].sort((a, b) => {
1553
+ const posA = a.node.getStart();
1554
+ return b.node.getStart() - posA;
1555
+ });
1556
+ for (const match of sortedMatches) {
1557
+ const prop = match.node;
1558
+ const propName = prop.name.text;
1559
+ const start = prop.getStart();
1560
+ const end = prop.getEnd();
1561
+ let replacement;
1562
+ if (propName === "shadow") if (prop.initializer.kind === ts.SyntaxKind.TrueKeyword) replacement = "encapsulation: { type: 'shadow' }";
1563
+ else if (ts.isObjectLiteralExpression(prop.initializer)) {
1564
+ const options = [];
1565
+ for (const innerProp of prop.initializer.properties) if (ts.isPropertyAssignment(innerProp) && ts.isIdentifier(innerProp.name)) {
1566
+ const optName = innerProp.name.text;
1567
+ const optValue = innerProp.initializer.getText();
1568
+ options.push(`${optName}: ${optValue}`);
1569
+ }
1570
+ if (options.length > 0) replacement = `encapsulation: { type: 'shadow', ${options.join(", ")} }`;
1571
+ else replacement = "encapsulation: { type: 'shadow' }";
1572
+ } else replacement = "";
1573
+ else if (propName === "scoped") if (prop.initializer.kind === ts.SyntaxKind.TrueKeyword) replacement = "encapsulation: { type: 'scoped' }";
1574
+ else replacement = "";
1575
+ else continue;
1576
+ let endPos = end;
1577
+ const afterProp = text.slice(end).match(/^\s*,/);
1578
+ if (afterProp && replacement === "") endPos = end + afterProp[0].length;
1579
+ else if (afterProp && replacement !== "") {} else if (!afterProp && replacement !== "") {}
1580
+ text = text.slice(0, start) + replacement + text.slice(endPos);
1581
+ }
1582
+ return text;
1583
+ }
1584
+ };
1585
+ //#endregion
1586
+ //#region src/migrations/rules/external-runtime.ts
1587
+ /**
1588
+ * Migration rule for `externalRuntime` on `standalone` output targets.
1589
+ *
1590
+ * In Stencil v5, `externalRuntime` defaults to `false` (was `true` in v4).
1591
+ * Explicit `externalRuntime: false` is now redundant and can be removed.
1592
+ */
1593
+ const externalRuntimeRule = {
1594
+ id: "external-runtime",
1595
+ name: "externalRuntime Default Change",
1596
+ description: "Remove redundant 'externalRuntime: false' from standalone output targets - false is now the default",
1597
+ fromVersion: "4.x",
1598
+ toVersion: "5.x",
1599
+ detect(sourceFile) {
1600
+ const matches = [];
1601
+ const visit = (node) => {
1602
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === "externalRuntime" && node.initializer.kind === ts.SyntaxKind.FalseKeyword) {
1603
+ const parent = node.parent;
1604
+ if (ts.isObjectLiteralExpression(parent)) {
1605
+ if (parent.properties.some((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "type" && ts.isStringLiteral(p.initializer) && p.initializer.text === "standalone")) {
1606
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
1607
+ matches.push({
1608
+ node,
1609
+ message: "'externalRuntime: false' is now the default - this property can be removed",
1610
+ line: line + 1,
1611
+ column: character + 1
1612
+ });
1613
+ }
1614
+ }
1615
+ }
1616
+ ts.forEachChild(node, visit);
1617
+ };
1618
+ visit(sourceFile);
1619
+ return matches;
1620
+ },
1621
+ transform(sourceFile, matches) {
1622
+ if (matches.length === 0) return sourceFile.getFullText();
1623
+ let text = sourceFile.getFullText();
1624
+ for (const match of [...matches].reverse()) {
1625
+ const node = match.node;
1626
+ const start = node.getFullStart();
1627
+ const end = node.getEnd();
1628
+ let removeEnd = end;
1629
+ const trailingComma = text.slice(end).match(/^\s*,/);
1630
+ if (trailingComma) removeEnd = end + trailingComma[0].length;
1631
+ text = text.slice(0, start) + text.slice(removeEnd);
1632
+ }
1633
+ return text;
1634
+ }
1635
+ };
1636
+ //#endregion
1637
+ //#region src/migrations/rules/extras-to-compat.ts
1638
+ /**
1639
+ * Migration rule: rename the top-level `extras` config key to `compat`.
1640
+ *
1641
+ * In v5, `extras` is replaced by `compat` (framework/bundler compatibility flags).
1642
+ */
1643
+ const extrasToCompatRule = {
1644
+ id: "extras-to-compat",
1645
+ name: "Extras → Compat Rename",
1646
+ description: "Rename top-level 'extras' config key to 'compat'",
1647
+ fromVersion: "4.x",
1648
+ toVersion: "5.x",
1649
+ detect(sourceFile) {
1650
+ const matches = [];
1651
+ const visit = (node) => {
1652
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name)) {
1653
+ if (node.name.text === "extras") {
1654
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
1655
+ matches.push({
1656
+ node,
1657
+ message: "'extras' has been renamed to 'compat'",
1658
+ line: line + 1,
1659
+ column: character + 1
1660
+ });
1661
+ }
1662
+ }
1663
+ ts.forEachChild(node, visit);
1664
+ };
1665
+ visit(sourceFile);
1666
+ return matches;
1667
+ },
1668
+ transform(sourceFile, matches) {
1669
+ if (matches.length === 0) return sourceFile.getFullText();
1670
+ let text = sourceFile.getFullText();
1671
+ const sorted = [...matches].sort((a, b) => b.node.getStart() - a.node.getStart());
1672
+ for (const match of sorted) {
1673
+ const node = match.node;
1674
+ if (node.name.text === "extras") {
1675
+ const keyStart = node.name.getStart();
1676
+ const keyEnd = node.name.getEnd();
1677
+ text = text.slice(0, keyStart) + "compat" + text.slice(keyEnd);
1678
+ }
1679
+ }
1680
+ return text;
1681
+ }
1682
+ };
1683
+ //#endregion
1684
+ //#region src/migrations/rules/form-associated.ts
1685
+ /**
1686
+ * Migration rule for formAssociated → @AttachInternals.
1687
+ *
1688
+ * Migrates:
1689
+ * - `formAssociated: true` in @Component → Adds `@AttachInternals() internals: ElementInternals;`
1690
+ */
1691
+ const formAssociatedRule = {
1692
+ id: "form-associated",
1693
+ name: "Form Associated",
1694
+ description: "Migrate formAssociated to @AttachInternals decorator",
1695
+ fromVersion: "4.x",
1696
+ toVersion: "5.x",
1697
+ detect(sourceFile) {
1698
+ const matches = [];
1699
+ const importMap = getStencilCoreImportMap(sourceFile);
1700
+ let hasAttachInternalsImport = false;
1701
+ let stencilImportEnd = 0;
1702
+ for (const statement of sourceFile.statements) if (ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier) && statement.moduleSpecifier.text === "@stencil/core") {
1703
+ stencilImportEnd = statement.getEnd();
1704
+ for (const [, originalName] of importMap) if (originalName === "AttachInternals") {
1705
+ hasAttachInternalsImport = true;
1706
+ break;
1707
+ }
1708
+ break;
1709
+ }
1710
+ const visit = (node) => {
1711
+ if (ts.isClassDeclaration(node)) {
1712
+ const decorators = ts.getDecorators(node);
1713
+ if (!decorators) {
1714
+ ts.forEachChild(node, visit);
1715
+ return;
1716
+ }
1717
+ let componentDecorator;
1718
+ let formAssociatedProp;
1719
+ for (const decorator of decorators) if (ts.isCallExpression(decorator.expression) && ts.isIdentifier(decorator.expression.expression) && isStencilDecorator(decorator.expression.expression.text, "Component", importMap)) {
1720
+ componentDecorator = decorator;
1721
+ const [arg] = decorator.expression.arguments;
1722
+ if (arg && ts.isObjectLiteralExpression(arg)) {
1723
+ for (const prop of arg.properties) if (ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.name) && prop.name.text === "formAssociated") {
1724
+ formAssociatedProp = prop;
1725
+ break;
1726
+ }
1727
+ }
1728
+ break;
1729
+ }
1730
+ if (componentDecorator && formAssociatedProp) {
1731
+ let hasAttachInternals = false;
1732
+ for (const member of node.members) if (ts.isPropertyDeclaration(member) || ts.isMethodDeclaration(member)) {
1733
+ const memberDecorators = ts.getDecorators(member);
1734
+ if (memberDecorators) {
1735
+ for (const d of memberDecorators) if (ts.isCallExpression(d.expression) && ts.isIdentifier(d.expression.expression) && isStencilDecorator(d.expression.expression.text, "AttachInternals", importMap)) {
1736
+ hasAttachInternals = true;
1737
+ break;
1738
+ }
1739
+ }
1740
+ }
1741
+ let searchStart = node.name ? node.name.getEnd() : node.getStart(sourceFile);
1742
+ if (node.heritageClauses) for (const clause of node.heritageClauses) searchStart = Math.max(searchStart, clause.getEnd());
1743
+ const braceMatch = sourceFile.getFullText().slice(searchStart).match(/\s*\{/);
1744
+ if (!braceMatch) {
1745
+ ts.forEachChild(node, visit);
1746
+ return;
1747
+ }
1748
+ const classBodyStart = searchStart + braceMatch[0].length;
1749
+ let indent = " ";
1750
+ if (node.members.length > 0) {
1751
+ const memberStart = node.members[0].getStart(sourceFile);
1752
+ const indentMatch = sourceFile.getFullText().slice(classBodyStart, memberStart).match(/\n(\s+)/);
1753
+ if (indentMatch) indent = indentMatch[1];
1754
+ }
1755
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(formAssociatedProp.getStart());
1756
+ matches.push({
1757
+ node: formAssociatedProp,
1758
+ message: hasAttachInternals ? "Remove 'formAssociated' (already has @AttachInternals)" : "Migrate 'formAssociated' to @AttachInternals decorator",
1759
+ line: line + 1,
1760
+ column: character + 1,
1761
+ classBodyStart,
1762
+ hasAttachInternals,
1763
+ indent,
1764
+ needsImport: !hasAttachInternalsImport && !hasAttachInternals,
1765
+ stencilImportEnd
1766
+ });
1767
+ }
1768
+ }
1769
+ ts.forEachChild(node, visit);
1770
+ };
1771
+ visit(sourceFile);
1772
+ return matches;
1773
+ },
1774
+ transform(sourceFile, matches) {
1775
+ if (matches.length === 0) return sourceFile.getFullText();
1776
+ let text = sourceFile.getFullText();
1777
+ const typedMatches = matches;
1778
+ const sortedMatches = [...typedMatches].sort((a, b) => {
1779
+ return b.classBodyStart - a.classBodyStart;
1780
+ });
1781
+ for (const match of sortedMatches) {
1782
+ if (!match.hasAttachInternals) {
1783
+ const newMember = `\n${match.indent}@AttachInternals() internals: ElementInternals;\n`;
1784
+ text = text.slice(0, match.classBodyStart) + newMember + text.slice(match.classBodyStart);
1785
+ }
1786
+ const prop = match.node;
1787
+ const start = prop.getStart();
1788
+ let end = prop.getEnd();
1789
+ const afterProp = text.slice(end).match(/^\s*,/);
1790
+ if (afterProp) end = end + afterProp[0].length;
1791
+ text = text.slice(0, start) + text.slice(end);
1792
+ }
1793
+ const firstMatch = typedMatches[0];
1794
+ if (firstMatch?.needsImport && firstMatch.stencilImportEnd > 0) {
1795
+ const importMatch = text.match(/import\s*\{([^}]*)\}\s*from\s*['"]@stencil\/core['"]/);
1796
+ if (importMatch) {
1797
+ const newImports = importMatch[1].trimEnd() + ", AttachInternals";
1798
+ text = text.replace(importMatch[0], `import {${newImports}} from '@stencil/core'`);
1799
+ }
1800
+ }
1801
+ return text;
1802
+ }
1803
+ };
1804
+ //#endregion
1805
+ //#region src/migrations/rules/global-style-inject.ts
1806
+ /**
1807
+ * Migration rule for `extras.addGlobalStyleToComponents` → `global-style` output target `inject`.
1808
+ *
1809
+ * In v5, the `addGlobalStyleToComponents` extras option is removed. Instead, configure
1810
+ * the `inject` option on the `global-style` output target.
1811
+ *
1812
+ * Migration mapping:
1813
+ * - `addGlobalStyleToComponents: true` → `inject: 'all'`
1814
+ * - `addGlobalStyleToComponents: 'client'` → `inject: 'client'`
1815
+ * - `addGlobalStyleToComponents: false` → omit (default is 'none')
1816
+ *
1817
+ * Note: This migration only acts on explicitly set `addGlobalStyleToComponents`.
1818
+ * Users who relied on the implicit v4 default ('client') will need to manually
1819
+ * add `inject: 'client'` to their global-style output target if desired.
1820
+ */
1821
+ const globalStyleInjectRule = {
1822
+ id: "global-style-inject",
1823
+ name: "Global Style Inject Migration",
1824
+ description: "Migrate extras.addGlobalStyleToComponents to global-style output target inject option",
1825
+ fromVersion: "4.x",
1826
+ toVersion: "5.x",
1827
+ detect(sourceFile) {
1828
+ const matches = [];
1829
+ const visit = (node) => {
1830
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === "addGlobalStyleToComponents") {
1831
+ const parent = node.parent;
1832
+ if (ts.isObjectLiteralExpression(parent)) {
1833
+ const grandparent = parent.parent;
1834
+ if (ts.isPropertyAssignment(grandparent) && ts.isIdentifier(grandparent.name) && grandparent.name.text === "extras") {
1835
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
1836
+ matches.push({
1837
+ node,
1838
+ message: `extras.addGlobalStyleToComponents is removed. Use 'inject' on global-style output target instead.`,
1839
+ line: line + 1,
1840
+ column: character + 1
1841
+ });
1842
+ }
1843
+ }
1844
+ }
1845
+ ts.forEachChild(node, visit);
1846
+ };
1847
+ visit(sourceFile);
1848
+ return matches;
1849
+ },
1850
+ transform(sourceFile, matches) {
1851
+ if (matches.length === 0) return sourceFile.getFullText();
1852
+ let text = sourceFile.getFullText();
1853
+ const matchNode = matches[0].node;
1854
+ if (!ts.isPropertyAssignment(matchNode)) return text;
1855
+ let injectValue = null;
1856
+ if (matchNode.initializer.kind === ts.SyntaxKind.TrueKeyword) injectValue = "all";
1857
+ else if (ts.isStringLiteral(matchNode.initializer) && matchNode.initializer.text === "client") injectValue = "client";
1858
+ let insertionOffset = 0;
1859
+ if (injectValue) {
1860
+ const result = addGlobalStyleOutputTarget(text, sourceFile, injectValue);
1861
+ insertionOffset = result.length - text.length;
1862
+ text = result;
1863
+ }
1864
+ let start = matchNode.getStart();
1865
+ let end = matchNode.getEnd();
1866
+ const outputTargetsEnd = findOutputTargetsEnd(sourceFile);
1867
+ if (insertionOffset !== 0 && outputTargetsEnd !== null && matchNode.getStart() > outputTargetsEnd) {
1868
+ start += insertionOffset;
1869
+ end += insertionOffset;
1870
+ }
1871
+ const afterProp = text.slice(end).match(/^\s*,/);
1872
+ if (afterProp) end = end + afterProp[0].length;
1873
+ else {
1874
+ const beforeProp = text.slice(0, start).match(/,\s*$/);
1875
+ if (beforeProp) {
1876
+ text = text.slice(0, start - beforeProp[0].length) + text.slice(end);
1877
+ end = -1;
1878
+ }
1879
+ }
1880
+ if (end !== -1) text = text.slice(0, start) + text.slice(end);
1881
+ text = cleanupEmptyExtras$1(text);
1882
+ return text;
1883
+ }
1884
+ };
1885
+ /**
1886
+ * Find the end position of the outputTargets array in the source file.
1887
+ * @param sourceFile The source file to search
1888
+ * @returns The end position of the outputTargets array, or null if not found
1889
+ */
1890
+ function findOutputTargetsEnd(sourceFile) {
1891
+ let endPos = null;
1892
+ const visit = (node) => {
1893
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === "outputTargets") endPos = node.getEnd();
1894
+ ts.forEachChild(node, visit);
1895
+ };
1896
+ visit(sourceFile);
1897
+ return endPos;
1898
+ }
1899
+ /**
1900
+ * Clean up empty extras object after removing addGlobalStyleToComponents.
1901
+ * @param text The source text to clean up
1902
+ * @returns The cleaned up text with empty extras removed
1903
+ */
1904
+ function cleanupEmptyExtras$1(text) {
1905
+ return text.replace(/,?\s*extras\s*:\s*\{\s*\},?/g, "");
1906
+ }
1907
+ /**
1908
+ * Add a global-style output target with the specified inject value.
1909
+ * @param text The source text to modify
1910
+ * @param sourceFile The source file for position info
1911
+ * @param injectValue The inject value to set on the new global-style output target
1912
+ * @returns The modified text with the new global-style output target added
1913
+ */
1914
+ function addGlobalStyleOutputTarget(text, sourceFile, injectValue) {
1915
+ if (text.includes("type: 'global-style'")) return text;
1916
+ let outputTargetsArray = null;
1917
+ const findOutputTargets = (node) => {
1918
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === "outputTargets" && ts.isArrayLiteralExpression(node.initializer)) outputTargetsArray = node.initializer;
1919
+ ts.forEachChild(node, findOutputTargets);
1920
+ };
1921
+ findOutputTargets(sourceFile);
1922
+ if (!outputTargetsArray) return text;
1923
+ const array = outputTargetsArray;
1924
+ let indent = " ";
1925
+ if (array.elements.length > 0) {
1926
+ const elemStart = array.elements[0].getStart();
1927
+ const lineStart = text.lastIndexOf("\n", elemStart) + 1;
1928
+ const leadingWhitespace = text.slice(lineStart, elemStart);
1929
+ if (/^\s+$/.test(leadingWhitespace)) indent = leadingWhitespace;
1930
+ }
1931
+ const lastElement = array.elements[array.elements.length - 1];
1932
+ if (!lastElement) {
1933
+ const arrayStart = array.getStart() + 1;
1934
+ const newTarget = `\n${indent}{\n${indent} type: 'global-style',\n${indent} inject: '${injectValue}',\n${indent}}\n${indent.slice(2)}`;
1935
+ return text.slice(0, arrayStart) + newTarget + text.slice(arrayStart);
1936
+ }
1937
+ let insertPos = lastElement.getEnd();
1938
+ const afterLastElement = text.slice(insertPos).match(/^(\s*,)?/);
1939
+ const hasTrailingComma = afterLastElement && afterLastElement[1];
1940
+ if (hasTrailingComma) insertPos += afterLastElement[0].length;
1941
+ const newTarget = `{\n${indent} type: 'global-style',\n${indent} inject: '${injectValue}',\n${indent}}`;
1942
+ const insertion = (hasTrailingComma ? "" : ",") + "\n" + indent + newTarget;
1943
+ return text.slice(0, insertPos) + insertion + text.slice(insertPos);
1944
+ }
1945
+ //#endregion
1946
+ //#region src/migrations/rules/hash-file-names.ts
1947
+ /**
1948
+ * Migration rule for `hashFileNames` and `hashedFileNameLength` config options.
1949
+ *
1950
+ * In Stencil v5, these are no longer top-level config options. They belong on
1951
+ * the `loader-bundle` and `www` output targets, which are the only outputs that
1952
+ * are served directly in the browser and benefit from content-hash caching.
1953
+ *
1954
+ * This migration:
1955
+ * 1. Removes them from the top-level config
1956
+ * 2. Injects them into any `loader-bundle` and `www` output targets found in the same file
1957
+ */
1958
+ const hashFileNamesRule = {
1959
+ id: "hash-file-names",
1960
+ name: "Hash File Names Config Move",
1961
+ description: "Move hashFileNames and hashedFileNameLength from top-level config to loader-bundle and www output targets",
1962
+ fromVersion: "4.x",
1963
+ toVersion: "5.x",
1964
+ detect(sourceFile) {
1965
+ const matches = [];
1966
+ const visit = (node) => {
1967
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && (node.name.text === "hashFileNames" || node.name.text === "hashedFileNameLength")) {
1968
+ const parent = node.parent;
1969
+ if (ts.isObjectLiteralExpression(parent)) {
1970
+ if (!parent.properties.some((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "type")) {
1971
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
1972
+ matches.push({
1973
+ node,
1974
+ message: `'${node.name.text}' is no longer a top-level config option. Move it to your 'loader-bundle' and/or 'www' output targets.`,
1975
+ line: line + 1,
1976
+ column: character + 1
1977
+ });
1978
+ }
1979
+ }
1980
+ }
1981
+ ts.forEachChild(node, visit);
1982
+ };
1983
+ visit(sourceFile);
1984
+ return matches;
1985
+ },
1986
+ transform(sourceFile, matches) {
1987
+ if (matches.length === 0) return sourceFile.getFullText();
1988
+ const fullText = sourceFile.getFullText();
1989
+ const propsToInject = matches.map((m) => {
1990
+ const node = m.node;
1991
+ return {
1992
+ name: node.name.text,
1993
+ value: node.initializer.getText(sourceFile)
1994
+ };
1995
+ });
1996
+ const TARGET_TYPES = new Set(["loader-bundle", "www"]);
1997
+ const insertionsByPos = /* @__PURE__ */ new Map();
1998
+ const visit = (node) => {
1999
+ if (ts.isObjectLiteralExpression(node)) {
2000
+ 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))) {
2001
+ const existingPropNames = new Set(node.properties.filter((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name)).map((p) => p.name.text));
2002
+ const objStart = node.getStart(sourceFile);
2003
+ const objLineStart = fullText.lastIndexOf("\n", objStart) + 1;
2004
+ const propIndent = (fullText.slice(objLineStart, objStart).match(/^(\s*)/)?.[1] ?? "") + " ";
2005
+ const closingBracePos = node.getEnd() - 1;
2006
+ const isMultiLine = fullText.slice(objStart, node.getEnd()).includes("\n");
2007
+ let insertPos;
2008
+ if (isMultiLine) insertPos = fullText.lastIndexOf("\n", closingBracePos - 1);
2009
+ else {
2010
+ insertPos = closingBracePos;
2011
+ while (insertPos > 0 && fullText[insertPos - 1] === " ") insertPos--;
2012
+ }
2013
+ const existing = insertionsByPos.get(insertPos) ?? [];
2014
+ for (const prop of propsToInject) if (!existingPropNames.has(prop.name)) existing.push(isMultiLine ? `\n${propIndent}${prop.name}: ${prop.value},` : `, ${prop.name}: ${prop.value}`);
2015
+ if (existing.length > 0) insertionsByPos.set(insertPos, existing);
2016
+ }
2017
+ }
2018
+ ts.forEachChild(node, visit);
2019
+ };
2020
+ visit(sourceFile);
2021
+ const edits = [];
2022
+ for (const match of matches) {
2023
+ const node = match.node;
2024
+ const start = node.getFullStart();
2025
+ const end = node.getEnd();
2026
+ let removeEnd = end;
2027
+ const trailingComma = fullText.slice(end).match(/^\s*,/);
2028
+ if (trailingComma) removeEnd = end + trailingComma[0].length;
2029
+ edits.push({
2030
+ start,
2031
+ end: removeEnd,
2032
+ replacement: ""
2033
+ });
2034
+ }
2035
+ for (const [pos, insertions] of insertionsByPos) edits.push({
2036
+ start: pos,
2037
+ end: pos,
2038
+ replacement: insertions.join("")
2039
+ });
2040
+ edits.sort((a, b) => b.start - a.start);
2041
+ let text = fullText;
2042
+ for (const edit of edits) text = text.slice(0, edit.start) + edit.replacement + text.slice(edit.end);
2043
+ return text;
2044
+ }
2045
+ };
2046
+ //#endregion
2047
+ //#region src/migrations/rules/light-dom-patches.ts
2048
+ /**
2049
+ * Migration rule for slot-fix extras → `lightDomPatches`.
2050
+ *
2051
+ * In v5, the individual slot-fix flags and `experimentalSlotFixes` umbrella are replaced
2052
+ * by a single `lightDomPatches` option which defaults to `true`.
2053
+ *
2054
+ * Migration mapping:
2055
+ * - `experimentalSlotFixes: true` → remove (new default is `true`)
2056
+ * - `experimentalSlotFixes: false` → `lightDomPatches: false`
2057
+ * - Individual flags only → `lightDomPatches: { <new names> }`
2058
+ *
2059
+ * Old → new individual key names:
2060
+ * appendChildSlotFix → domMutations
2061
+ * cloneNodeFix → cloneNode
2062
+ * scopedSlotTextContentFix → textContent
2063
+ * slotChildNodesFix → childNodes
2064
+ */
2065
+ const lightDomPatchesRule = {
2066
+ id: "light-dom-patches",
2067
+ name: "Light DOM Patches Migration",
2068
+ description: "Migrate experimentalSlotFixes / individual slot-fix flags to lightDomPatches",
2069
+ fromVersion: "4.x",
2070
+ toVersion: "5.x",
2071
+ detect(sourceFile) {
2072
+ const matches = [];
2073
+ const oldKeys = new Set([
2074
+ "experimentalSlotFixes",
2075
+ "appendChildSlotFix",
2076
+ "cloneNodeFix",
2077
+ "scopedSlotTextContentFix",
2078
+ "slotChildNodesFix"
2079
+ ]);
2080
+ const visit = (node) => {
2081
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && oldKeys.has(node.name.text)) {
2082
+ const parent = node.parent;
2083
+ if (ts.isObjectLiteralExpression(parent)) {
2084
+ const grandparent = parent.parent;
2085
+ if (ts.isPropertyAssignment(grandparent) && ts.isIdentifier(grandparent.name) && grandparent.name.text === "extras") {
2086
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
2087
+ matches.push({
2088
+ node,
2089
+ message: `extras.${node.name.text} is removed. Use 'extras.lightDomPatches' instead.`,
2090
+ line: line + 1,
2091
+ column: character + 1
2092
+ });
2093
+ }
2094
+ }
2095
+ }
2096
+ ts.forEachChild(node, visit);
2097
+ };
2098
+ visit(sourceFile);
2099
+ return matches;
2100
+ },
2101
+ transform(sourceFile, matches) {
2102
+ if (matches.length === 0) return sourceFile.getFullText();
2103
+ const oldKeyMap = {};
2104
+ for (const match of matches) {
2105
+ const node = match.node;
2106
+ const key = node.name.text;
2107
+ const init = node.initializer;
2108
+ oldKeyMap[key] = init.kind === ts.SyntaxKind.TrueKeyword ? true : init.kind === ts.SyntaxKind.FalseKeyword ? false : void 0;
2109
+ }
2110
+ const keyRename = {
2111
+ appendChildSlotFix: "domMutations",
2112
+ cloneNodeFix: "cloneNode",
2113
+ scopedSlotTextContentFix: "textContent",
2114
+ slotChildNodesFix: "childNodes"
2115
+ };
2116
+ const experimentalValue = oldKeyMap["experimentalSlotFixes"];
2117
+ const hasIndividualKeys = matches.some((m) => {
2118
+ return m.node.name.text !== "experimentalSlotFixes";
2119
+ });
2120
+ let replacement = null;
2121
+ if (experimentalValue === true && !hasIndividualKeys) replacement = null;
2122
+ else if (experimentalValue === false && !hasIndividualKeys) replacement = "lightDomPatches: false";
2123
+ else if (experimentalValue === true && hasIndividualKeys) replacement = null;
2124
+ else {
2125
+ const parts = [];
2126
+ for (const [oldKey, newKey] of Object.entries(keyRename)) {
2127
+ const val = oldKeyMap[oldKey];
2128
+ if (val === true) parts.push(`${newKey}: true`);
2129
+ else if (val === false) parts.push(`${newKey}: false`);
2130
+ }
2131
+ if (parts.length > 0) replacement = `lightDomPatches: { ${parts.join(", ")} }`;
2132
+ }
2133
+ const sorted = [...matches].sort((a, b) => b.node.getStart() - a.node.getStart());
2134
+ let text = sourceFile.getFullText();
2135
+ let replacementInserted = false;
2136
+ for (const match of sorted) {
2137
+ const node = match.node;
2138
+ let start = node.getStart();
2139
+ let end = node.getEnd();
2140
+ const trailingComma = text.slice(end).match(/^(\s*,)/);
2141
+ if (trailingComma) end += trailingComma[1].length;
2142
+ else {
2143
+ const leadingComma = text.slice(0, start).match(/,\s*$/);
2144
+ if (leadingComma) start -= leadingComma[0].length;
2145
+ }
2146
+ if (!replacementInserted && replacement !== null) {
2147
+ text = text.slice(0, start) + replacement + text.slice(end);
2148
+ replacementInserted = true;
2149
+ } else text = text.slice(0, start) + text.slice(end);
2150
+ }
2151
+ text = cleanupEmptyExtras(text);
2152
+ return text;
2153
+ }
2154
+ };
2155
+ function cleanupEmptyExtras(text) {
2156
+ return text.replace(/,?\s*extras\s*:\s*\{\s*\},?/g, "");
2157
+ }
2158
+ //#endregion
2159
+ //#region src/migrations/rules/output-target-renames.ts
2160
+ /**
2161
+ * Migration rule for output target renames in Stencil v5.
2162
+ *
2163
+ * This migration:
2164
+ * - Renames `dist` → `loader-bundle`
2165
+ * - Renames `dist-custom-elements` → `standalone`
2166
+ * - Renames `dist-hydrate-script` → `ssr`
2167
+ * - Renames `dist-collection` → `collection`
2168
+ * - Renames `dist-types` → `types`
2169
+ * - Extracts `collectionDir` from loader-bundle into separate `collection` output
2170
+ * - Extracts `typesDir` from loader-bundle into separate `types` output
2171
+ * - Renames `esmLoaderPath` → `loaderPath` (applies to all module formats, not just ESM)
2172
+ * - Removes `isPrimaryPackageOutputTarget` (no longer needed, package.json validation auto-detects)
2173
+ * - Removes `generateTypeDeclarations` (types are now auto-generated via the `types` output target)
2174
+ */
2175
+ const outputTargetRenamesRule = {
2176
+ id: "output-target-renames",
2177
+ name: "Output Target Renames",
2178
+ description: "Rename output targets to new v5 names",
2179
+ fromVersion: "4.x",
2180
+ toVersion: "5.x",
2181
+ detect(sourceFile) {
2182
+ const matches = [];
2183
+ const oldToNewNames = {
2184
+ dist: "loader-bundle",
2185
+ "dist-custom-elements": "standalone",
2186
+ "dist-hydrate-script": "ssr",
2187
+ "dist-collection": "collection",
2188
+ "dist-types": "types"
2189
+ };
2190
+ const visit = (node) => {
2191
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === "type" && ts.isStringLiteral(node.initializer)) {
2192
+ const typeValue = node.initializer.text;
2193
+ if (typeValue in oldToNewNames) {
2194
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
2195
+ matches.push({
2196
+ node,
2197
+ message: `Output target type '${typeValue}' → '${oldToNewNames[typeValue]}'`,
2198
+ line: line + 1,
2199
+ column: character + 1
2200
+ });
2201
+ }
2202
+ }
2203
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && (node.name.text === "collectionDir" || node.name.text === "typesDir")) {
2204
+ const parent = node.parent;
2205
+ if (ts.isObjectLiteralExpression(parent)) {
2206
+ if (parent.properties.some((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "type")) {
2207
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
2208
+ const propName = node.name.text;
2209
+ const newType = propName === "collectionDir" ? "collection" : "types";
2210
+ matches.push({
2211
+ node,
2212
+ message: `Property '${propName}' will be extracted to separate '${newType}' output target`,
2213
+ line: line + 1,
2214
+ column: character + 1
2215
+ });
2216
+ }
2217
+ }
2218
+ }
2219
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === "esmLoaderPath") {
2220
+ const parent = node.parent;
2221
+ if (ts.isObjectLiteralExpression(parent)) {
2222
+ if (parent.properties.some((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "type")) {
2223
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
2224
+ matches.push({
2225
+ node,
2226
+ message: `Property 'esmLoaderPath' renamed to 'loaderPath' (applies to all module formats)`,
2227
+ line: line + 1,
2228
+ column: character + 1
2229
+ });
2230
+ }
2231
+ }
2232
+ }
2233
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && (node.name.text === "isPrimaryPackageOutputTarget" || node.name.text === "generateTypeDeclarations")) {
2234
+ const parent = node.parent;
2235
+ if (ts.isObjectLiteralExpression(parent)) {
2236
+ if (parent.properties.some((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "type")) {
2237
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
2238
+ const propName = node.name.text;
2239
+ const reason = propName === "isPrimaryPackageOutputTarget" ? "Package.json validation now auto-detects based on configured outputs" : "Types are now auto-generated via the 'types' output target";
2240
+ matches.push({
2241
+ node,
2242
+ message: `Property '${propName}' is removed in v5. ${reason}`,
2243
+ line: line + 1,
2244
+ column: character + 1
2245
+ });
2246
+ }
2247
+ }
2248
+ }
2249
+ ts.forEachChild(node, visit);
2250
+ };
2251
+ visit(sourceFile);
2252
+ return matches;
2253
+ },
2254
+ transform(sourceFile, matches) {
2255
+ if (matches.length === 0) return sourceFile.getFullText();
2256
+ let text = sourceFile.getFullText();
2257
+ const oldToNewNames = {
2258
+ dist: "loader-bundle",
2259
+ "dist-custom-elements": "standalone",
2260
+ "dist-hydrate-script": "ssr",
2261
+ "dist-collection": "collection",
2262
+ "dist-types": "types"
2263
+ };
2264
+ const outputTargetsToExtract = [];
2265
+ const findOutputTargetsToExtract = (node) => {
2266
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === "outputTargets" && ts.isArrayLiteralExpression(node.initializer)) {
2267
+ for (const element of node.initializer.elements) if (ts.isObjectLiteralExpression(element)) {
2268
+ let collectionDir;
2269
+ let typesDir;
2270
+ for (const prop of element.properties) if (ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.name)) {
2271
+ if (prop.name.text === "collectionDir" && ts.isStringLiteral(prop.initializer)) collectionDir = prop.initializer.text;
2272
+ else if (prop.name.text === "typesDir" && ts.isStringLiteral(prop.initializer)) typesDir = prop.initializer.text;
2273
+ }
2274
+ if (collectionDir || typesDir) outputTargetsToExtract.push({
2275
+ targetNode: element,
2276
+ collectionDir,
2277
+ typesDir
2278
+ });
2279
+ }
2280
+ }
2281
+ ts.forEachChild(node, findOutputTargetsToExtract);
2282
+ };
2283
+ findOutputTargetsToExtract(sourceFile);
2284
+ const modifications = [];
2285
+ for (const match of matches) {
2286
+ const prop = match.node;
2287
+ const propName = prop.name.text;
2288
+ if (propName === "type" && ts.isStringLiteral(prop.initializer)) {
2289
+ const newType = oldToNewNames[prop.initializer.text];
2290
+ if (newType) {
2291
+ const start = prop.initializer.getStart() + 1;
2292
+ const end = prop.initializer.getEnd() - 1;
2293
+ modifications.push({
2294
+ type: "replace",
2295
+ start,
2296
+ end,
2297
+ replacement: newType
2298
+ });
2299
+ }
2300
+ } else if (propName === "esmLoaderPath") {
2301
+ const nameNode = prop.name;
2302
+ modifications.push({
2303
+ type: "replace",
2304
+ start: nameNode.getStart(),
2305
+ end: nameNode.getEnd(),
2306
+ replacement: "loaderPath"
2307
+ });
2308
+ if (ts.isStringLiteral(prop.initializer)) {
2309
+ const newPath = "../" + prop.initializer.text;
2310
+ modifications.push({
2311
+ type: "replace",
2312
+ start: prop.initializer.getStart() + 1,
2313
+ end: prop.initializer.getEnd() - 1,
2314
+ replacement: newPath
2315
+ });
2316
+ }
2317
+ } else if (propName === "collectionDir" || propName === "typesDir" || propName === "isPrimaryPackageOutputTarget" || propName === "generateTypeDeclarations") {
2318
+ const start = prop.getStart();
2319
+ let end = prop.getEnd();
2320
+ const beforeProp = text.slice(0, start).match(/,\s*$/);
2321
+ const afterProp = text.slice(end).match(/^\s*,/);
2322
+ if (afterProp) end = end + afterProp[0].length;
2323
+ else if (beforeProp) {
2324
+ const commaStart = start - beforeProp[0].length;
2325
+ modifications.push({
2326
+ type: "remove",
2327
+ start: commaStart,
2328
+ end
2329
+ });
2330
+ continue;
2331
+ }
2332
+ modifications.push({
2333
+ type: "remove",
2334
+ start,
2335
+ end
2336
+ });
2337
+ }
2338
+ }
2339
+ modifications.sort((a, b) => b.start - a.start);
2340
+ for (const mod of modifications) if (mod.type === "replace") text = text.slice(0, mod.start) + mod.replacement + text.slice(mod.end);
2341
+ else if (mod.type === "remove") text = text.slice(0, mod.start) + text.slice(mod.end);
2342
+ if (outputTargetsToExtract.length > 0) text = addExtractedOutputTargets(text, sourceFile, outputTargetsToExtract);
2343
+ text = text.replace(/,\s*\n\s*\n/g, ",\n");
2344
+ text = text.replace(/{\s*\n\s*\n/g, "{\n");
2345
+ text = text.replace(/,\s*,/g, ",");
2346
+ return text;
2347
+ }
2348
+ };
2349
+ /**
2350
+ * Add new output targets for extracted collectionDir and typesDir.
2351
+ * @param text The original source text
2352
+ * @param sourceFile The TypeScript source file object
2353
+ * @param toExtract An array of objects containing the output target nodes and their collectionDir/typesDir values to extract
2354
+ * @returns The modified source text with new output targets added
2355
+ */
2356
+ function addExtractedOutputTargets(text, sourceFile, toExtract) {
2357
+ let outputTargetsArray = null;
2358
+ const findOutputTargets = (node) => {
2359
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === "outputTargets" && ts.isArrayLiteralExpression(node.initializer)) outputTargetsArray = node.initializer;
2360
+ ts.forEachChild(node, findOutputTargets);
2361
+ };
2362
+ findOutputTargets(sourceFile);
2363
+ if (!outputTargetsArray || toExtract.length === 0) return text;
2364
+ const array = outputTargetsArray;
2365
+ let indent = " ";
2366
+ if (array.elements.length > 0) {
2367
+ const elemStart = array.elements[0].getStart();
2368
+ const lineStart = text.lastIndexOf("\n", elemStart) + 1;
2369
+ const leadingWhitespace = text.slice(lineStart, elemStart);
2370
+ if (/^\s+$/.test(leadingWhitespace)) indent = leadingWhitespace;
2371
+ }
2372
+ const lastElement = array.elements[array.elements.length - 1];
2373
+ if (!lastElement) return text;
2374
+ let insertPos = lastElement.getEnd();
2375
+ const afterLastElement = text.slice(insertPos).match(/^(\s*,)?/);
2376
+ if (afterLastElement && afterLastElement[1]) insertPos += afterLastElement[0].length;
2377
+ const newTargets = [];
2378
+ for (const extracted of toExtract) {
2379
+ if (extracted.collectionDir) newTargets.push(`{\n${indent} type: 'collection',\n${indent} dir: '${extracted.collectionDir}',\n${indent}}`);
2380
+ if (extracted.typesDir) newTargets.push(`{\n${indent} type: 'types',\n${indent} dir: '${extracted.typesDir}',\n${indent}}`);
2381
+ }
2382
+ if (newTargets.length === 0) return text;
2383
+ const insertion = ",\n" + newTargets.map((t) => `${indent}${t}`).join(",\n");
2384
+ text = text.slice(0, insertPos) + insertion + text.slice(insertPos);
2385
+ return text;
2386
+ }
2387
+ //#endregion
2388
+ //#region src/migrations/rules/rolldown-config.ts
2389
+ /**
2390
+ * NodeResolve fields that were valid in @rollup/plugin-node-resolve but don't exist
2391
+ * in rolldown's native resolver and should be removed.
2392
+ */
2393
+ const REMOVED_NODE_RESOLVE_FIELDS = new Set([
2394
+ "browser",
2395
+ "modulePaths",
2396
+ "dedupe",
2397
+ "jail",
2398
+ "modulesOnly",
2399
+ "preferBuiltins",
2400
+ "resolveOnly",
2401
+ "rootDir",
2402
+ "allowExportsFolderMapping"
2403
+ ]);
2404
+ /** Fields renamed between @rollup/plugin-node-resolve and rolldown's native resolver. */
2405
+ const RENAMED_NODE_RESOLVE_FIELDS = {
2406
+ exportConditions: "conditionNames",
2407
+ moduleDirectories: "modules"
2408
+ };
2409
+ function isInsideNodeResolve(node) {
2410
+ const parent = node.parent;
2411
+ if (!ts.isObjectLiteralExpression(parent)) return false;
2412
+ const grandParent = parent.parent;
2413
+ return ts.isPropertyAssignment(grandParent) && ts.isIdentifier(grandParent.name) && grandParent.name.text === "nodeResolve";
2414
+ }
2415
+ /**
2416
+ * Migration rule for rolldown-related config changes in Stencil v5.
2417
+ *
2418
+ * Handles:
2419
+ * - `rollupConfig` → `rolldownConfig` (key rename + flatten `inputOptions`)
2420
+ * - `rolldownConfig: { inputOptions: { ... } }` → `rolldownConfig: { ... }` (flatten)
2421
+ * - `rollupPlugins` → `rolldownPlugins`
2422
+ * - `nodeResolve.exportConditions` → `nodeResolve.conditionNames`
2423
+ * - `nodeResolve.moduleDirectories` → `nodeResolve.modules`
2424
+ * - Removes unsupported `nodeResolve` fields (`browser`, `dedupe`, `jail`, etc.)
2425
+ */
2426
+ const rolldownConfigRule = {
2427
+ id: "rolldown-config",
2428
+ name: "Rolldown Config Migration",
2429
+ description: "Migrate rollup/rolldown config options to v5 rolldown-native API",
2430
+ fromVersion: "4.x",
2431
+ toVersion: "5.x",
2432
+ detect(sourceFile) {
2433
+ const matches = [];
2434
+ const visit = (node) => {
2435
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name)) {
2436
+ const name = node.name.text;
2437
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
2438
+ if (name === "rollupPlugins") matches.push({
2439
+ node,
2440
+ message: `'rollupPlugins' renamed to 'rolldownPlugins'`,
2441
+ line: line + 1,
2442
+ column: character + 1
2443
+ });
2444
+ else if (name === "rollupConfig" || name === "rolldownConfig") {
2445
+ const value = node.initializer;
2446
+ if (name === "rollupConfig" || ts.isObjectLiteralExpression(value) && value.properties.some((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "inputOptions")) matches.push({
2447
+ node,
2448
+ message: name === "rollupConfig" ? `'rollupConfig' renamed to 'rolldownConfig'; 'inputOptions' wrapper removed` : `'rolldownConfig.inputOptions' wrapper removed - options are now top-level`,
2449
+ line: line + 1,
2450
+ column: character + 1
2451
+ });
2452
+ } else if (name in RENAMED_NODE_RESOLVE_FIELDS && isInsideNodeResolve(node)) matches.push({
2453
+ node,
2454
+ message: `'nodeResolve.${name}' renamed to 'nodeResolve.${RENAMED_NODE_RESOLVE_FIELDS[name]}'`,
2455
+ line: line + 1,
2456
+ column: character + 1
2457
+ });
2458
+ else if (REMOVED_NODE_RESOLVE_FIELDS.has(name) && isInsideNodeResolve(node)) matches.push({
2459
+ node,
2460
+ message: `'nodeResolve.${name}' is not supported by rolldown's native resolver and will be removed`,
2461
+ line: line + 1,
2462
+ column: character + 1
2463
+ });
2464
+ }
2465
+ ts.forEachChild(node, visit);
2466
+ };
2467
+ visit(sourceFile);
2468
+ return matches;
2469
+ },
2470
+ transform(sourceFile, matches) {
2471
+ if (matches.length === 0) return sourceFile.getFullText();
2472
+ const edits = [];
2473
+ const fullText = sourceFile.getFullText();
2474
+ for (const match of matches) {
2475
+ const node = match.node;
2476
+ const name = node.name.text;
2477
+ if (name === "rollupPlugins") {
2478
+ const nameStart = node.name.getStart(sourceFile);
2479
+ const nameEnd = node.name.getEnd();
2480
+ edits.push({
2481
+ start: nameStart,
2482
+ end: nameEnd,
2483
+ replacement: "rolldownPlugins"
2484
+ });
2485
+ continue;
2486
+ }
2487
+ if (name in RENAMED_NODE_RESOLVE_FIELDS && isInsideNodeResolve(node)) {
2488
+ const nameStart = node.name.getStart(sourceFile);
2489
+ const nameEnd = node.name.getEnd();
2490
+ edits.push({
2491
+ start: nameStart,
2492
+ end: nameEnd,
2493
+ replacement: RENAMED_NODE_RESOLVE_FIELDS[name]
2494
+ });
2495
+ continue;
2496
+ }
2497
+ if (REMOVED_NODE_RESOLVE_FIELDS.has(name) && isInsideNodeResolve(node)) {
2498
+ const start = node.getFullStart();
2499
+ const end = node.getEnd();
2500
+ const trailingComma = fullText.slice(end).match(/^\s*,/);
2501
+ edits.push({
2502
+ start,
2503
+ end: trailingComma ? end + trailingComma[0].length : end,
2504
+ replacement: ""
2505
+ });
2506
+ continue;
2507
+ }
2508
+ if (name === "rollupConfig" || name === "rolldownConfig") {
2509
+ const value = node.initializer;
2510
+ if (!ts.isObjectLiteralExpression(value)) {
2511
+ if (name === "rollupConfig") {
2512
+ const nameStart = node.name.getStart(sourceFile);
2513
+ edits.push({
2514
+ start: nameStart,
2515
+ end: node.name.getEnd(),
2516
+ replacement: "rolldownConfig"
2517
+ });
2518
+ }
2519
+ continue;
2520
+ }
2521
+ const inputOptionsProp = value.properties.find((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "inputOptions");
2522
+ if (!inputOptionsProp) {
2523
+ if (name === "rollupConfig") {
2524
+ const nameStart = node.name.getStart(sourceFile);
2525
+ edits.push({
2526
+ start: nameStart,
2527
+ end: node.name.getEnd(),
2528
+ replacement: "rolldownConfig"
2529
+ });
2530
+ }
2531
+ continue;
2532
+ }
2533
+ const newValueText = inputOptionsProp.initializer.getText(sourceFile);
2534
+ const keyStart = node.name.getStart(sourceFile);
2535
+ edits.push({
2536
+ start: keyStart,
2537
+ end: node.getEnd(),
2538
+ replacement: `rolldownConfig: ${newValueText}`
2539
+ });
2540
+ }
2541
+ }
2542
+ edits.sort((a, b) => b.start - a.start);
2543
+ let text = fullText;
2544
+ for (const edit of edits) text = text.slice(0, edit.start) + edit.replacement + text.slice(edit.end);
2545
+ return text;
2546
+ }
2547
+ };
2548
+ //#endregion
2549
+ //#region src/migrations/rules/service-worker-default.ts
2550
+ /**
2551
+ * Migration rule for `serviceWorker: null` / `serviceWorker: false` on `www` output targets.
2552
+ *
2553
+ * In Stencil v5, `serviceWorker` defaults to `null` (disabled). Explicit `null` or `false`
2554
+ * values on `www` output targets are now redundant and can be removed.
2555
+ */
2556
+ const serviceWorkerDefaultRule = {
2557
+ id: "service-worker-default",
2558
+ name: "Service Worker Default Cleanup",
2559
+ description: "Remove redundant 'serviceWorker: null' / 'serviceWorker: false' from www output targets - null is now the default",
2560
+ fromVersion: "4.x",
2561
+ toVersion: "5.x",
2562
+ detect(sourceFile) {
2563
+ const matches = [];
2564
+ const visit = (node) => {
2565
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === "serviceWorker") {
2566
+ const init = node.initializer;
2567
+ if (init.kind === ts.SyntaxKind.NullKeyword || init.kind === ts.SyntaxKind.FalseKeyword) {
2568
+ const parent = node.parent;
2569
+ if (ts.isObjectLiteralExpression(parent)) {
2570
+ if (parent.properties.some((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "type" && ts.isStringLiteral(p.initializer) && p.initializer.text === "www")) {
2571
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
2572
+ matches.push({
2573
+ node,
2574
+ message: `'serviceWorker: ${init.kind === ts.SyntaxKind.NullKeyword ? "null" : "false"}' is now the default on www output targets and can be removed`,
2575
+ line: line + 1,
2576
+ column: character + 1
2577
+ });
2578
+ }
2579
+ }
2580
+ }
2581
+ }
2582
+ ts.forEachChild(node, visit);
2583
+ };
2584
+ visit(sourceFile);
2585
+ return matches;
2586
+ },
2587
+ transform(sourceFile, matches) {
2588
+ if (matches.length === 0) return sourceFile.getFullText();
2589
+ let text = sourceFile.getFullText();
2590
+ for (const match of [...matches].reverse()) {
2591
+ const node = match.node;
2592
+ let start = node.getFullStart();
2593
+ const end = node.getEnd();
2594
+ let removeEnd = end;
2595
+ const trailingComma = text.slice(end).match(/^\s*,/);
2596
+ if (trailingComma) removeEnd = end + trailingComma[0].length;
2597
+ else {
2598
+ const leadingComma = text.slice(0, start).match(/,\s*$/);
2599
+ if (leadingComma) start -= leadingComma[0].length;
2600
+ }
2601
+ text = text.slice(0, start) + text.slice(removeEnd);
2602
+ }
2603
+ return text;
2604
+ }
2605
+ };
2606
+ //#endregion
2607
+ //#region src/migrations/index.ts
2608
+ /**
2609
+ * Build a map of local import names to their original names from @stencil/core.
2610
+ * Handles aliased imports like `import { Component as Cmp } from '@stencil/core'`.
2611
+ * Also handles multiple imports from @stencil/core (e.g., separate type and value imports).
648
2612
  *
649
- * @param coreCompiler the compiler instance being used for this invocation of Stencil
650
- * @param config a validated configuration object to be used for this run of Stencil
2613
+ * @param sourceFile The TypeScript source file to analyze
2614
+ * @returns Map where keys are local names and values are original imported names
651
2615
  */
652
- const startupCompilerLog = (coreCompiler, config) => {
653
- if (config.suppressLogs === true) return;
654
- const { logger } = config;
655
- const isDebug = logger.getLevel() === "debug";
656
- const isPrerelease = coreCompiler.version.includes("-");
657
- const isDevBuild = coreCompiler.version.includes("-dev.");
658
- if (isPrerelease && !isDevBuild) logger.warn(logger.yellow(`This is a prerelease build, undocumented changes might happen at any time. Technical support is not available for prereleases, but any assistance testing is appreciated.`));
659
- if (config.devMode && !isDebug) {
660
- if (config.buildEs5) logger.warn(`Generating ES5 during development is a very task expensive, initial and incremental builds will be much slower. Drop the '--es5' flag and use a modern browser for development.`);
661
- if (!config.enableCache) logger.warn(`Disabling cache during development will slow down incremental builds.`);
2616
+ const getStencilCoreImportMap = (sourceFile) => {
2617
+ const importMap = /* @__PURE__ */ new Map();
2618
+ for (const statement of sourceFile.statements) if (ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier) && statement.moduleSpecifier.text === "@stencil/core") {
2619
+ const namedBindings = statement.importClause?.namedBindings;
2620
+ if (namedBindings && ts.isNamedImports(namedBindings)) for (const element of namedBindings.elements) {
2621
+ const localName = element.name.text;
2622
+ const originalName = element.propertyName?.text ?? element.name.text;
2623
+ importMap.set(localName, originalName);
2624
+ }
662
2625
  }
2626
+ return importMap;
663
2627
  };
664
- //#endregion
665
- //#region src/merge-flags.ts
666
2628
  /**
667
- * Merge CLI flags into a Stencil configuration object.
668
- *
669
- * This function applies command-line flags to the config, with CLI flags
670
- * taking precedence over config file values. This is the canonical place
671
- * where flag values are translated into config properties.?
2629
+ * Check if a decorator identifier refers to a specific @stencil/core export.
2630
+ * Handles aliased imports like `import { Component as Cmp } from '@stencil/core'`.
672
2631
  *
673
- * @param config The config object (from stencil.config.ts or empty)
674
- * @param flags The parsed CLI flags
675
- * @returns The config with flags merged in
2632
+ * @param decoratorName The identifier used in the decorator
2633
+ * @param expectedOriginalName The original export name (e.g., 'Component')
2634
+ * @param importMap The import map from getStencilCoreImportMap
2635
+ * @returns True if the decorator refers to the expected export
676
2636
  */
677
- const mergeFlags = (config, flags) => {
678
- const merged = { ...config };
679
- if (flags.prod === true) merged.devMode = false;
680
- else if (flags.dev === true) merged.devMode = true;
681
- if (flags.debug === true || flags.verbose === true) merged.logLevel = "debug";
682
- else if (flags.logLevel) merged.logLevel = flags.logLevel;
683
- if (typeof flags.watch === "boolean") merged.watch = flags.watch;
684
- if (typeof flags.docs === "boolean") merged.buildDocs = flags.docs;
685
- if (typeof flags.esm === "boolean") merged.buildDist = flags.esm;
686
- if (typeof flags.profile === "boolean") merged.profile = flags.profile;
687
- if (typeof flags.log === "boolean") merged.writeLog = flags.log;
688
- if (typeof flags.cache === "boolean") merged.enableCache = flags.cache;
689
- if (typeof flags.ci === "boolean") merged.ci = flags.ci;
690
- if (typeof flags.ssr === "boolean") merged.ssr = flags.ssr;
691
- if (typeof flags.prerender === "boolean") merged.prerender = flags.prerender;
692
- if (typeof flags.docsJson === "string") merged.docsJsonPath = flags.docsJson;
693
- if (flags.stats) merged.statsJsonPath = flags.stats;
694
- if (typeof flags.serviceWorker === "boolean") merged.generateServiceWorker = flags.serviceWorker;
695
- if (typeof flags.e2e === "boolean") merged.e2eTests = flags.e2e;
696
- if (typeof flags.maxWorkers === "number") merged.maxConcurrentWorkers = flags.maxWorkers;
697
- if (typeof flags.address === "string") merged.devServerAddress = flags.address;
698
- if (typeof flags.port === "number") merged.devServerPort = flags.port;
699
- if (typeof flags.open === "boolean") merged.devServerOpen = flags.open;
700
- return merged;
2637
+ const isStencilDecorator = (decoratorName, expectedOriginalName, importMap) => {
2638
+ return importMap.get(decoratorName) === expectedOriginalName;
701
2639
  };
702
- //#endregion
703
- //#region src/check-version.ts
704
2640
  /**
705
- * Retrieve a reference to the active `CompilerSystem`'s `checkVersion` function
706
- * @param config the Stencil configuration associated with the currently compiled project
707
- * @param currentVersion the Stencil compiler's version string
708
- * @param flags the CLI flags (owned by CLI, not part of core config)
709
- * @returns a reference to `checkVersion`, or `null` if one does not exist on the current `CompilerSystem`
2641
+ * Registry of all available migration rules.
2642
+ * Rules are applied in order, so add new rules at the end.
710
2643
  */
711
- const startCheckVersion = async (config, currentVersion, flags) => {
712
- if (config.devMode && !flags.ci && !currentVersion.includes("-dev.") && isFunction(config.sys.checkVersion)) return config.sys.checkVersion(config.logger, currentVersion);
713
- return null;
2644
+ const migrationRules = [
2645
+ encapsulationApiRule,
2646
+ formAssociatedRule,
2647
+ buildDistDocsRule,
2648
+ outputTargetRenamesRule,
2649
+ devModeRule,
2650
+ globalStyleInjectRule,
2651
+ lightDomPatchesRule,
2652
+ extrasToCompatRule,
2653
+ externalRuntimeRule,
2654
+ hashFileNamesRule,
2655
+ rolldownConfigRule,
2656
+ serviceWorkerDefaultRule
2657
+ ];
2658
+ /**
2659
+ * Get all migration rules for a specific version upgrade.
2660
+ * @param fromVersion Source version (e.g., '4')
2661
+ * @param toVersion Target version (e.g., '5')
2662
+ * @returns Filtered list of applicable rules
2663
+ */
2664
+ const getRulesForVersionUpgrade = (fromVersion, toVersion) => {
2665
+ return migrationRules.filter((rule) => rule.fromVersion.startsWith(fromVersion) && rule.toVersion.startsWith(toVersion));
714
2666
  };
2667
+ //#endregion
2668
+ //#region src/task-migrate.ts
715
2669
  /**
716
- * Print the results of running the provided `versionChecker`.
2670
+ * Run the migration task to update Stencil components from v4 to v5 API.
717
2671
  *
718
- * Does not print if no `versionChecker` is provided.
2672
+ * @param coreCompiler the Stencil compiler instance
2673
+ * @param config the validated Stencil config
2674
+ * @param flags CLI flags (includes dryRun option)
2675
+ */
2676
+ const taskMigrate = async (coreCompiler, config, flags) => {
2677
+ const logger = config.logger;
2678
+ const sys = config.sys;
2679
+ const dryRun = flags.dryRun ?? false;
2680
+ const currentMajor = coreCompiler.version.split(".")[0];
2681
+ const fromVersion = String(Number(currentMajor) - 1);
2682
+ const toVersion = currentMajor;
2683
+ const rules = getRulesForVersionUpgrade(fromVersion, toVersion);
2684
+ if (rules.length === 0) {
2685
+ logger.info(`No migration rules found for ${fromVersion}.x → ${toVersion}.x upgrade.`);
2686
+ return;
2687
+ }
2688
+ logger.info(`${logger.emoji("🔄 ")}Stencil Migration Tool (v${fromVersion} → v${toVersion})`);
2689
+ logger.info(`Scanning for components that need migration...`);
2690
+ if (dryRun) logger.info(logger.cyan("Dry run mode - no files will be modified"));
2691
+ const tsFiles = await getTypeScriptFiles(config, sys, logger);
2692
+ if (tsFiles.length === 0) {
2693
+ logger.info(`No TypeScript files found. Check your tsconfig.json configuration.`);
2694
+ return;
2695
+ }
2696
+ logger.info(`Found ${tsFiles.length} TypeScript files to scan`);
2697
+ const results = [];
2698
+ for (const filePath of tsFiles) {
2699
+ let content = await sys.readFile(filePath);
2700
+ if (!content) continue;
2701
+ for (const rule of rules) {
2702
+ const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);
2703
+ const matches = rule.detect(sourceFile);
2704
+ if (matches.length > 0) {
2705
+ const relPath = relative$1(config.rootDir, filePath);
2706
+ logger.info(`\n${logger.cyan(relPath)}`);
2707
+ logger.info(` ${logger.yellow(`[${rule.id}]`)} ${rule.name}`);
2708
+ for (const match of matches) logger.info(` Line ${match.line}: ${match.message}`);
2709
+ if (!dryRun) {
2710
+ const transformed = rule.transform(sourceFile, matches);
2711
+ await sys.writeFile(filePath, transformed);
2712
+ content = transformed;
2713
+ results.push({
2714
+ filePath,
2715
+ rule,
2716
+ matches,
2717
+ transformed: true
2718
+ });
2719
+ logger.info(` ${logger.green("✓")} Migrated`);
2720
+ } else results.push({
2721
+ filePath,
2722
+ rule,
2723
+ matches,
2724
+ transformed: false
2725
+ });
2726
+ }
2727
+ }
2728
+ }
2729
+ logger.info("\n" + logger.bold("Migration Summary"));
2730
+ logger.info("─".repeat(40));
2731
+ const totalMatches = results.reduce((sum, r) => sum + r.matches.length, 0);
2732
+ const filesAffected = new Set(results.map((r) => r.filePath)).size;
2733
+ if (totalMatches === 0) logger.info(logger.green("No migrations needed - your code is up to date!"));
2734
+ else {
2735
+ logger.info(`Found ${totalMatches} item(s) to migrate in ${filesAffected} file(s)`);
2736
+ if (dryRun) logger.info(logger.yellow("\nRun without --dry-run to apply the migrations"));
2737
+ else logger.info(logger.green(`\n✓ Successfully migrated ${totalMatches} item(s)`));
2738
+ }
2739
+ const byRule = /* @__PURE__ */ new Map();
2740
+ for (const result of results) {
2741
+ const existing = byRule.get(result.rule.id) || [];
2742
+ existing.push(result);
2743
+ byRule.set(result.rule.id, existing);
2744
+ }
2745
+ if (byRule.size > 0) {
2746
+ logger.info("\nBy migration rule:");
2747
+ for (const [ruleId, ruleResults] of byRule) {
2748
+ const rule = rules.find((r) => r.id === ruleId);
2749
+ const count = ruleResults.reduce((sum, r) => sum + r.matches.length, 0);
2750
+ logger.info(` ${rule?.name || ruleId}: ${count} item(s)`);
2751
+ }
2752
+ }
2753
+ };
2754
+ /**
2755
+ * Detect available migrations without applying them.
2756
+ * Used by the build task to check if migrations might help fix build errors.
719
2757
  *
720
- * @param versionChecker the function to invoke.
2758
+ * @param coreCompiler the Stencil compiler instance
2759
+ * @param config the validated Stencil config
2760
+ * @returns detection result with migration information
721
2761
  */
722
- const printCheckVersionResults = async (versionChecker) => {
723
- if (versionChecker) {
724
- const checkVersionResults = await versionChecker;
725
- if (isFunction(checkVersionResults)) checkVersionResults();
2762
+ const detectMigrations = async (coreCompiler, config) => {
2763
+ const sys = config.sys;
2764
+ const logger = config.logger;
2765
+ const currentMajor = coreCompiler.version.split(".")[0];
2766
+ const rules = getRulesForVersionUpgrade(String(Number(currentMajor) - 1), currentMajor);
2767
+ if (rules.length === 0) return {
2768
+ hasMigrations: false,
2769
+ totalMatches: 0,
2770
+ filesAffected: 0,
2771
+ migrations: [],
2772
+ rules: []
2773
+ };
2774
+ const tsFiles = await getTypeScriptFiles(config, sys, logger);
2775
+ if (tsFiles.length === 0) return {
2776
+ hasMigrations: false,
2777
+ totalMatches: 0,
2778
+ filesAffected: 0,
2779
+ migrations: [],
2780
+ rules
2781
+ };
2782
+ const migrations = [];
2783
+ for (const filePath of tsFiles) {
2784
+ const content = await sys.readFile(filePath);
2785
+ if (!content) continue;
2786
+ for (const rule of rules) {
2787
+ const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);
2788
+ const matches = rule.detect(sourceFile);
2789
+ if (matches.length > 0) migrations.push({
2790
+ filePath,
2791
+ rule,
2792
+ matches
2793
+ });
2794
+ }
726
2795
  }
2796
+ const totalMatches = migrations.reduce((sum, m) => sum + m.matches.length, 0);
2797
+ const filesAffected = new Set(migrations.map((m) => m.filePath)).size;
2798
+ return {
2799
+ hasMigrations: migrations.length > 0,
2800
+ totalMatches,
2801
+ filesAffected,
2802
+ migrations,
2803
+ rules
2804
+ };
727
2805
  };
2806
+ /**
2807
+ * Get TypeScript files using the project's tsconfig.json.
2808
+ * Uses the same approach as the Stencil compiler.
2809
+ *
2810
+ * @param config the validated Stencil config
2811
+ * @param sys the compiler system for file operations
2812
+ * @param logger the logger for output
2813
+ * @returns array of absolute paths to TypeScript files
2814
+ */
2815
+ async function getTypeScriptFiles(config, sys, logger) {
2816
+ let tsconfigPath;
2817
+ if (config.tsconfig) tsconfigPath = isAbsolute(config.tsconfig) ? config.tsconfig : join$1(config.rootDir, config.tsconfig);
2818
+ else tsconfigPath = join$1(config.rootDir, "tsconfig.json");
2819
+ logger.debug(`Using tsconfig: ${tsconfigPath}`);
2820
+ const tsconfigContent = await sys.readFile(tsconfigPath);
2821
+ if (!tsconfigContent) {
2822
+ logger.error(`tsconfig not found: ${tsconfigPath}`);
2823
+ return [];
2824
+ }
2825
+ const host = {
2826
+ ...ts.sys,
2827
+ readFile: (p) => {
2828
+ if (p === tsconfigPath) return tsconfigContent;
2829
+ return ts.sys.readFile(p);
2830
+ },
2831
+ onUnRecoverableConfigFileDiagnostic: (diagnostic) => {
2832
+ logger.error(ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"));
2833
+ }
2834
+ };
2835
+ const results = ts.getParsedCommandLineOfConfigFile(tsconfigPath, {}, host);
2836
+ if (!results) {
2837
+ logger.error(`Failed to parse tsconfig: ${tsconfigPath}`);
2838
+ return [];
2839
+ }
2840
+ if (results.errors && results.errors.length > 0) for (const err of results.errors) logger.warn(ts.flattenDiagnosticMessageText(err.messageText, "\n"));
2841
+ const files = results.fileNames.filter((f) => (f.endsWith(".ts") || f.endsWith(".tsx")) && !f.endsWith(".d.ts"));
2842
+ const configFile = config.configPath;
2843
+ if (configFile && (configFile.endsWith(".ts") || configFile.endsWith(".mts"))) {
2844
+ if (!files.includes(configFile)) files.push(configFile);
2845
+ const configContent = await sys.readFile(configFile);
2846
+ if (configContent) {
2847
+ const configSourceFile = ts.createSourceFile(configFile, configContent, ts.ScriptTarget.Latest, true);
2848
+ const configDir = dirname$1(configFile);
2849
+ for (const statement of configSourceFile.statements) if (ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier)) {
2850
+ const specifier = statement.moduleSpecifier.text;
2851
+ if (!specifier.startsWith("./") && !specifier.startsWith("../")) continue;
2852
+ const basePath = join$1(configDir, specifier);
2853
+ const candidates = basePath.endsWith(".ts") || basePath.endsWith(".tsx") ? [basePath] : [`${basePath}.ts`, `${basePath}.tsx`];
2854
+ for (const candidate of candidates) if (!candidate.endsWith(".d.ts") && !files.includes(candidate) && candidate.startsWith(config.rootDir)) {
2855
+ if (await sys.readFile(candidate)) {
2856
+ files.push(candidate);
2857
+ break;
2858
+ }
2859
+ }
2860
+ }
2861
+ }
2862
+ }
2863
+ return files;
2864
+ }
728
2865
  //#endregion
729
2866
  //#region src/task-prerender.ts
730
2867
  const taskPrerender = async (coreCompiler, config, flags) => {
731
2868
  startupCompilerLog(coreCompiler, config);
732
- const hydrateAppFilePath = flags.unknownArgs[0];
733
- if (typeof hydrateAppFilePath !== "string") {
2869
+ const ssrAppFilePath = flags.unknownArgs[0];
2870
+ if (typeof ssrAppFilePath !== "string") {
734
2871
  config.logger.error(`Missing hydrate app script path`);
735
2872
  return config.sys.exit(1);
736
2873
  }
737
2874
  const srcIndexHtmlPath = config.srcIndexHtml;
738
- const diagnostics = await runPrerenderTask(coreCompiler, config, hydrateAppFilePath, void 0, srcIndexHtmlPath);
2875
+ const diagnostics = await runPrerenderTask(coreCompiler, config, ssrAppFilePath, void 0, srcIndexHtmlPath);
739
2876
  config.logger.printDiagnostics(diagnostics);
740
2877
  if (diagnostics.some((d) => d.level === "error")) return config.sys.exit(1);
741
2878
  };
742
- const runPrerenderTask = async (coreCompiler, config, hydrateAppFilePath, componentGraph, srcIndexHtmlPath) => {
2879
+ const runPrerenderTask = async (coreCompiler, config, ssrAppFilePath, componentGraph, srcIndexHtmlPath) => {
743
2880
  const diagnostics = [];
744
2881
  try {
745
2882
  const results = await (await coreCompiler.createPrerenderer(config)).start({
746
- hydrateAppFilePath,
2883
+ ssrAppFilePath,
747
2884
  componentGraph,
748
2885
  srcIndexHtmlPath
749
2886
  });
@@ -848,8 +2985,8 @@ function hasVerbose(flags) {
848
2985
  }
849
2986
  //#endregion
850
2987
  //#region src/ionic-config.ts
851
- const isTest$1 = () => process.env.JEST_WORKER_ID !== void 0;
852
- const defaultConfig = (sys) => sys.resolvePath(`${sys.homeDir()}/.ionic/${isTest$1() ? "tmp-config.json" : "config.json"}`);
2988
+ const isTest = () => process.env.JEST_WORKER_ID !== void 0;
2989
+ const defaultConfig = (sys) => sys.resolvePath(`${sys.homeDir()}/.ionic/${isTest() ? "tmp-config.json" : "config.json"}`);
853
2990
  const defaultConfigDirectory = (sys) => sys.resolvePath(`${sys.homeDir()}/.ionic`);
854
2991
  /**
855
2992
  * Reads an Ionic configuration file from disk, parses it, and performs any necessary corrections to it if certain
@@ -1000,9 +3137,9 @@ function getActiveTargets(config) {
1000
3137
  * @returns a Promise wrapping data for the telemetry endpoint
1001
3138
  */
1002
3139
  const prepareData = async (coreCompiler, config, sys, flags, duration_ms, component_count = void 0) => {
1003
- const { typescript, rollup } = coreCompiler.versions || {
3140
+ const { typescript, rolldown } = coreCompiler.versions || {
1004
3141
  typescript: "unknown",
1005
- rollup: "unknown"
3142
+ rolldown: "unknown"
1006
3143
  };
1007
3144
  const { packages, packagesNoVersions } = await getInstalledPackages(sys, flags);
1008
3145
  const targets = getActiveTargets(config);
@@ -1027,7 +3164,7 @@ const prepareData = async (coreCompiler, config, sys, flags, duration_ms, compon
1027
3164
  os_version,
1028
3165
  packages,
1029
3166
  packages_no_versions: packagesNoVersions,
1030
- rollup,
3167
+ rolldown,
1031
3168
  stencil,
1032
3169
  system,
1033
3170
  system_major: getMajorVersion(system),
@@ -1051,13 +3188,11 @@ const CONFIG_PROPS_TO_ANONYMIZE = [
1051
3188
  "tsconfig"
1052
3189
  ];
1053
3190
  const CONFIG_PROPS_TO_DELETE = [
1054
- "commonjs",
1055
3191
  "devServer",
1056
3192
  "env",
1057
3193
  "logger",
1058
- "rollupConfig",
3194
+ "rolldownConfig",
1059
3195
  "sys",
1060
- "testing",
1061
3196
  "tsCompilerOptions"
1062
3197
  ];
1063
3198
  /**
@@ -1077,7 +3212,7 @@ const anonymizeConfigForTelemetry = (config) => {
1077
3212
  if (OUTPUT_TARGET_KEYS_TO_KEEP.includes(key)) return value;
1078
3213
  return "omitted";
1079
3214
  }));
1080
- if (isOutputTargetHydrate(target) && target.external) anonymizedOT["external"] = target.external.concat();
3215
+ if (isOutputTargetSsr(target) && target.external) anonymizedOT["external"] = target.external.concat();
1081
3216
  return anonymizedOT;
1082
3217
  });
1083
3218
  for (const prop of CONFIG_PROPS_TO_DELETE) delete anonymizedConfig[prop];
@@ -1271,14 +3406,59 @@ const taskBuild = async (coreCompiler, config, flags) => {
1271
3406
  let exitCode = 0;
1272
3407
  try {
1273
3408
  startupCompilerLog(coreCompiler, config);
3409
+ const preBuildMigrationResult = await detectMigrations(coreCompiler, config);
3410
+ if (preBuildMigrationResult.hasMigrations) {
3411
+ const action = await promptForMigration(config, preBuildMigrationResult, "pre-build");
3412
+ if (action === "run") {
3413
+ await taskMigrate(coreCompiler, config, {
3414
+ ...flags,
3415
+ dryRun: false
3416
+ });
3417
+ config.logger.info("\nMigrations applied. Starting build...\n");
3418
+ } else if (action === "dry-run") {
3419
+ await taskMigrate(coreCompiler, config, {
3420
+ ...flags,
3421
+ dryRun: true
3422
+ });
3423
+ return config.sys.exit(1);
3424
+ } else return config.sys.exit(1);
3425
+ }
1274
3426
  const versionChecker = startCheckVersion(config, coreCompiler.version, flags);
1275
3427
  const compiler = await coreCompiler.createCompiler(config);
1276
3428
  const results = await compiler.build();
1277
3429
  await telemetryBuildFinishedAction(config.sys, config, coreCompiler, results, flags);
1278
3430
  await compiler.destroy();
1279
- if (results.hasError) exitCode = 1;
1280
- else if (flags.prerender) {
1281
- const prerenderDiagnostics = await runPrerenderTask(coreCompiler, config, results.hydrateAppFilePath, results.componentGraph, void 0);
3431
+ if (results.hasError) {
3432
+ const migrationResult = await detectMigrations(coreCompiler, config);
3433
+ if (migrationResult.hasMigrations) {
3434
+ const action = await promptForMigration(config, migrationResult, "post-error");
3435
+ if (action === "run") {
3436
+ await taskMigrate(coreCompiler, config, {
3437
+ ...flags,
3438
+ dryRun: false
3439
+ });
3440
+ config.logger.info("\nRe-running build after migrations...\n");
3441
+ const newCompiler = await coreCompiler.createCompiler(config);
3442
+ const newResults = await newCompiler.build();
3443
+ await newCompiler.destroy();
3444
+ if (!newResults.hasError) {
3445
+ exitCode = 0;
3446
+ if (flags.prerender) {
3447
+ const prerenderDiagnostics = await runPrerenderTask(coreCompiler, config, newResults.ssrAppFilePath, newResults.componentGraph, void 0);
3448
+ config.logger.printDiagnostics(prerenderDiagnostics);
3449
+ if (prerenderDiagnostics.some((d) => d.level === "error")) exitCode = 1;
3450
+ }
3451
+ } else exitCode = 1;
3452
+ } else if (action === "dry-run") {
3453
+ await taskMigrate(coreCompiler, config, {
3454
+ ...flags,
3455
+ dryRun: true
3456
+ });
3457
+ exitCode = 1;
3458
+ } else exitCode = 1;
3459
+ } else exitCode = 1;
3460
+ } else if (flags.prerender) {
3461
+ const prerenderDiagnostics = await runPrerenderTask(coreCompiler, config, results.ssrAppFilePath, results.componentGraph, void 0);
1282
3462
  config.logger.printDiagnostics(prerenderDiagnostics);
1283
3463
  if (prerenderDiagnostics.some((d) => d.level === "error")) exitCode = 1;
1284
3464
  }
@@ -1289,6 +3469,50 @@ const taskBuild = async (coreCompiler, config, flags) => {
1289
3469
  }
1290
3470
  if (exitCode > 0) return config.sys.exit(exitCode);
1291
3471
  };
3472
+ /**
3473
+ * Prompt the user about available migrations.
3474
+ * Shows what migrations are available and lets them choose to run them.
3475
+ * @param config the Stencil config
3476
+ * @param migrationResult the result of migration detection with available migrations
3477
+ * @param context whether this is a pre-build check or post-error check
3478
+ * @returns the user's chosen action for handling migrations
3479
+ */
3480
+ async function promptForMigration(config, migrationResult, context) {
3481
+ const logger = config.logger;
3482
+ logger.info("");
3483
+ logger.info(logger.bold(logger.yellow("Migrations Required")));
3484
+ logger.info("─".repeat(40));
3485
+ logger.info(`Found ${migrationResult.totalMatches} item(s) in ${migrationResult.filesAffected} file(s) that need to be migrated for Stencil v5.`);
3486
+ for (const migration of migrationResult.migrations) {
3487
+ const relPath = relative$1(config.rootDir, migration.filePath);
3488
+ logger.info(` ${logger.cyan(relPath)}: ${migration.matches.length} item(s)`);
3489
+ }
3490
+ logger.info("");
3491
+ if (context === "pre-build") logger.info("Your config contains deprecated options that must be migrated before building.");
3492
+ else logger.info("These migrations may help resolve the build errors above.");
3493
+ const action = await select({
3494
+ message: "What would you like to do?",
3495
+ options: [
3496
+ {
3497
+ value: "run",
3498
+ label: "Run migration",
3499
+ hint: "Apply migrations and re-run build"
3500
+ },
3501
+ {
3502
+ value: "dry-run",
3503
+ label: "Dry run",
3504
+ hint: "Preview changes without modifying files"
3505
+ },
3506
+ {
3507
+ value: "exit",
3508
+ label: "Exit",
3509
+ hint: "Exit without making changes"
3510
+ }
3511
+ ]
3512
+ });
3513
+ if (isCancel(action)) return "exit";
3514
+ return action;
3515
+ }
1292
3516
  //#endregion
1293
3517
  //#region src/task-docs.ts
1294
3518
  const taskDocs = async (coreCompiler, config) => {
@@ -1302,276 +3526,109 @@ const taskDocs = async (coreCompiler, config) => {
1302
3526
  };
1303
3527
  //#endregion
1304
3528
  //#region src/task-generate.ts
1305
- /**
1306
- * Task to generate component boilerplate and write it to disk. This task can
1307
- * cause the program to exit with an error under various circumstances, such as
1308
- * being called in an inappropriate place, being asked to overwrite files that
1309
- * already exist, etc.
1310
- *
1311
- * @param config the user-supplied config, which we need here to access `.sys`.
1312
- * @param flags the CLI flags (owned by CLI, not part of core config)
1313
- * @returns a void promise
1314
- */
3529
+ async function resolveFileTemplates(contrib, ctx) {
3530
+ const { fileTemplates } = contrib;
3531
+ if (!fileTemplates) return [];
3532
+ return typeof fileTemplates === "function" ? fileTemplates(ctx) : fileTemplates;
3533
+ }
1315
3534
  const taskGenerate = async (config, flags) => {
1316
- if (!config.configPath) {
1317
- config.logger.error("Please run this command in your root directory (i. e. the one containing stencil.config.ts).");
3535
+ const srcDir = config.srcDir;
3536
+ if (!srcDir || !existsSync(srcDir)) {
3537
+ config.logger.error("Please run this command in your project root directory.");
1318
3538
  return config.sys.exit(1);
1319
3539
  }
1320
- const absoluteSrcDir = config.srcDir;
1321
- if (!absoluteSrcDir) {
1322
- config.logger.error(`Stencil's srcDir was not specified.`);
1323
- return config.sys.exit(1);
3540
+ const generateContribs = (await discoverPlugins(config.rootDir)).flatMap((d) => d.plugin.generate ? [d.plugin.generate] : []);
3541
+ p.intro("stencil generate");
3542
+ const rawInput = flags.unknownArgs.find((arg) => !arg.startsWith("-"));
3543
+ let input;
3544
+ if (rawInput) input = rawInput;
3545
+ else {
3546
+ const tagName = await p.text({
3547
+ message: "Component tag name (dash-case):",
3548
+ validate: (value) => validateComponentTag(value ?? "")
3549
+ });
3550
+ cancelIfAborted(tagName);
3551
+ input = tagName;
1324
3552
  }
1325
- const { prompt } = await import("prompts");
1326
- const input = flags.unknownArgs.find((arg) => !arg.startsWith("-")) || (await prompt({
1327
- name: "tagName",
1328
- type: "text",
1329
- message: "Component tag name (dash-case):"
1330
- })).tagName;
1331
- if (void 0 === input) return;
1332
3553
  const { dir, base: componentName } = parse(input);
1333
3554
  const tagError = validateComponentTag(componentName);
1334
3555
  if (tagError) {
1335
3556
  config.logger.error(tagError);
1336
3557
  return config.sys.exit(1);
1337
3558
  }
1338
- let cssExtension = "css";
1339
- if (config.plugins?.find((plugin) => plugin.name === "sass")) cssExtension = await chooseSassExtension();
1340
- else if (config.plugins?.find((plugin) => plugin.name === "less")) cssExtension = "less";
1341
- const filesToGenerateExt = await chooseFilesToGenerate(cssExtension);
1342
- if (!filesToGenerateExt) return;
1343
- const extensionsToGenerate = ["tsx", ...filesToGenerateExt];
1344
- const testFolder = extensionsToGenerate.some(isTest) ? "test" : "";
1345
- const outDir = join(absoluteSrcDir, "components", dir, componentName);
1346
- await config.sys.createDir(normalizePath(join(outDir, testFolder)), { recursive: true });
1347
- const filesToGenerate = extensionsToGenerate.map((extension) => ({
1348
- extension,
1349
- path: getFilepathForFile(outDir, componentName, extension)
1350
- }));
1351
- await checkForOverwrite(filesToGenerate, config);
1352
- 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));
1353
- if (!writtenFiles) return config.sys.exit(1);
1354
- console.log();
1355
- console.log(`${config.logger.gray("$")} stencil generate ${input}`);
1356
- console.log();
1357
- console.log(config.logger.bold("The following files have been generated:"));
1358
- const absoluteRootDir = config.rootDir;
1359
- writtenFiles.map((file) => console.log(` - ${relative(absoluteRootDir, file)}`));
1360
- };
1361
- /**
1362
- * Show a checkbox prompt to select the files to be generated.
1363
- *
1364
- * @param cssExtension the extension of the CSS file to be generated
1365
- * @returns a read-only array of `GeneratableExtension`, the extensions that the user has decided
1366
- * to generate
1367
- */
1368
- const chooseFilesToGenerate = async (cssExtension) => {
1369
- const { prompt } = await import("prompts");
1370
- return (await prompt({
1371
- name: "filesToGenerate",
1372
- type: "multiselect",
1373
- message: "Which additional files do you want to generate?",
1374
- choices: [
1375
- {
1376
- value: cssExtension,
1377
- title: `Stylesheet (.${cssExtension})`,
1378
- selected: true
1379
- },
1380
- {
1381
- value: "spec.tsx",
1382
- title: "Spec Test (.spec.tsx)",
1383
- selected: true
1384
- },
1385
- {
1386
- value: "e2e.ts",
1387
- title: "E2E Test (.e2e.ts)",
1388
- selected: true
1389
- }
1390
- ]
1391
- })).filesToGenerate;
1392
- };
1393
- const chooseSassExtension = async () => {
1394
- const { prompt } = await import("prompts");
1395
- return (await prompt({
1396
- name: "sassFormat",
1397
- type: "select",
1398
- message: "Which Sass format would you like to use? (More info: https://sass-lang.com/documentation/syntax/#the-indented-syntax)",
1399
- choices: [{
1400
- value: "sass",
1401
- title: `*.sass Format`,
1402
- selected: true
1403
- }, {
1404
- value: "scss",
1405
- title: "*.scss Format"
1406
- }]
1407
- })).sassFormat;
1408
- };
1409
- /**
1410
- * Get a filepath for a file we want to generate!
1411
- *
1412
- * The filepath for a given file depends on the path, the user-supplied
1413
- * component name, the extension, and whether we're inside of a test directory.
1414
- *
1415
- * @param filePath path to where we're going to generate the component
1416
- * @param componentName the user-supplied name for the generated component
1417
- * @param extension the file extension
1418
- * @returns the full filepath to the component (with a possible `test` directory
1419
- * added)
1420
- */
1421
- const getFilepathForFile = (filePath, componentName, extension) => isTest(extension) ? normalizePath(join(filePath, "test", `${componentName}.${extension}`)) : normalizePath(join(filePath, `${componentName}.${extension}`));
1422
- /**
1423
- * Get the boilerplate for a file and write it to disk
1424
- *
1425
- * @param config the current config, needed for file operations
1426
- * @param componentName the component name (user-supplied)
1427
- * @param withCss are we generating CSS?
1428
- * @param file the file we want to write
1429
- * @param styleExtension extension used for styles
1430
- * @returns a `Promise<string>` which holds the full filepath we've written to,
1431
- * used to print out a little summary of our activity to the user.
1432
- */
1433
- const getBoilerplateAndWriteFile = async (config, componentName, withCss, file, styleExtension) => {
1434
- const boilerplate = getBoilerplateByExtension(componentName, file.extension, withCss, styleExtension);
1435
- await config.sys.writeFile(normalizePath(file.path), boilerplate);
1436
- return file.path;
1437
- };
1438
- /**
1439
- * Check to see if any of the files we plan to write already exist and would
1440
- * therefore be overwritten if we proceed, because we'd like to not overwrite
1441
- * people's code!
1442
- *
1443
- * This function will check all the filepaths and if it finds any files log an
1444
- * error and exit with an error code. If it doesn't find anything it will just
1445
- * peacefully return `Promise<void>`.
1446
- *
1447
- * @param files the files we want to check
1448
- * @param config the Config object, used here to get access to `sys.readFile`
1449
- */
1450
- const checkForOverwrite = async (files, config) => {
1451
- const alreadyPresent = [];
1452
- await Promise.all(files.map(async ({ path }) => {
1453
- if (await config.sys.readFile(path) !== void 0) alreadyPresent.push(path);
1454
- }));
1455
- if (alreadyPresent.length > 0) {
1456
- config.logger.error("Generating code would overwrite the following files:", ...alreadyPresent.map((path) => " " + normalizePath(path)));
1457
- await config.sys.exit(1);
3559
+ const styleOptions = [
3560
+ {
3561
+ value: "css",
3562
+ label: "CSS (.css)"
3563
+ },
3564
+ ...[...new Set(generateContribs.flatMap((c) => c.styleExtensions ?? []))].map((ext) => ({
3565
+ value: ext,
3566
+ label: `${ext.toUpperCase()} (.${ext})`
3567
+ })),
3568
+ {
3569
+ value: "",
3570
+ label: "None"
3571
+ }
3572
+ ];
3573
+ const stylePick = await p.select({
3574
+ message: "Stylesheet format:",
3575
+ options: styleOptions
3576
+ });
3577
+ cancelIfAborted(stylePick);
3578
+ const styleExtension = stylePick || void 0;
3579
+ const generateCtx = {
3580
+ tagName: componentName,
3581
+ config: toProjectConfig(config),
3582
+ prompts: p,
3583
+ nypm
3584
+ };
3585
+ const allFileTemplates = [];
3586
+ for (const contrib of generateContribs) allFileTemplates.push(...await resolveFileTemplates(contrib, generateCtx));
3587
+ let pickedExtensions = [];
3588
+ if (allFileTemplates.length > 0) {
3589
+ const filePick = await p.multiselect({
3590
+ message: "Additional files:",
3591
+ options: allFileTemplates.map((ft) => ({
3592
+ value: ft.extension,
3593
+ label: ft.label
3594
+ })),
3595
+ initialValues: allFileTemplates.filter((ft) => ft.selectedByDefault !== false).map((ft) => ft.extension),
3596
+ required: false
3597
+ });
3598
+ cancelIfAborted(filePick);
3599
+ pickedExtensions = filePick;
1458
3600
  }
1459
- };
1460
- /**
1461
- * Check if an extension is for a test
1462
- *
1463
- * @param extension the extension we want to check
1464
- * @returns a boolean indicating whether or not its a test
1465
- */
1466
- const isTest = (extension) => {
1467
- return extension === "e2e.ts" || extension === "spec.tsx";
1468
- };
1469
- /**
1470
- * Get the boilerplate for a file by its extension.
1471
- *
1472
- * @param tagName the name of the component we're generating
1473
- * @param extension the file extension we want boilerplate for (.css, tsx, etc)
1474
- * @param withCss a boolean indicating whether we're generating a CSS file
1475
- * @param styleExtension extension used for styles
1476
- * @returns a string container the file boilerplate for the supplied extension
1477
- */
1478
- const getBoilerplateByExtension = (tagName, extension, withCss, styleExtension) => {
1479
- switch (extension) {
1480
- case "tsx": return getComponentBoilerplate(tagName, withCss, styleExtension);
1481
- case "css":
1482
- case "less":
1483
- case "sass":
1484
- case "scss": return getStyleUrlBoilerplate(styleExtension);
1485
- case "spec.tsx": return getSpecTestBoilerplate(tagName);
1486
- case "e2e.ts": return getE2eTestBoilerplate(tagName);
1487
- default: throw new Error(`Unkown extension "${extension}".`);
3601
+ const outDir = join(srcDir, "components", dir, componentName);
3602
+ const className = toPascalCase(componentName);
3603
+ const filesToWrite = [];
3604
+ filesToWrite.push({
3605
+ absPath: normalizePath(join(outDir, `${componentName}.tsx`)),
3606
+ content: getComponentBoilerplate(componentName, styleExtension)
3607
+ });
3608
+ if (styleExtension) filesToWrite.push({
3609
+ absPath: normalizePath(join(outDir, `${componentName}.${styleExtension}`)),
3610
+ content: getStyleBoilerplate(styleExtension)
3611
+ });
3612
+ for (const ext of pickedExtensions) {
3613
+ const tmpl = allFileTemplates.find((ft) => ft.extension === ext);
3614
+ const absPath = normalizePath(join(outDir, tmpl.subdirectory ?? "", `${componentName}.${ext}`));
3615
+ filesToWrite.push({
3616
+ absPath,
3617
+ content: tmpl.template(componentName, className)
3618
+ });
1488
3619
  }
3620
+ const wouldOverwrite = (await Promise.all(filesToWrite.map(async ({ absPath }) => await config.sys.readFile(absPath) !== void 0 ? absPath : null))).filter((f) => f !== null);
3621
+ if (wouldOverwrite.length > 0) {
3622
+ config.logger.error("Generating code would overwrite the following files:", ...wouldOverwrite.map((path) => " " + normalizePath(path)));
3623
+ await config.sys.exit(1);
3624
+ return;
3625
+ }
3626
+ const dirs = [...new Set(filesToWrite.map(({ absPath }) => normalizePath(join(absPath, ".."))))];
3627
+ await Promise.all(dirs.map((d) => config.sys.createDir(d, { recursive: true })));
3628
+ await Promise.all(filesToWrite.map(({ absPath, content }) => config.sys.writeFile(absPath, content)));
3629
+ p.note(filesToWrite.map(({ absPath }) => relative(config.rootDir, absPath)).join("\n"), "Generated");
3630
+ p.outro(`stencil generate ${input}`);
1489
3631
  };
1490
- /**
1491
- * Get the boilerplate for a file containing the definition of a component
1492
- * @param tagName the name of the tag to give the component
1493
- * @param hasStyle designates if the component has an external stylesheet or not
1494
- * @param styleExtension extension used for styles
1495
- * @returns the contents of a file that defines a component
1496
- */
1497
- const getComponentBoilerplate = (tagName, hasStyle, styleExtension) => {
1498
- const decorator = [`{`];
1499
- decorator.push(` tag: '${tagName}',`);
1500
- if (hasStyle) decorator.push(` styleUrl: '${tagName}.${styleExtension}',`);
1501
- decorator.push(` shadow: true,`);
1502
- decorator.push(`}`);
1503
- return `import { Component, Host, h } from '@stencil/core';
1504
-
1505
- @Component(${decorator.join("\n")})
1506
- export class ${toPascalCase(tagName)} {
1507
- render() {
1508
- return (
1509
- <Host>
1510
- <slot></slot>
1511
- </Host>
1512
- );
1513
- }
1514
- }
1515
- `;
1516
- };
1517
- /**
1518
- * Get the boilerplate for style for a generated component
1519
- * @param ext extension used for styles
1520
- * @returns a boilerplate CSS block
1521
- */
1522
- const getStyleUrlBoilerplate = (ext) => ext === "sass" ? `:host
1523
- display: block
1524
- ` : `:host {
1525
- display: block;
1526
- }
1527
- `;
1528
- /**
1529
- * Get the boilerplate for a file containing a spec (unit) test for a component
1530
- * @param tagName the name of the tag associated with the component under test
1531
- * @returns the contents of a file that unit tests a component
1532
- */
1533
- const getSpecTestBoilerplate = (tagName) => `import { newSpecPage } from '@stencil/core/testing';
1534
- import { ${toPascalCase(tagName)} } from '../${tagName}';
1535
-
1536
- describe('${tagName}', () => {
1537
- it('renders', async () => {
1538
- const page = await newSpecPage({
1539
- components: [${toPascalCase(tagName)}],
1540
- html: \`<${tagName}></${tagName}>\`,
1541
- });
1542
- expect(page.root).toEqualHtml(\`
1543
- <${tagName}>
1544
- <mock:shadow-root>
1545
- <slot></slot>
1546
- </mock:shadow-root>
1547
- </${tagName}>
1548
- \`);
1549
- });
1550
- });
1551
- `;
1552
- /**
1553
- * Get the boilerplate for a file containing an end-to-end (E2E) test for a component
1554
- * @param tagName the name of the tag associated with the component under test
1555
- * @returns the contents of a file that E2E tests a component
1556
- */
1557
- const getE2eTestBoilerplate = (tagName) => `import { newE2EPage } from '@stencil/core/testing';
1558
-
1559
- describe('${tagName}', () => {
1560
- it('renders', async () => {
1561
- const page = await newE2EPage();
1562
- await page.setContent('<${tagName}></${tagName}>');
1563
-
1564
- const element = await page.find('${tagName}');
1565
- expect(element).toHaveClass('hydrated');
1566
- });
1567
- });
1568
- `;
1569
- /**
1570
- * Convert a dash case string to pascal case.
1571
- * @param str the string to convert
1572
- * @returns the converted input as pascal case
1573
- */
1574
- const toPascalCase = (str) => str.split("-").reduce((res, part) => res + part[0].toUpperCase() + part.slice(1), "");
1575
3632
  //#endregion
1576
3633
  //#region src/task-telemetry.ts
1577
3634
  /**
@@ -1680,11 +3737,370 @@ const taskInfo = (coreCompiler, sys, logger) => {
1680
3737
  console.log(`${logger.cyan(" Build:")} ${coreCompiler.buildId}`);
1681
3738
  console.log(`${logger.cyan(" Stencil:")} ${coreCompiler.version}${logger.emoji(" " + coreCompiler.vermoji)}`);
1682
3739
  console.log(`${logger.cyan(" TypeScript:")} ${versions.typescript}`);
1683
- console.log(`${logger.cyan(" Rollup:")} ${versions.rollup}`);
3740
+ console.log(`${logger.cyan(" Rolldown:")} ${versions.rolldown}`);
1684
3741
  console.log(`${logger.cyan(" Terser:")} ${versions.terser}`);
1685
3742
  console.log(``);
1686
3743
  };
1687
3744
  //#endregion
3745
+ //#region src/wizard/init/apply.ts
3746
+ /**
3747
+ * Copy component-starter template into rootDir, interpolating project name and namespace.
3748
+ *
3749
+ * @param rootDir - Destination directory (typically `process.cwd()`).
3750
+ * @param projectName - Value to substitute for `{{PROJECT_NAME}}` placeholders.
3751
+ * @param namespace - Value to substitute for `{{NAMESPACE}}` placeholders.
3752
+ * @param stencilVersion - Optional version to substitute for `{{STENCIL_VERSION}}` placeholders.
3753
+ */
3754
+ async function copyTemplate(rootDir, projectName, namespace, stencilVersion) {
3755
+ const templateDir = getTemplatePath("component-starter");
3756
+ const entries = await readdir(templateDir, {
3757
+ recursive: true,
3758
+ withFileTypes: true
3759
+ });
3760
+ const resolvedStencilVersion = stencilVersion ? `^${stencilVersion}` : "^5.0.0";
3761
+ for (const entry of entries) {
3762
+ if (!entry.isFile()) continue;
3763
+ const srcPath = join(entry.parentPath, entry.name);
3764
+ const relPath = relative(templateDir, srcPath);
3765
+ const destPath = join(rootDir, relPath);
3766
+ await mkdir(dirname(destPath), { recursive: true });
3767
+ const content = (await readFile(srcPath, "utf8")).replace(/\{\{PROJECT_NAME\}\}/g, projectName).replace(/\{\{NAMESPACE\}\}/g, namespace).replace(/\{\{STENCIL_VERSION\}\}/g, resolvedStencilVersion);
3768
+ if (relPath === "package.json") await mergePackageJson(destPath, content);
3769
+ else if (relPath === "tsconfig.json") await mergeTsConfig(destPath, content);
3770
+ else if (relPath === ".gitignore") await mergeGitignore(destPath, content);
3771
+ else await writeIfAbsent(destPath, content);
3772
+ }
3773
+ }
3774
+ const PARCEL_WATCHER_BUILD_ALLOWANCES = [
3775
+ `onlyBuiltDependencies:`,
3776
+ ` - '@parcel/watcher'`,
3777
+ ``,
3778
+ `allowBuilds:`,
3779
+ ` '@parcel/watcher': true`
3780
+ ].join("\n");
3781
+ async function mergePnpmWorkspaceYaml(yamlPath) {
3782
+ let existing = null;
3783
+ try {
3784
+ existing = await readFile(yamlPath, "utf8");
3785
+ } catch {}
3786
+ if (existing === null) {
3787
+ await writeFile(yamlPath, [
3788
+ `packages:`,
3789
+ ` - 'packages/*'`,
3790
+ ``,
3791
+ PARCEL_WATCHER_BUILD_ALLOWANCES,
3792
+ ``
3793
+ ].join("\n"), "utf8");
3794
+ return;
3795
+ }
3796
+ let toAppend = "";
3797
+ if (!existing.includes("packages/*")) toAppend += `\npackages:\n - 'packages/*'\n`;
3798
+ if (!existing.includes("onlyBuiltDependencies:")) toAppend += `\nonlyBuiltDependencies:\n - '@parcel/watcher'\n`;
3799
+ if (!existing.includes("allowBuilds:")) toAppend += `\nallowBuilds:\n '@parcel/watcher': true\n`;
3800
+ if (toAppend) {
3801
+ const separator = existing.endsWith("\n") ? "" : "\n";
3802
+ await writeFile(yamlPath, existing + separator + toAppend, "utf8");
3803
+ }
3804
+ }
3805
+ async function writeIfAbsent(destPath, content) {
3806
+ try {
3807
+ await writeFile(destPath, content, {
3808
+ encoding: "utf8",
3809
+ flag: "wx"
3810
+ });
3811
+ } catch (e) {
3812
+ if (e.code !== "EEXIST") throw e;
3813
+ }
3814
+ }
3815
+ async function mergePackageJson(destPath, templateContent) {
3816
+ const template = JSON.parse(templateContent);
3817
+ let existing;
3818
+ try {
3819
+ existing = JSON.parse(await readFile(destPath, "utf8"));
3820
+ } catch {
3821
+ await writeFile(destPath, templateContent, "utf8");
3822
+ return;
3823
+ }
3824
+ const dependencies = mergeStringRecord(template.dependencies, existing.dependencies);
3825
+ const devDependencies = mergeStringRecord(template.devDependencies, existing.devDependencies);
3826
+ for (const pkg of Object.keys(devDependencies)) if (pkg in dependencies) delete devDependencies[pkg];
3827
+ const merged = {
3828
+ ...template,
3829
+ ...existing,
3830
+ scripts: mergeStringRecord(template.scripts, existing.scripts),
3831
+ dependencies,
3832
+ devDependencies
3833
+ };
3834
+ await writeFile(destPath, JSON.stringify(merged, null, 2) + "\n", "utf8");
3835
+ }
3836
+ async function mergeTsConfig(destPath, templateContent) {
3837
+ const template = JSON.parse(templateContent);
3838
+ let existing;
3839
+ try {
3840
+ existing = JSON.parse(await readFile(destPath, "utf8"));
3841
+ } catch {
3842
+ await writeFile(destPath, templateContent, "utf8");
3843
+ return;
3844
+ }
3845
+ const merged = {
3846
+ ...template,
3847
+ ...existing,
3848
+ compilerOptions: mergeStringRecord(template.compilerOptions, existing.compilerOptions)
3849
+ };
3850
+ await writeFile(destPath, JSON.stringify(merged, null, 2) + "\n", "utf8");
3851
+ }
3852
+ async function mergeGitignore(destPath, templateContent) {
3853
+ let existing;
3854
+ try {
3855
+ existing = await readFile(destPath, "utf8");
3856
+ } catch {
3857
+ await writeFile(destPath, templateContent, "utf8");
3858
+ return;
3859
+ }
3860
+ const existingEntries = new Set(existing.split("\n").map((l) => l.trim()).filter(Boolean));
3861
+ const missing = templateContent.split("\n").filter((line) => line.trim() && !existingEntries.has(line.trim()));
3862
+ if (missing.length === 0) return;
3863
+ const separator = existing.endsWith("\n") ? "" : "\n";
3864
+ await writeFile(destPath, existing + separator + missing.join("\n") + "\n", "utf8");
3865
+ }
3866
+ function mergeStringRecord(base, override) {
3867
+ const toObj = (v) => v !== null && typeof v === "object" ? v : {};
3868
+ return {
3869
+ ...toObj(base),
3870
+ ...toObj(override)
3871
+ };
3872
+ }
3873
+ async function writeStencilConfig(rootDir, content) {
3874
+ await writeFile(join(rootDir, "stencil.config.ts"), content, "utf8");
3875
+ }
3876
+ async function writeGlobalStyle(rootDir) {
3877
+ const path = join(rootDir, "src", "global.css");
3878
+ await mkdir(dirname(path), { recursive: true });
3879
+ await writeIfAbsent(path, `@import "stencil-globals";\n@import "stencil-hydrate";\n`);
3880
+ }
3881
+ async function writeGlobalScript(rootDir) {
3882
+ const path = join(rootDir, "src", "global.ts");
3883
+ await mkdir(dirname(path), { recursive: true });
3884
+ await writeIfAbsent(path, `export default function (): void {}\n`);
3885
+ }
3886
+ function workspaceBuildScript(pm) {
3887
+ switch (pm) {
3888
+ case "pnpm": return "pnpm -r build";
3889
+ case "yarn": return "yarn workspaces run build";
3890
+ case "bun": return "bun run --filter \"*\" build";
3891
+ default: return "npm run build --workspaces --if-present";
3892
+ }
3893
+ }
3894
+ /**
3895
+ * Scaffold a workspace root in `cwd`: creates `packages/`, writes the appropriate
3896
+ * workspace manifest (`pnpm-workspace.yaml` for pnpm, `workspaces` field in
3897
+ * `package.json` for npm / yarn / bun), and ensures a root `package.json` exists.
3898
+ * @param cwd - Absolute path to the workspace root (where `package.json` will be created).
3899
+ * @param projectName - Name to use for the root package.json (typically the project name).
3900
+ * @returns A promise that resolves when the workspace root has been scaffolded.
3901
+ */
3902
+ async function scaffoldWorkspaceRoot(cwd, projectName) {
3903
+ await mkdir(join(cwd, "packages"), { recursive: true });
3904
+ const pm = await detectPackageManager(cwd);
3905
+ const usePnpmYaml = pm?.name === "pnpm";
3906
+ const pkgPath = join(cwd, "package.json");
3907
+ let pkg;
3908
+ try {
3909
+ pkg = JSON.parse(await readFile(pkgPath, "utf8"));
3910
+ } catch {
3911
+ pkg = {};
3912
+ }
3913
+ pkg.name ??= `${projectName}-workspace`;
3914
+ pkg.version ??= "0.0.1";
3915
+ pkg.private = true;
3916
+ pkg.scripts ??= { build: workspaceBuildScript(pm?.name) };
3917
+ if (!usePnpmYaml) pkg.workspaces = ["packages/*"];
3918
+ delete pkg.dependencies;
3919
+ delete pkg.devDependencies;
3920
+ await writeFile(pkgPath, JSON.stringify(pkg, null, 2) + "\n", "utf8");
3921
+ if (usePnpmYaml) await mergePnpmWorkspaceYaml(join(cwd, "pnpm-workspace.yaml"));
3922
+ }
3923
+ /**
3924
+ * Write output-driven distributable fields (type, module, types) into package.json.
3925
+ * These fields depend on which outputs the user selected, so they cannot be static in the template.
3926
+ * Skips if fields is empty (e.g. www-only project).
3927
+ *
3928
+ * @param rootDir - Absolute path to the project root.
3929
+ * @param fields - Fields to write, from generatePackageJsonFields().
3930
+ */
3931
+ async function applyPackageJsonFields(rootDir, fields) {
3932
+ if (Object.keys(fields).length === 0) return;
3933
+ const pkgPath = join(rootDir, "package.json");
3934
+ const pkg = JSON.parse(await readFile(pkgPath, "utf8"));
3935
+ Object.assign(pkg, fields);
3936
+ await writeFile(pkgPath, JSON.stringify(pkg, null, 2) + "\n", "utf8");
3937
+ }
3938
+ //#endregion
3939
+ //#region src/task-init.ts
3940
+ function outputKeysToTargets(keys) {
3941
+ const map = {
3942
+ loader: "loader-bundle",
3943
+ standalone: "standalone",
3944
+ ssr: "ssr",
3945
+ "ssr-wasm": "ssr-wasm",
3946
+ www: "www"
3947
+ };
3948
+ return keys.length > 0 ? keys.map((k) => ({ type: map[k] })) : [{ type: "loader-bundle" }];
3949
+ }
3950
+ async function taskInit(coreCompiler, strictConfig, loadProjectConfig) {
3951
+ const cwd = process.cwd();
3952
+ const isExistingProject = await isExistingStencilProject(cwd);
3953
+ printSplash();
3954
+ p.intro(`stencil init`);
3955
+ if (process.env.STENCIL_WIZARD_DEV) p.log.warn(`Dev mode: loading wizards from ${process.env.STENCIL_WIZARD_DEV}`);
3956
+ if (isCI) {
3957
+ p.log.warn("Running in CI - non-interactive mode is not yet supported for `stencil init`.");
3958
+ process.exit(1);
3959
+ }
3960
+ if (isExistingProject) {
3961
+ await addCapabilities(cwd, strictConfig);
3962
+ return;
3963
+ }
3964
+ const projectName = await promptProjectName();
3965
+ const namespace = toNamespace(projectName);
3966
+ const outputs = await promptOutputs();
3967
+ const features = await promptFeatures();
3968
+ const docs = await promptDocs();
3969
+ const selectedIntegrations = await promptIntegrations();
3970
+ let monorepo = false;
3971
+ let coreName = "";
3972
+ if (hasFrameworkTargets(selectedIntegrations)) {
3973
+ monorepo = await promptMonorepo();
3974
+ if (monorepo) coreName = await promptWorkspaceCoreName();
3975
+ }
3976
+ const configSource = generateStencilConfig({
3977
+ namespace,
3978
+ outputs,
3979
+ signals: features.signals,
3980
+ docs
3981
+ }) ?? (needsStencilConfig(selectedIntegrations) ? `import { Config } from '@stencil/core';\n\nexport const config: Config = {\n namespace: '${namespace}',\n outputTargets: [{ type: 'loader-bundle' }],\n};\n` : null);
3982
+ const summaryLines = [
3983
+ `Template: component-starter`,
3984
+ `Name: ${projectName}`,
3985
+ `Namespace: ${namespace}`,
3986
+ `Config: ${configSource ? "stencil.config.ts" : "zero-config (loader default)"}`
3987
+ ];
3988
+ if (monorepo) {
3989
+ summaryLines.push(`Structure: monorepo workspace`);
3990
+ summaryLines.push(`Core: packages/${coreName}/`);
3991
+ }
3992
+ if (selectedIntegrations.length > 0) summaryLines.push(`Add: ${selectedIntegrations.map((i) => i.displayName).join(", ")}`);
3993
+ p.note(summaryLines.join("\n"), "Summary");
3994
+ const coreDir = monorepo ? join(cwd, "packages", coreName) : cwd;
3995
+ const s1 = p.spinner();
3996
+ s1.start("Scaffolding project files");
3997
+ if (monorepo) await scaffoldWorkspaceRoot(cwd, projectName);
3998
+ await copyTemplate(coreDir, projectName, namespace, coreCompiler?.version);
3999
+ await applyPackageJsonFields(coreDir, generatePackageJsonFields(outputs));
4000
+ if (configSource) await writeStencilConfig(coreDir, configSource);
4001
+ if (features.globalStyle) await writeGlobalStyle(coreDir);
4002
+ if (features.globalScript) await writeGlobalScript(coreDir);
4003
+ s1.stop("Project files created");
4004
+ const s2 = p.spinner();
4005
+ s2.start("Installing dependencies");
4006
+ await installDependencies({
4007
+ cwd,
4008
+ silent: true
4009
+ });
4010
+ s2.stop("Dependencies installed");
4011
+ if (selectedIntegrations.length > 0) {
4012
+ const s3 = p.spinner();
4013
+ const pkgs = selectedIntegrations.map((i) => i.package);
4014
+ s3.start(`Installing ${pkgs.join(", ")}`);
4015
+ await addDevDependency(withVersionRanges(pkgs), {
4016
+ cwd: coreDir,
4017
+ silent: true
4018
+ });
4019
+ s3.stop("Integrations installed");
4020
+ }
4021
+ if (selectedIntegrations.length > 0) {
4022
+ const discovered = await discoverPlugins(coreDir);
4023
+ const selectedPkgs = new Set(selectedIntegrations.map((i) => i.package));
4024
+ const resolvedValidated = loadProjectConfig && configSource ? await loadProjectConfig(join(coreDir, "stencil.config.ts")) : coreCompiler ? coreCompiler.validateConfig({
4025
+ rootDir: coreDir,
4026
+ outputTargets: outputKeysToTargets(outputs),
4027
+ ...configSource ? { namespace } : {}
4028
+ }, {}).config : null;
4029
+ const projectConfig = resolvedValidated ? {
4030
+ ...toProjectConfig(resolvedValidated),
4031
+ rootDir: coreDir
4032
+ } : defaultProjectConfig(coreDir, { namespace });
4033
+ for (const d of discovered) if (selectedPkgs.has(d.packageName) && d.plugin.init?.run) await d.plugin.init.run({
4034
+ isNewProject: true,
4035
+ prompts: p,
4036
+ nypm,
4037
+ config: projectConfig,
4038
+ workspaceRoot: monorepo ? cwd : void 0,
4039
+ ts,
4040
+ openStencilConfig: () => openStencilConfig(join(projectConfig.rootDir, "stencil.config.ts"))
4041
+ });
4042
+ }
4043
+ const pm = (await nypm.detectPackageManager(cwd))?.name ?? "npm";
4044
+ const devDir = monorepo ? `packages/${coreName}` : null;
4045
+ const devCmd = `${pm} run dev`;
4046
+ p.outro(devDir ? `Your project is ready!\n cd ${devDir}\n ${devCmd}` : `Your project is ready! Run: ${devCmd}`);
4047
+ }
4048
+ async function addCapabilities(cwd, strictConfig) {
4049
+ const workspaceRoot = await detectWorkspaceRoot(cwd);
4050
+ const raw = JSON.parse(await readFile(join(cwd, "package.json"), "utf8"));
4051
+ const installed = new Set([...Object.keys(raw.dependencies ?? {}), ...Object.keys(raw.devDependencies ?? {})]);
4052
+ const discovered = await discoverPlugins(cwd);
4053
+ const configurable = discovered.filter((d) => d.plugin.init);
4054
+ const installable = KNOWN_INTEGRATIONS.filter((i) => !installed.has(i.package));
4055
+ if (installable.length === 0 && configurable.length === 0) {
4056
+ p.log.info("All known integrations are already installed and configured.");
4057
+ p.outro("Nothing to do.");
4058
+ return;
4059
+ }
4060
+ const { toInstall, toConfigure } = await promptAddCapabilities(installable, configurable);
4061
+ if (toInstall.length === 0 && toConfigure.length === 0) {
4062
+ p.outro("No changes made.");
4063
+ return;
4064
+ }
4065
+ const summaryLines = [];
4066
+ for (const i of toInstall) summaryLines.push(`Install: ${i.displayName}`);
4067
+ for (const d of toConfigure) summaryLines.push(`Configure: ${d.plugin.init.displayName}`);
4068
+ p.note(summaryLines.join("\n"), "Summary");
4069
+ const confirmed = await p.confirm({ message: "Apply changes?" });
4070
+ cancelIfAborted(confirmed);
4071
+ if (!confirmed) {
4072
+ p.cancel("Cancelled.");
4073
+ process.exit(0);
4074
+ }
4075
+ if (toInstall.length > 0) {
4076
+ const s = p.spinner();
4077
+ const pkgs = toInstall.map((i) => i.package);
4078
+ s.start(`Installing ${pkgs.join(", ")}`);
4079
+ await addDevDependency(withVersionRanges(pkgs), {
4080
+ cwd,
4081
+ silent: true
4082
+ });
4083
+ s.stop("Dependencies installed");
4084
+ }
4085
+ const allDiscovered = toInstall.length > 0 ? await discoverPlugins(cwd) : discovered;
4086
+ const newlyInstalledPkgs = new Set(toInstall.map((i) => i.package));
4087
+ const toRun = [...allDiscovered.filter((d) => newlyInstalledPkgs.has(d.packageName)), ...toConfigure].filter((d) => d.plugin.init?.run);
4088
+ const projectConfig = strictConfig ? toProjectConfig(strictConfig) : defaultProjectConfig(cwd);
4089
+ for (const d of toRun) await d.plugin.init.run({
4090
+ isNewProject: false,
4091
+ prompts: p,
4092
+ nypm,
4093
+ config: projectConfig,
4094
+ workspaceRoot,
4095
+ ts,
4096
+ openStencilConfig: () => openStencilConfig(join(projectConfig.rootDir, "stencil.config.ts"))
4097
+ });
4098
+ p.outro("Done! Run pnpm run dev to continue.");
4099
+ }
4100
+ function toNamespace(name) {
4101
+ return toPascalCase(name.replace(/^@[^/]+\//, "").replace(/[/_]/g, "-"));
4102
+ }
4103
+ //#endregion
1688
4104
  //#region src/task-serve.ts
1689
4105
  const taskServe = async (config, flags) => {
1690
4106
  config.suppressLogs = true;
@@ -1740,6 +4156,41 @@ const run = async (init) => {
1740
4156
  }), logger, sys);
1741
4157
  return;
1742
4158
  }
4159
+ if (task === "add" || task === "init") {
4160
+ const coreCompiler = await loadCoreCompiler(sys);
4161
+ const rootDir = sys.getCurrentDirectory();
4162
+ const findConfigResults = await findConfig({
4163
+ sys,
4164
+ configPath: flags.config
4165
+ });
4166
+ let strictConfig;
4167
+ const foundConfigPath = !findConfigResults.isErr ? result.unwrap(findConfigResults).configPath : null;
4168
+ if (foundConfigPath) {
4169
+ const loaded = await coreCompiler.loadConfig({
4170
+ config: { rootDir: dirname(foundConfigPath) },
4171
+ configPath: foundConfigPath,
4172
+ logger,
4173
+ sys
4174
+ });
4175
+ strictConfig = coreCompiler.validateConfig(loaded.config, {}).config;
4176
+ } else strictConfig = coreCompiler.validateConfig({ rootDir }, {}).config;
4177
+ if (task === "add") await taskAdd(flags.unknownArgs, strictConfig);
4178
+ else {
4179
+ const loadProjectConfig = async (configPath) => {
4180
+ const derivedRootDir = configPath ? dirname(configPath) : rootDir;
4181
+ const loaded = await coreCompiler.loadConfig({
4182
+ config: { rootDir: derivedRootDir },
4183
+ configPath,
4184
+ logger,
4185
+ sys
4186
+ });
4187
+ if (loaded.diagnostics.length > 0) logger.printDiagnostics(loaded.diagnostics);
4188
+ return coreCompiler.validateConfig(loaded.config ?? { rootDir: derivedRootDir }, {}).config;
4189
+ };
4190
+ await taskInit(coreCompiler, strictConfig, loadProjectConfig);
4191
+ }
4192
+ return;
4193
+ }
1743
4194
  startupLog(logger, task);
1744
4195
  const findConfigResults = await findConfig({
1745
4196
  sys,
@@ -1760,7 +4211,7 @@ const run = async (init) => {
1760
4211
  const configWithFlags = mergeFlags({}, flags);
1761
4212
  const validated = await coreCompiler.loadConfig({
1762
4213
  config: configWithFlags,
1763
- configPath: foundConfig.configPath,
4214
+ configPath: foundConfig.configPath ?? void 0,
1764
4215
  logger,
1765
4216
  sys
1766
4217
  });
@@ -1797,6 +4248,9 @@ const runTask = async (coreCompiler, config, task, sys, flags) => {
1797
4248
  if (!configWithFlags.sys) configWithFlags.sys = sys;
1798
4249
  const strictConfig = coreCompiler.validateConfig(configWithFlags, {}).config;
1799
4250
  switch (task) {
4251
+ case "add":
4252
+ await taskAdd(resolvedFlags.unknownArgs ?? [], strictConfig);
4253
+ break;
1800
4254
  case "build":
1801
4255
  await taskBuild(coreCompiler, strictConfig, resolvedFlags);
1802
4256
  break;
@@ -1810,6 +4264,12 @@ const runTask = async (coreCompiler, config, task, sys, flags) => {
1810
4264
  case "help":
1811
4265
  await taskHelp(resolvedFlags, strictConfig.logger, sys);
1812
4266
  break;
4267
+ case "init":
4268
+ await taskInit(coreCompiler, strictConfig);
4269
+ break;
4270
+ case "migrate":
4271
+ await taskMigrate(coreCompiler, strictConfig, resolvedFlags);
4272
+ break;
1813
4273
  case "prerender":
1814
4274
  await taskPrerender(coreCompiler, strictConfig, resolvedFlags);
1815
4275
  break;