@stencil/cli 5.0.0-alpha.1 → 5.0.0-alpha.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.d.mts +157 -14
  2. package/dist/index.mjs +2742 -474
  3. package/package.json +12 -8
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 { pathToFileURL } from "node:url";
11
+ import { existsSync } from "node:fs";
12
+ import { homedir } from "node:os";
13
+ import { dirname as dirname$1, isAbsolute, join as join$1, relative as relative$1 } from "path";
14
+ import ts from "typescript";
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,2172 @@ 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/discover.ts
606
+ function toStringRecord(val) {
607
+ return val !== null && typeof val === "object" ? val : {};
608
+ }
609
+ async function readJson$1(filePath) {
610
+ try {
611
+ return JSON.parse(await readFile(filePath, "utf8"));
612
+ } catch {
613
+ return null;
614
+ }
615
+ }
616
+ async function loadOne(rootDir, packageName, loader) {
617
+ const wizardEntry = ((await readJson$1(join(rootDir, "node_modules", packageName, "package.json")))?.stencil)?.wizard;
618
+ if (!wizardEntry) return null;
619
+ const wizardPath = join(rootDir, "node_modules", packageName, wizardEntry);
620
+ let mod;
621
+ try {
622
+ mod = await loader(pathToFileURL(wizardPath).href);
623
+ } catch {
624
+ console.warn(`[stencil] ${packageName} declares stencil.wizard but the module failed to load: ${wizardPath}`);
625
+ return null;
626
+ }
627
+ const plugin = mod.wizard;
628
+ if (!plugin || typeof plugin !== "object") {
629
+ console.warn(`[stencil] ${packageName} declares stencil.wizard but does not export a 'wizard' object`);
630
+ return null;
631
+ }
632
+ return {
633
+ packageName,
634
+ plugin
635
+ };
636
+ }
637
+ /**
638
+ * Scans the project's declared dependencies for packages that expose a
639
+ * `stencil.wizard` entry in their `package.json` and dynamically imports
640
+ * each matching module.
641
+ *
642
+ * @param rootDir - Absolute path to the project root (where `package.json` lives).
643
+ * @param loader - Module loader; injectable for testing. Defaults to `import()`.
644
+ * @returns Array of successfully loaded plugins, in dependency declaration order.
645
+ */
646
+ async function discoverPlugins(rootDir, loader = (url) => import(url)) {
647
+ const pkg = await readJson$1(join(rootDir, "package.json"));
648
+ if (!pkg) return [];
649
+ const depNames = [...new Set([...Object.keys(toStringRecord(pkg.dependencies)), ...Object.keys(toStringRecord(pkg.devDependencies))])];
650
+ const plugins = (await Promise.allSettled(depNames.map((name) => loadOne(rootDir, name, loader)))).filter((r) => r.status === "fulfilled" && r.value !== null).map((r) => r.value);
651
+ const devEnv = process.env.STENCIL_WIZARD_DEV;
652
+ if (devEnv) {
653
+ const devPaths = devEnv.split(",").map((s) => s.trim()).filter(Boolean);
654
+ for (const devPath of devPaths) {
655
+ const devPlugin = await loadDevPlugin(resolve(rootDir, devPath), loader);
656
+ if (devPlugin) {
657
+ const idx = plugins.findIndex((p) => p.packageName === devPlugin.packageName);
658
+ if (idx >= 0) plugins.splice(idx, 1, devPlugin);
659
+ else plugins.unshift(devPlugin);
660
+ }
661
+ }
662
+ }
663
+ return plugins;
664
+ }
665
+ async function findDevPackageName(wizardPath) {
666
+ const dir = dirname(wizardPath);
667
+ for (const candidate of [dir, resolve(dir, "..")]) {
668
+ const pkg = await readJson$1(join(candidate, "package.json"));
669
+ if (typeof pkg?.name === "string") return pkg.name;
670
+ }
671
+ return basename(dir);
672
+ }
673
+ async function loadDevPlugin(wizardPath, loader) {
674
+ const packageName = await findDevPackageName(wizardPath);
675
+ let mod;
676
+ try {
677
+ mod = await loader(pathToFileURL(wizardPath).href);
678
+ } catch {
679
+ console.warn(`[stencil] STENCIL_WIZARD_DEV: failed to load ${wizardPath}`);
680
+ return null;
681
+ }
682
+ const plugin = mod.wizard;
683
+ if (!plugin || typeof plugin !== "object") {
684
+ console.warn(`[stencil] STENCIL_WIZARD_DEV: ${wizardPath} does not export a 'wizard' object`);
685
+ return null;
686
+ }
687
+ return {
688
+ packageName,
689
+ plugin
690
+ };
691
+ }
692
+ //#endregion
693
+ //#region src/wizard/clack.ts
694
+ /**
695
+ * Exits cleanly if the user cancelled a prompt (Ctrl+C).
696
+ * Narrows the type from `T | symbol` to `T` for callers.
697
+ *
698
+ * @param value - Return value from a `@clack/prompts` prompt call.
699
+ */
700
+ function cancelIfAborted(value) {
701
+ if (isCancel(value)) {
702
+ cancel("Cancelled.");
703
+ process.exit(0);
704
+ }
705
+ }
706
+ //#endregion
707
+ //#region src/wizard/init/steps.ts
708
+ /** Well-known integrations the CLI can offer before any packages are installed. */
709
+ const KNOWN_INTEGRATIONS = [
710
+ {
711
+ package: "@stencil/vitest",
712
+ displayName: "Vitest",
713
+ description: "Unit / Spec / Integration / Browser testing",
714
+ group: "Testing"
715
+ },
716
+ {
717
+ package: "@stencil/playwright",
718
+ displayName: "Playwright",
719
+ description: "E2E testing",
720
+ group: "Testing"
721
+ },
722
+ {
723
+ package: "@stencil/sass",
724
+ displayName: "Sass",
725
+ description: "Sass/SCSS styles",
726
+ group: "Styling",
727
+ requiresStencilConfig: true
728
+ },
729
+ {
730
+ package: "@stencil/eslint-plugin",
731
+ displayName: "ESLint Plugin",
732
+ description: "Stencil-aware lint rules (ESLint, oxlint, Biome)",
733
+ group: "Linting"
734
+ },
735
+ {
736
+ package: "@stencil/storybook-plugin",
737
+ displayName: "Storybook",
738
+ description: "Component development & documentation",
739
+ group: "Tooling"
740
+ },
741
+ {
742
+ package: "@stencil/types-output-target",
743
+ displayName: "Types",
744
+ description: "TypeScript types for React, Vue, Solid, Svelte, Preact",
745
+ group: "Framework integrations",
746
+ requiresStencilConfig: true
747
+ },
748
+ {
749
+ package: "@stencil/react-output-target",
750
+ displayName: "React",
751
+ description: "React component wrappers",
752
+ group: "Framework integrations",
753
+ requiresStencilConfig: true
754
+ },
755
+ {
756
+ package: "@stencil/angular-output-target",
757
+ displayName: "Angular",
758
+ description: "Angular component wrappers",
759
+ group: "Framework integrations",
760
+ requiresStencilConfig: true
761
+ },
762
+ {
763
+ package: "@stencil/vue-output-target",
764
+ displayName: "Vue",
765
+ description: "Vue component wrappers",
766
+ group: "Framework integrations",
767
+ requiresStencilConfig: true
768
+ }
769
+ ];
770
+ async function promptOutputs() {
771
+ const picks = await p.multiselect({
772
+ message: "Outputs:",
773
+ options: [
774
+ {
775
+ value: "loader",
776
+ label: "Loader",
777
+ hint: "performant lazy-loader; browser & bundler ready"
778
+ },
779
+ {
780
+ value: "standalone",
781
+ label: "Standalone",
782
+ hint: "per-component modules, import only what you need"
783
+ },
784
+ {
785
+ value: "ssr",
786
+ label: "SSR",
787
+ hint: "pre-render components in any JS server environment"
788
+ },
789
+ {
790
+ value: "ssr-wasm",
791
+ label: "SSR WASM",
792
+ hint: "experimental: compile SSR to a portable WASM binary"
793
+ },
794
+ {
795
+ value: "www",
796
+ label: "WWW",
797
+ hint: "app mode with dev server and optional PWA support"
798
+ }
799
+ ],
800
+ required: false
801
+ });
802
+ cancelIfAborted(picks);
803
+ return picks;
804
+ }
805
+ async function promptFeatures() {
806
+ const picks = await p.multiselect({
807
+ message: "Features:",
808
+ options: [
809
+ {
810
+ value: "signals",
811
+ label: "Signals",
812
+ hint: "signal-backed @Prop/@State for cross-framework reactive interop"
813
+ },
814
+ {
815
+ value: "globalStyle",
816
+ label: "Global style",
817
+ hint: "Global stylesheet for font definitions, CSS variables, pre-load styles etc"
818
+ },
819
+ {
820
+ value: "globalScript",
821
+ label: "Global script",
822
+ hint: "Global script for initializing application-wide logic before components load"
823
+ }
824
+ ],
825
+ required: false
826
+ });
827
+ cancelIfAborted(picks);
828
+ const set = new Set(picks);
829
+ return {
830
+ signals: set.has("signals"),
831
+ globalStyle: set.has("globalStyle"),
832
+ globalScript: set.has("globalScript")
833
+ };
834
+ }
835
+ async function promptDocs() {
836
+ const picks = await p.multiselect({
837
+ message: "Docs:",
838
+ options: [
839
+ {
840
+ value: "cem",
841
+ label: "CEM",
842
+ hint: "custom-elements.json - preferred format for interop with tools like Storybook, Styleguidist, etc"
843
+ },
844
+ {
845
+ value: "json",
846
+ label: "JSON",
847
+ hint: "docs.json - Stencil / Ionic centric schema"
848
+ },
849
+ {
850
+ value: "vscode",
851
+ label: "VS Code",
852
+ hint: "vscode-data.json - editor autocomplete for your components"
853
+ }
854
+ ],
855
+ required: false
856
+ });
857
+ cancelIfAborted(picks);
858
+ return picks;
859
+ }
860
+ async function promptProjectName() {
861
+ const name = await p.text({
862
+ message: "Project name:",
863
+ defaultValue: "my-stencil-library",
864
+ validate: (v) => {
865
+ if (!v?.trim()) return "Project name is required";
866
+ }
867
+ });
868
+ cancelIfAborted(name);
869
+ return name;
870
+ }
871
+ function buildGroupedOptions(integrations) {
872
+ const groups = {};
873
+ for (const i of integrations) (groups[i.group] ??= []).push({
874
+ value: i.package,
875
+ label: i.displayName,
876
+ hint: i.description
877
+ });
878
+ return groups;
879
+ }
880
+ async function promptCustomPackages() {
881
+ const input = await p.text({
882
+ message: "Additional packages to install:",
883
+ placeholder: "e.g. my-plugin another-package (leave blank to skip)"
884
+ });
885
+ cancelIfAborted(input);
886
+ if (typeof input !== "string" || !input.trim()) return [];
887
+ return input.split(/[\s,]+/).map((s) => s.trim()).filter(Boolean);
888
+ }
889
+ async function promptIntegrations() {
890
+ const picks = await p.groupMultiselect({
891
+ message: "Add integrations (optional):",
892
+ options: buildGroupedOptions(KNOWN_INTEGRATIONS),
893
+ required: false
894
+ });
895
+ cancelIfAborted(picks);
896
+ return KNOWN_INTEGRATIONS.filter((i) => picks.includes(i.package));
897
+ }
898
+ function hasFrameworkTargets(integrations) {
899
+ return integrations.some((i) => i.group === "Framework integrations");
900
+ }
901
+ function needsStencilConfig(integrations) {
902
+ return integrations.some((i) => i.requiresStencilConfig);
903
+ }
904
+ async function promptMonorepo() {
905
+ const answer = await p.confirm({
906
+ message: "Set up as a monorepo workspace? (recommended for publishing framework wrappers)",
907
+ initialValue: true
908
+ });
909
+ cancelIfAborted(answer);
910
+ return answer;
911
+ }
912
+ async function promptWorkspaceCoreName() {
913
+ const name = await p.text({
914
+ message: "Core package directory name:",
915
+ defaultValue: "core",
916
+ placeholder: "core"
917
+ });
918
+ cancelIfAborted(name);
919
+ return name || "core";
920
+ }
921
+ /**
922
+ * Prompt for actions on an existing project: install new integrations and/or
923
+ * run init wizards for already-installed packages with wizard contributions.
924
+ *
925
+ * @param installable - KNOWN_INTEGRATIONS not yet present in the project.
926
+ * @param configurable - Already-installed plugins that declare an `init` contribution.
927
+ * @returns Selected integrations to install and plugins to configure.
928
+ */
929
+ async function promptAddCapabilities(installable, configurable) {
930
+ const options = {};
931
+ if (installable.length > 0) options["Install new integrations"] = installable.map((i) => ({
932
+ value: `install:${i.package}`,
933
+ label: i.displayName,
934
+ hint: i.description
935
+ }));
936
+ if (configurable.length > 0) options["Configure existing integrations"] = configurable.map((d) => ({
937
+ value: `configure:${d.packageName}`,
938
+ label: d.plugin.init.displayName,
939
+ hint: d.plugin.init.description
940
+ }));
941
+ const picks = await p.groupMultiselect({
942
+ message: "What would you like to do?",
943
+ options,
944
+ required: false
945
+ });
946
+ cancelIfAborted(picks);
947
+ const pickedSet = new Set(picks);
948
+ return {
949
+ toInstall: installable.filter((i) => pickedSet.has(`install:${i.package}`)),
950
+ toConfigure: configurable.filter((d) => pickedSet.has(`configure:${d.packageName}`))
951
+ };
952
+ }
953
+ //#endregion
954
+ //#region src/wizard/project.ts
955
+ /**
956
+ * Extracts the stable, plugin-relevant fields from a fully-resolved compiler config.
957
+ * @param validated The fully-resolved compiler config.
958
+ * @returns A ProjectConfig with only the fields relevant to plugins and the wizard.
959
+ * This is a stable subset of the compiler config that won't change between versions.
960
+ */
961
+ function toProjectConfig(validated) {
962
+ return {
963
+ rootDir: validated.rootDir,
964
+ srcDir: validated.srcDir,
965
+ namespace: validated.namespace,
966
+ fsNamespace: validated.fsNamespace,
967
+ outputTargets: validated.outputTargets ?? [],
968
+ globalScript: validated.globalScript,
969
+ globalStyle: validated.globalStyle,
970
+ compat: validated.compat,
971
+ signalBacking: validated.signalBacking
972
+ };
973
+ }
974
+ /**
975
+ * Builds a minimal ProjectConfig when no validated config is available (e.g. new project, no compiler).
976
+ * @param rootDir The root directory of the project.
977
+ * @param overrides Optional fields to override the defaults.
978
+ * @returns A ProjectConfig with reasonable defaults for a new project.
979
+ * */
980
+ function defaultProjectConfig(rootDir, overrides) {
981
+ const namespace = overrides?.namespace ?? "";
982
+ return {
983
+ rootDir,
984
+ srcDir: join(rootDir, "src"),
985
+ namespace,
986
+ fsNamespace: overrides?.fsNamespace ?? namespace.toLowerCase(),
987
+ outputTargets: [],
988
+ ...overrides
989
+ };
990
+ }
991
+ /**
992
+ * Walk up from `startDir` looking for a monorepo workspace root — a directory
993
+ * containing `pnpm-workspace.yaml` or a `package.json` with a `workspaces` field.
994
+ * Stops at the home directory or filesystem root. Returns `undefined` if none found.
995
+ * @param startDir The directory to start searching from.
996
+ * @returns A promise that resolves to the workspace root directory, or undefined if none found.
997
+ */
998
+ async function detectWorkspaceRoot(startDir) {
999
+ const home = homedir();
1000
+ let dir = startDir;
1001
+ while (true) {
1002
+ if (existsSync(join(dir, "pnpm-workspace.yaml"))) return dir;
1003
+ try {
1004
+ const pkg = JSON.parse(await readFile(join(dir, "package.json"), "utf8"));
1005
+ if (Array.isArray(pkg.workspaces)) return dir;
1006
+ } catch {}
1007
+ const parent = dirname(dir);
1008
+ if (parent === dir || dir === home) return void 0;
1009
+ dir = parent;
1010
+ }
1011
+ }
1012
+ /**
1013
+ * Returns true if the directory looks like an existing Stencil project:
1014
+ * - has an explicit `stencil.config.ts`, OR
1015
+ * - has `.tsx` files under `src/` (zero-config project).
1016
+ * @param dir The directory to check for an existing Stencil project.
1017
+ * @returns A promise that resolves to true if the directory looks like an existing Stencil project, false otherwise.
1018
+ */
1019
+ async function isExistingStencilProject(dir) {
1020
+ if (existsSync(join(dir, "stencil.config.ts"))) return true;
1021
+ try {
1022
+ return (await readdir(join(dir, "src"), {
1023
+ recursive: true,
1024
+ withFileTypes: true
1025
+ })).some((e) => e.isFile() && e.name.endsWith(".tsx"));
1026
+ } catch {
1027
+ return false;
1028
+ }
1029
+ }
1030
+ //#endregion
1031
+ //#region src/wizard/splash.ts
1032
+ const CLI_VERSION = "5.0.0-alpha.12";
1033
+ const isTTY = process.stdout.isTTY;
1034
+ const noColor = !isTTY || "NO_COLOR" in process.env;
1035
+ const RESET = noColor ? "" : "\x1B[0m";
1036
+ const BOLD = noColor ? "" : "\x1B[1m";
1037
+ const DIM = noColor ? "" : "\x1B[2m";
1038
+ const BLUE = noColor ? "" : "\x1B[38;2;60;44;255m";
1039
+ const RAW = `\
1040
+ .............
1041
+ ...................
1042
+ .........................
1043
+ ..............................
1044
+ .................................
1045
+ ..............████████████.........
1046
+ .............████████████............
1047
+ ............████████████...............
1048
+ ...........*************.................
1049
+ .........████████████████████████████....
1050
+ .......████████████████████████████......
1051
+ .....████████████████████████████........
1052
+ ...████████████████████████████..........
1053
+ ................*************............
1054
+ ..............████████████.............
1055
+ ............████████████..............
1056
+ .........████████████...............
1057
+ .................................
1058
+ ..............................
1059
+ ..........................
1060
+ ......................
1061
+ ................`;
1062
+ function colorize(raw) {
1063
+ if (noColor) return raw;
1064
+ let out = "";
1065
+ let style = "";
1066
+ for (const ch of raw) {
1067
+ const next = ".*".includes(ch) ? BLUE : "";
1068
+ if (next !== style) {
1069
+ if (style) out += RESET;
1070
+ if (next) out += next;
1071
+ style = next;
1072
+ }
1073
+ out += ch;
1074
+ }
1075
+ return style ? out + RESET : out;
1076
+ }
1077
+ const SPLASH = colorize(RAW);
1078
+ function printSplash() {
1079
+ if (!isTTY) return;
1080
+ const header = ` ${BOLD}Stencil${RESET} ${BLUE}v${CLI_VERSION}${RESET}`;
1081
+ const tagline = ` ${DIM}The Custom Element Compiler${RESET}`;
1082
+ process.stdout.write(`\n${SPLASH}\n\n${header}\n${tagline}\n\n`);
1083
+ }
1084
+ //#endregion
1085
+ //#region src/task-add.ts
1086
+ async function getInstalledPackageNames(rootDir) {
1087
+ try {
1088
+ const pkg = JSON.parse(await readFile(join(rootDir, "package.json"), "utf8"));
1089
+ const keys = (v) => Object.keys(v !== null && typeof v === "object" ? v : {});
1090
+ return new Set([...keys(pkg.dependencies), ...keys(pkg.devDependencies)]);
1091
+ } catch {
1092
+ return /* @__PURE__ */ new Set();
1093
+ }
1094
+ }
1095
+ async function selectInteractive(cwd) {
1096
+ const discovered = await discoverPlugins(cwd);
1097
+ const installed = await getInstalledPackageNames(cwd);
1098
+ const installable = KNOWN_INTEGRATIONS.filter((i) => !installed.has(i.package));
1099
+ const configurable = discovered.filter((d) => d.plugin.init != null);
1100
+ let toInstall = [];
1101
+ let toConfigure = [];
1102
+ if (installable.length > 0 || configurable.length > 0) {
1103
+ const result = await promptAddCapabilities(installable, configurable);
1104
+ toInstall = result.toInstall;
1105
+ toConfigure = result.toConfigure;
1106
+ } else p.log.info("All known integrations are already installed.");
1107
+ const customPackages = await promptCustomPackages();
1108
+ return {
1109
+ packagesToInstall: [...toInstall.map((i) => i.package), ...customPackages],
1110
+ pluginsToReconfigure: toConfigure
1111
+ };
1112
+ }
1113
+ async function taskAdd(packages, strictConfig) {
1114
+ const cwd = process.cwd();
1115
+ printSplash();
1116
+ p.intro("stencil add");
1117
+ if (isCI) {
1118
+ p.log.warn("Running in CI - non-interactive mode is not yet supported for `stencil add`.");
1119
+ process.exit(1);
1120
+ }
1121
+ let packagesToInstall = packages;
1122
+ let pluginsToReconfigure = [];
1123
+ if (packages.length === 0) ({packagesToInstall, pluginsToReconfigure} = await selectInteractive(cwd));
1124
+ if (packagesToInstall.length === 0 && pluginsToReconfigure.length === 0) {
1125
+ p.outro("Nothing to do.");
1126
+ return;
1127
+ }
1128
+ 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}`);
1129
+ else {
1130
+ const s = p.spinner();
1131
+ s.start(`Installing ${packagesToInstall.join(", ")}`);
1132
+ await addDevDependency(packagesToInstall, {
1133
+ cwd,
1134
+ silent: true
1135
+ });
1136
+ s.stop("Installed");
1137
+ }
1138
+ const context = {
1139
+ isNewProject: false,
1140
+ prompts: p,
1141
+ nypm,
1142
+ config: strictConfig ? toProjectConfig(strictConfig) : defaultProjectConfig(cwd),
1143
+ workspaceRoot: await detectWorkspaceRoot(cwd)
1144
+ };
1145
+ if (packagesToInstall.length > 0) {
1146
+ const discovered = await discoverPlugins(cwd);
1147
+ const installedSet = new Set(packagesToInstall);
1148
+ for (const d of discovered) if (installedSet.has(d.packageName) && d.plugin.init?.run) await d.plugin.init.run(context);
1149
+ }
1150
+ for (const d of pluginsToReconfigure) if (d.plugin.init?.run) await d.plugin.init.run(context);
1151
+ p.outro("Done!");
1152
+ }
1153
+ //#endregion
1154
+ //#region src/check-version.ts
1155
+ /**
1156
+ * Retrieve a reference to the active `CompilerSystem`'s `checkVersion` function
1157
+ * @param config the Stencil configuration associated with the currently compiled project
1158
+ * @param currentVersion the Stencil compiler's version string
1159
+ * @param flags the CLI flags (owned by CLI, not part of core config)
1160
+ * @returns a reference to `checkVersion`, or `null` if one does not exist on the current `CompilerSystem`
1161
+ */
1162
+ const startCheckVersion = async (config, currentVersion, flags) => {
1163
+ if (config.devMode && !flags.ci && !currentVersion.includes("-dev.") && isFunction(config.sys.checkVersion)) return config.sys.checkVersion(config.logger, currentVersion);
1164
+ return null;
1165
+ };
1166
+ /**
1167
+ * Print the results of running the provided `versionChecker`.
1168
+ *
1169
+ * Does not print if no `versionChecker` is provided.
1170
+ *
1171
+ * @param versionChecker the function to invoke.
1172
+ */
1173
+ const printCheckVersionResults = async (versionChecker) => {
1174
+ if (versionChecker) {
1175
+ const checkVersionResults = await versionChecker;
1176
+ if (isFunction(checkVersionResults)) checkVersionResults();
1177
+ }
1178
+ };
1179
+ //#endregion
1180
+ //#region src/migrations/rules/build-dist-docs.ts
1181
+ /**
1182
+ * Migration rule for buildDist and buildDocs removal.
1183
+ *
1184
+ * In Stencil v5, these global config options are replaced with per-output-target
1185
+ * `skipInDev` property. This migration:
1186
+ * - Detects `buildDist` or `buildDocs` in stencil.config.ts
1187
+ * - Removes the property
1188
+ * - For `buildDist: true` or `buildDocs: true`, adds `skipInDev: false` to relevant output targets
1189
+ */
1190
+ const buildDistDocsRule = {
1191
+ id: "build-dist-docs",
1192
+ name: "buildDist/buildDocs Removal",
1193
+ description: "Remove deprecated buildDist and buildDocs config options",
1194
+ fromVersion: "4.x",
1195
+ toVersion: "5.x",
1196
+ detect(sourceFile) {
1197
+ const matches = [];
1198
+ const visit = (node) => {
1199
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name)) {
1200
+ const propName = node.name.text;
1201
+ if (propName === "buildDist" || propName === "buildDocs") {
1202
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
1203
+ const isTrue = node.initializer.kind === ts.SyntaxKind.TrueKeyword;
1204
+ matches.push({
1205
+ node,
1206
+ message: `Deprecated '${propName}' found${isTrue ? " (set to true)" : ""} - will be removed and skipInDev added to output targets`,
1207
+ line: line + 1,
1208
+ column: character + 1
1209
+ });
1210
+ }
1211
+ }
1212
+ ts.forEachChild(node, visit);
1213
+ };
1214
+ visit(sourceFile);
1215
+ return matches;
1216
+ },
1217
+ transform(sourceFile, matches) {
1218
+ if (matches.length === 0) return sourceFile.getFullText();
1219
+ let text = sourceFile.getFullText();
1220
+ const targetTypesNeedingSkipInDev = [];
1221
+ for (const match of matches) {
1222
+ const prop = match.node;
1223
+ const propName = prop.name.text;
1224
+ if (prop.initializer.kind === ts.SyntaxKind.TrueKeyword) {
1225
+ if (propName === "buildDist") targetTypesNeedingSkipInDev.push("dist", "dist-custom-elements", "dist-hydrate-script", "loader-bundle", "standalone", "ssr");
1226
+ else if (propName === "buildDocs") targetTypesNeedingSkipInDev.push("docs-readme", "docs-json", "docs-custom", "docs-vscode", "docs-custom-elements-manifest");
1227
+ }
1228
+ }
1229
+ const outputTargetsToModify = [];
1230
+ const findOutputTargets = (node) => {
1231
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === "outputTargets" && ts.isArrayLiteralExpression(node.initializer)) {
1232
+ for (const element of node.initializer.elements) if (ts.isObjectLiteralExpression(element)) {
1233
+ const typeProp = element.properties.find((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "type");
1234
+ if (typeProp && ts.isStringLiteral(typeProp.initializer)) {
1235
+ const targetType = typeProp.initializer.text;
1236
+ if (targetTypesNeedingSkipInDev.includes(targetType)) {
1237
+ if (!element.properties.some((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "skipInDev")) outputTargetsToModify.push(element);
1238
+ }
1239
+ }
1240
+ }
1241
+ }
1242
+ ts.forEachChild(node, findOutputTargets);
1243
+ };
1244
+ findOutputTargets(sourceFile);
1245
+ const allModifications = [];
1246
+ for (const match of matches) {
1247
+ const prop = match.node;
1248
+ const start = prop.getStart();
1249
+ let end = prop.getEnd();
1250
+ const afterProp = text.slice(end).match(/^\s*,/);
1251
+ if (afterProp) end = end + afterProp[0].length;
1252
+ allModifications.push({
1253
+ type: "remove",
1254
+ start,
1255
+ end,
1256
+ node: prop
1257
+ });
1258
+ }
1259
+ for (const target of outputTargetsToModify) {
1260
+ const lastProp = target.properties[target.properties.length - 1];
1261
+ if (lastProp) allModifications.push({
1262
+ type: "addSkipInDev",
1263
+ start: lastProp.getEnd(),
1264
+ end: lastProp.getEnd(),
1265
+ node: target
1266
+ });
1267
+ }
1268
+ allModifications.sort((a, b) => b.start - a.start);
1269
+ for (const mod of allModifications) if (mod.type === "remove") text = text.slice(0, mod.start) + text.slice(mod.end);
1270
+ else if (mod.type === "addSkipInDev") {
1271
+ const firstProp = mod.node.properties[0];
1272
+ let indent = " ";
1273
+ if (firstProp) {
1274
+ const propStart = firstProp.getStart();
1275
+ const lineStart = text.lastIndexOf("\n", propStart) + 1;
1276
+ const leadingWhitespace = text.slice(lineStart, propStart);
1277
+ if (/^\s+$/.test(leadingWhitespace)) indent = leadingWhitespace;
1278
+ }
1279
+ const afterLastProp = text.slice(mod.start).match(/^(\s*,)?/);
1280
+ const skipLength = afterLastProp && afterLastProp[1] ? afterLastProp[0].length : 0;
1281
+ text = text.slice(0, mod.start) + `,\n${indent}skipInDev: false,` + text.slice(mod.start + skipLength);
1282
+ }
1283
+ text = text.replace(/,\s*\n\s*\n/g, ",\n");
1284
+ text = text.replace(/{\s*\n\s*\n/g, "{\n");
1285
+ return text;
1286
+ }
1287
+ };
1288
+ //#endregion
1289
+ //#region src/migrations/rules/dev-mode.ts
1290
+ /**
1291
+ * Migration rule for `devMode` config option removal.
1292
+ *
1293
+ * In Stencil v5, `devMode` is no longer a user-settable config option in `stencil.config.ts`.
1294
+ * Build mode is controlled exclusively by the `--dev` CLI flag (default is production).
1295
+ * This migration removes `devMode` from the config object.
1296
+ */
1297
+ const devModeRule = {
1298
+ id: "dev-mode",
1299
+ name: "devMode Config Removal",
1300
+ description: "Remove deprecated devMode config option - use --dev CLI flag instead",
1301
+ fromVersion: "4.x",
1302
+ toVersion: "5.x",
1303
+ detect(sourceFile) {
1304
+ const matches = [];
1305
+ const visit = (node) => {
1306
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name)) {
1307
+ if (node.name.text === "devMode") {
1308
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
1309
+ matches.push({
1310
+ node,
1311
+ message: `Deprecated 'devMode' config option found - build mode is now set via the --dev CLI flag (production is the default)`,
1312
+ line: line + 1,
1313
+ column: character + 1
1314
+ });
1315
+ }
1316
+ }
1317
+ ts.forEachChild(node, visit);
1318
+ };
1319
+ visit(sourceFile);
1320
+ return matches;
1321
+ },
1322
+ transform(sourceFile, matches) {
1323
+ if (matches.length === 0) return sourceFile.getFullText();
1324
+ let text = sourceFile.getFullText();
1325
+ for (const match of [...matches].reverse()) {
1326
+ const node = match.node;
1327
+ const start = node.getFullStart();
1328
+ const end = node.getEnd();
1329
+ let removeEnd = end;
1330
+ const trailingComma = text.slice(end).match(/^\s*,/);
1331
+ if (trailingComma) removeEnd = end + trailingComma[0].length;
1332
+ text = text.slice(0, start) + text.slice(removeEnd);
1333
+ }
1334
+ return text;
1335
+ }
1336
+ };
1337
+ //#endregion
1338
+ //#region src/migrations/rules/encapsulation-api.ts
1339
+ /**
1340
+ * Migration rule for the @Component encapsulation API change.
1341
+ *
1342
+ * Migrates:
1343
+ * - `shadow: true` → `encapsulation: { type: 'shadow' }`
1344
+ * - `shadow: { delegatesFocus: true }` → `encapsulation: { type: 'shadow', delegatesFocus: true }`
1345
+ * - `scoped: true` → `encapsulation: { type: 'scoped' }`
1346
+ */
1347
+ const encapsulationApiRule = {
1348
+ id: "encapsulation-api",
1349
+ name: "Encapsulation API",
1350
+ description: "Migrate shadow/scoped properties to new encapsulation API",
1351
+ fromVersion: "4.x",
1352
+ toVersion: "5.x",
1353
+ detect(sourceFile) {
1354
+ const matches = [];
1355
+ const importMap = getStencilCoreImportMap(sourceFile);
1356
+ const visit = (node) => {
1357
+ if (ts.isDecorator(node) && ts.isCallExpression(node.expression)) {
1358
+ const decoratorName = node.expression.expression;
1359
+ if (ts.isIdentifier(decoratorName) && isStencilDecorator(decoratorName.text, "Component", importMap)) {
1360
+ const [arg] = node.expression.arguments;
1361
+ if (arg && ts.isObjectLiteralExpression(arg)) {
1362
+ for (const prop of arg.properties) if (ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.name)) {
1363
+ const propName = prop.name.text;
1364
+ if (propName === "shadow" || propName === "scoped") {
1365
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(prop.getStart());
1366
+ matches.push({
1367
+ node: prop,
1368
+ message: `Deprecated '${propName}' property found - migrate to 'encapsulation' API`,
1369
+ line: line + 1,
1370
+ column: character + 1
1371
+ });
1372
+ }
1373
+ }
1374
+ }
1375
+ }
1376
+ }
1377
+ ts.forEachChild(node, visit);
1378
+ };
1379
+ visit(sourceFile);
1380
+ return matches;
1381
+ },
1382
+ transform(sourceFile, matches) {
1383
+ if (matches.length === 0) return sourceFile.getFullText();
1384
+ let text = sourceFile.getFullText();
1385
+ const sortedMatches = [...matches].sort((a, b) => {
1386
+ const posA = a.node.getStart();
1387
+ return b.node.getStart() - posA;
1388
+ });
1389
+ for (const match of sortedMatches) {
1390
+ const prop = match.node;
1391
+ const propName = prop.name.text;
1392
+ const start = prop.getStart();
1393
+ const end = prop.getEnd();
1394
+ let replacement;
1395
+ if (propName === "shadow") if (prop.initializer.kind === ts.SyntaxKind.TrueKeyword) replacement = "encapsulation: { type: 'shadow' }";
1396
+ else if (ts.isObjectLiteralExpression(prop.initializer)) {
1397
+ const options = [];
1398
+ for (const innerProp of prop.initializer.properties) if (ts.isPropertyAssignment(innerProp) && ts.isIdentifier(innerProp.name)) {
1399
+ const optName = innerProp.name.text;
1400
+ const optValue = innerProp.initializer.getText();
1401
+ options.push(`${optName}: ${optValue}`);
1402
+ }
1403
+ if (options.length > 0) replacement = `encapsulation: { type: 'shadow', ${options.join(", ")} }`;
1404
+ else replacement = "encapsulation: { type: 'shadow' }";
1405
+ } else replacement = "";
1406
+ else if (propName === "scoped") if (prop.initializer.kind === ts.SyntaxKind.TrueKeyword) replacement = "encapsulation: { type: 'scoped' }";
1407
+ else replacement = "";
1408
+ else continue;
1409
+ let endPos = end;
1410
+ const afterProp = text.slice(end).match(/^\s*,/);
1411
+ if (afterProp && replacement === "") endPos = end + afterProp[0].length;
1412
+ else if (afterProp && replacement !== "") {} else if (!afterProp && replacement !== "") {}
1413
+ text = text.slice(0, start) + replacement + text.slice(endPos);
1414
+ }
1415
+ return text;
1416
+ }
1417
+ };
1418
+ //#endregion
1419
+ //#region src/migrations/rules/external-runtime.ts
1420
+ /**
1421
+ * Migration rule for `externalRuntime` on `standalone` output targets.
1422
+ *
1423
+ * In Stencil v5, `externalRuntime` defaults to `false` (was `true` in v4).
1424
+ * Explicit `externalRuntime: false` is now redundant and can be removed.
1425
+ */
1426
+ const externalRuntimeRule = {
1427
+ id: "external-runtime",
1428
+ name: "externalRuntime Default Change",
1429
+ description: "Remove redundant 'externalRuntime: false' from standalone output targets - false is now the default",
1430
+ fromVersion: "4.x",
1431
+ toVersion: "5.x",
1432
+ detect(sourceFile) {
1433
+ const matches = [];
1434
+ const visit = (node) => {
1435
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === "externalRuntime" && node.initializer.kind === ts.SyntaxKind.FalseKeyword) {
1436
+ const parent = node.parent;
1437
+ if (ts.isObjectLiteralExpression(parent)) {
1438
+ if (parent.properties.some((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "type" && ts.isStringLiteral(p.initializer) && p.initializer.text === "standalone")) {
1439
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
1440
+ matches.push({
1441
+ node,
1442
+ message: "'externalRuntime: false' is now the default - this property can be removed",
1443
+ line: line + 1,
1444
+ column: character + 1
1445
+ });
1446
+ }
1447
+ }
1448
+ }
1449
+ ts.forEachChild(node, visit);
1450
+ };
1451
+ visit(sourceFile);
1452
+ return matches;
1453
+ },
1454
+ transform(sourceFile, matches) {
1455
+ if (matches.length === 0) return sourceFile.getFullText();
1456
+ let text = sourceFile.getFullText();
1457
+ for (const match of [...matches].reverse()) {
1458
+ const node = match.node;
1459
+ const start = node.getFullStart();
1460
+ const end = node.getEnd();
1461
+ let removeEnd = end;
1462
+ const trailingComma = text.slice(end).match(/^\s*,/);
1463
+ if (trailingComma) removeEnd = end + trailingComma[0].length;
1464
+ text = text.slice(0, start) + text.slice(removeEnd);
1465
+ }
1466
+ return text;
1467
+ }
1468
+ };
1469
+ //#endregion
1470
+ //#region src/migrations/rules/extras-to-compat.ts
1471
+ /**
1472
+ * Migration rule: rename the top-level `extras` config key to `compat`.
1473
+ *
1474
+ * In v5, `extras` is replaced by `compat` (framework/bundler compatibility flags).
1475
+ */
1476
+ const extrasToCompatRule = {
1477
+ id: "extras-to-compat",
1478
+ name: "Extras → Compat Rename",
1479
+ description: "Rename top-level 'extras' config key to 'compat'",
1480
+ fromVersion: "4.x",
1481
+ toVersion: "5.x",
1482
+ detect(sourceFile) {
1483
+ const matches = [];
1484
+ const visit = (node) => {
1485
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name)) {
1486
+ if (node.name.text === "extras") {
1487
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
1488
+ matches.push({
1489
+ node,
1490
+ message: "'extras' has been renamed to 'compat'",
1491
+ line: line + 1,
1492
+ column: character + 1
1493
+ });
1494
+ }
1495
+ }
1496
+ ts.forEachChild(node, visit);
1497
+ };
1498
+ visit(sourceFile);
1499
+ return matches;
1500
+ },
1501
+ transform(sourceFile, matches) {
1502
+ if (matches.length === 0) return sourceFile.getFullText();
1503
+ let text = sourceFile.getFullText();
1504
+ const sorted = [...matches].sort((a, b) => b.node.getStart() - a.node.getStart());
1505
+ for (const match of sorted) {
1506
+ const node = match.node;
1507
+ if (node.name.text === "extras") {
1508
+ const keyStart = node.name.getStart();
1509
+ const keyEnd = node.name.getEnd();
1510
+ text = text.slice(0, keyStart) + "compat" + text.slice(keyEnd);
1511
+ }
1512
+ }
1513
+ return text;
1514
+ }
1515
+ };
1516
+ //#endregion
1517
+ //#region src/migrations/rules/form-associated.ts
1518
+ /**
1519
+ * Migration rule for formAssociated → @AttachInternals.
1520
+ *
1521
+ * Migrates:
1522
+ * - `formAssociated: true` in @Component → Adds `@AttachInternals() internals: ElementInternals;`
1523
+ */
1524
+ const formAssociatedRule = {
1525
+ id: "form-associated",
1526
+ name: "Form Associated",
1527
+ description: "Migrate formAssociated to @AttachInternals decorator",
1528
+ fromVersion: "4.x",
1529
+ toVersion: "5.x",
1530
+ detect(sourceFile) {
1531
+ const matches = [];
1532
+ const importMap = getStencilCoreImportMap(sourceFile);
1533
+ let hasAttachInternalsImport = false;
1534
+ let stencilImportEnd = 0;
1535
+ for (const statement of sourceFile.statements) if (ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier) && statement.moduleSpecifier.text === "@stencil/core") {
1536
+ stencilImportEnd = statement.getEnd();
1537
+ for (const [, originalName] of importMap) if (originalName === "AttachInternals") {
1538
+ hasAttachInternalsImport = true;
1539
+ break;
1540
+ }
1541
+ break;
1542
+ }
1543
+ const visit = (node) => {
1544
+ if (ts.isClassDeclaration(node)) {
1545
+ const decorators = ts.getDecorators(node);
1546
+ if (!decorators) {
1547
+ ts.forEachChild(node, visit);
1548
+ return;
1549
+ }
1550
+ let componentDecorator;
1551
+ let formAssociatedProp;
1552
+ for (const decorator of decorators) if (ts.isCallExpression(decorator.expression) && ts.isIdentifier(decorator.expression.expression) && isStencilDecorator(decorator.expression.expression.text, "Component", importMap)) {
1553
+ componentDecorator = decorator;
1554
+ const [arg] = decorator.expression.arguments;
1555
+ if (arg && ts.isObjectLiteralExpression(arg)) {
1556
+ for (const prop of arg.properties) if (ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.name) && prop.name.text === "formAssociated") {
1557
+ formAssociatedProp = prop;
1558
+ break;
1559
+ }
1560
+ }
1561
+ break;
1562
+ }
1563
+ if (componentDecorator && formAssociatedProp) {
1564
+ let hasAttachInternals = false;
1565
+ for (const member of node.members) if (ts.isPropertyDeclaration(member) || ts.isMethodDeclaration(member)) {
1566
+ const memberDecorators = ts.getDecorators(member);
1567
+ if (memberDecorators) {
1568
+ for (const d of memberDecorators) if (ts.isCallExpression(d.expression) && ts.isIdentifier(d.expression.expression) && isStencilDecorator(d.expression.expression.text, "AttachInternals", importMap)) {
1569
+ hasAttachInternals = true;
1570
+ break;
1571
+ }
1572
+ }
1573
+ }
1574
+ let searchStart = node.name ? node.name.getEnd() : node.getStart(sourceFile);
1575
+ if (node.heritageClauses) for (const clause of node.heritageClauses) searchStart = Math.max(searchStart, clause.getEnd());
1576
+ const braceMatch = sourceFile.getFullText().slice(searchStart).match(/\s*\{/);
1577
+ if (!braceMatch) {
1578
+ ts.forEachChild(node, visit);
1579
+ return;
1580
+ }
1581
+ const classBodyStart = searchStart + braceMatch[0].length;
1582
+ let indent = " ";
1583
+ if (node.members.length > 0) {
1584
+ const memberStart = node.members[0].getStart(sourceFile);
1585
+ const indentMatch = sourceFile.getFullText().slice(classBodyStart, memberStart).match(/\n(\s+)/);
1586
+ if (indentMatch) indent = indentMatch[1];
1587
+ }
1588
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(formAssociatedProp.getStart());
1589
+ matches.push({
1590
+ node: formAssociatedProp,
1591
+ message: hasAttachInternals ? "Remove 'formAssociated' (already has @AttachInternals)" : "Migrate 'formAssociated' to @AttachInternals decorator",
1592
+ line: line + 1,
1593
+ column: character + 1,
1594
+ classBodyStart,
1595
+ hasAttachInternals,
1596
+ indent,
1597
+ needsImport: !hasAttachInternalsImport && !hasAttachInternals,
1598
+ stencilImportEnd
1599
+ });
1600
+ }
1601
+ }
1602
+ ts.forEachChild(node, visit);
1603
+ };
1604
+ visit(sourceFile);
1605
+ return matches;
1606
+ },
1607
+ transform(sourceFile, matches) {
1608
+ if (matches.length === 0) return sourceFile.getFullText();
1609
+ let text = sourceFile.getFullText();
1610
+ const typedMatches = matches;
1611
+ const sortedMatches = [...typedMatches].sort((a, b) => {
1612
+ return b.classBodyStart - a.classBodyStart;
1613
+ });
1614
+ for (const match of sortedMatches) {
1615
+ if (!match.hasAttachInternals) {
1616
+ const newMember = `\n${match.indent}@AttachInternals() internals: ElementInternals;\n`;
1617
+ text = text.slice(0, match.classBodyStart) + newMember + text.slice(match.classBodyStart);
1618
+ }
1619
+ const prop = match.node;
1620
+ const start = prop.getStart();
1621
+ let end = prop.getEnd();
1622
+ const afterProp = text.slice(end).match(/^\s*,/);
1623
+ if (afterProp) end = end + afterProp[0].length;
1624
+ text = text.slice(0, start) + text.slice(end);
1625
+ }
1626
+ const firstMatch = typedMatches[0];
1627
+ if (firstMatch?.needsImport && firstMatch.stencilImportEnd > 0) {
1628
+ const importMatch = text.match(/import\s*\{([^}]*)\}\s*from\s*['"]@stencil\/core['"]/);
1629
+ if (importMatch) {
1630
+ const newImports = importMatch[1].trimEnd() + ", AttachInternals";
1631
+ text = text.replace(importMatch[0], `import {${newImports}} from '@stencil/core'`);
1632
+ }
1633
+ }
1634
+ return text;
1635
+ }
1636
+ };
1637
+ //#endregion
1638
+ //#region src/migrations/rules/global-style-inject.ts
1639
+ /**
1640
+ * Migration rule for `extras.addGlobalStyleToComponents` → `global-style` output target `inject`.
1641
+ *
1642
+ * In v5, the `addGlobalStyleToComponents` extras option is removed. Instead, configure
1643
+ * the `inject` option on the `global-style` output target.
1644
+ *
1645
+ * Migration mapping:
1646
+ * - `addGlobalStyleToComponents: true` → `inject: 'all'`
1647
+ * - `addGlobalStyleToComponents: 'client'` → `inject: 'client'`
1648
+ * - `addGlobalStyleToComponents: false` → omit (default is 'none')
1649
+ *
1650
+ * Note: This migration only acts on explicitly set `addGlobalStyleToComponents`.
1651
+ * Users who relied on the implicit v4 default ('client') will need to manually
1652
+ * add `inject: 'client'` to their global-style output target if desired.
1653
+ */
1654
+ const globalStyleInjectRule = {
1655
+ id: "global-style-inject",
1656
+ name: "Global Style Inject Migration",
1657
+ description: "Migrate extras.addGlobalStyleToComponents to global-style output target inject option",
1658
+ fromVersion: "4.x",
1659
+ toVersion: "5.x",
1660
+ detect(sourceFile) {
1661
+ const matches = [];
1662
+ const visit = (node) => {
1663
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === "addGlobalStyleToComponents") {
1664
+ const parent = node.parent;
1665
+ if (ts.isObjectLiteralExpression(parent)) {
1666
+ const grandparent = parent.parent;
1667
+ if (ts.isPropertyAssignment(grandparent) && ts.isIdentifier(grandparent.name) && grandparent.name.text === "extras") {
1668
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
1669
+ matches.push({
1670
+ node,
1671
+ message: `extras.addGlobalStyleToComponents is removed. Use 'inject' on global-style output target instead.`,
1672
+ line: line + 1,
1673
+ column: character + 1
1674
+ });
1675
+ }
1676
+ }
1677
+ }
1678
+ ts.forEachChild(node, visit);
1679
+ };
1680
+ visit(sourceFile);
1681
+ return matches;
1682
+ },
1683
+ transform(sourceFile, matches) {
1684
+ if (matches.length === 0) return sourceFile.getFullText();
1685
+ let text = sourceFile.getFullText();
1686
+ const matchNode = matches[0].node;
1687
+ if (!ts.isPropertyAssignment(matchNode)) return text;
1688
+ let injectValue = null;
1689
+ if (matchNode.initializer.kind === ts.SyntaxKind.TrueKeyword) injectValue = "all";
1690
+ else if (ts.isStringLiteral(matchNode.initializer) && matchNode.initializer.text === "client") injectValue = "client";
1691
+ let insertionOffset = 0;
1692
+ if (injectValue) {
1693
+ const result = addGlobalStyleOutputTarget(text, sourceFile, injectValue);
1694
+ insertionOffset = result.length - text.length;
1695
+ text = result;
1696
+ }
1697
+ let start = matchNode.getStart();
1698
+ let end = matchNode.getEnd();
1699
+ const outputTargetsEnd = findOutputTargetsEnd(sourceFile);
1700
+ if (insertionOffset !== 0 && outputTargetsEnd !== null && matchNode.getStart() > outputTargetsEnd) {
1701
+ start += insertionOffset;
1702
+ end += insertionOffset;
1703
+ }
1704
+ const afterProp = text.slice(end).match(/^\s*,/);
1705
+ if (afterProp) end = end + afterProp[0].length;
1706
+ else {
1707
+ const beforeProp = text.slice(0, start).match(/,\s*$/);
1708
+ if (beforeProp) {
1709
+ text = text.slice(0, start - beforeProp[0].length) + text.slice(end);
1710
+ end = -1;
1711
+ }
1712
+ }
1713
+ if (end !== -1) text = text.slice(0, start) + text.slice(end);
1714
+ text = cleanupEmptyExtras$1(text);
1715
+ return text;
1716
+ }
1717
+ };
1718
+ /**
1719
+ * Find the end position of the outputTargets array in the source file.
1720
+ * @param sourceFile The source file to search
1721
+ * @returns The end position of the outputTargets array, or null if not found
1722
+ */
1723
+ function findOutputTargetsEnd(sourceFile) {
1724
+ let endPos = null;
1725
+ const visit = (node) => {
1726
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === "outputTargets") endPos = node.getEnd();
1727
+ ts.forEachChild(node, visit);
1728
+ };
1729
+ visit(sourceFile);
1730
+ return endPos;
1731
+ }
1732
+ /**
1733
+ * Clean up empty extras object after removing addGlobalStyleToComponents.
1734
+ * @param text The source text to clean up
1735
+ * @returns The cleaned up text with empty extras removed
1736
+ */
1737
+ function cleanupEmptyExtras$1(text) {
1738
+ return text.replace(/,?\s*extras\s*:\s*\{\s*\},?/g, "");
1739
+ }
1740
+ /**
1741
+ * Add a global-style output target with the specified inject value.
1742
+ * @param text The source text to modify
1743
+ * @param sourceFile The source file for position info
1744
+ * @param injectValue The inject value to set on the new global-style output target
1745
+ * @returns The modified text with the new global-style output target added
1746
+ */
1747
+ function addGlobalStyleOutputTarget(text, sourceFile, injectValue) {
1748
+ if (text.includes("type: 'global-style'")) return text;
1749
+ let outputTargetsArray = null;
1750
+ const findOutputTargets = (node) => {
1751
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === "outputTargets" && ts.isArrayLiteralExpression(node.initializer)) outputTargetsArray = node.initializer;
1752
+ ts.forEachChild(node, findOutputTargets);
1753
+ };
1754
+ findOutputTargets(sourceFile);
1755
+ if (!outputTargetsArray) return text;
1756
+ const array = outputTargetsArray;
1757
+ let indent = " ";
1758
+ if (array.elements.length > 0) {
1759
+ const elemStart = array.elements[0].getStart();
1760
+ const lineStart = text.lastIndexOf("\n", elemStart) + 1;
1761
+ const leadingWhitespace = text.slice(lineStart, elemStart);
1762
+ if (/^\s+$/.test(leadingWhitespace)) indent = leadingWhitespace;
1763
+ }
1764
+ const lastElement = array.elements[array.elements.length - 1];
1765
+ if (!lastElement) {
1766
+ const arrayStart = array.getStart() + 1;
1767
+ const newTarget = `\n${indent}{\n${indent} type: 'global-style',\n${indent} inject: '${injectValue}',\n${indent}}\n${indent.slice(2)}`;
1768
+ return text.slice(0, arrayStart) + newTarget + text.slice(arrayStart);
1769
+ }
1770
+ let insertPos = lastElement.getEnd();
1771
+ const afterLastElement = text.slice(insertPos).match(/^(\s*,)?/);
1772
+ const hasTrailingComma = afterLastElement && afterLastElement[1];
1773
+ if (hasTrailingComma) insertPos += afterLastElement[0].length;
1774
+ const newTarget = `{\n${indent} type: 'global-style',\n${indent} inject: '${injectValue}',\n${indent}}`;
1775
+ const insertion = (hasTrailingComma ? "" : ",") + "\n" + indent + newTarget;
1776
+ return text.slice(0, insertPos) + insertion + text.slice(insertPos);
1777
+ }
1778
+ //#endregion
1779
+ //#region src/migrations/rules/hash-file-names.ts
1780
+ /**
1781
+ * Migration rule for `hashFileNames` and `hashedFileNameLength` config options.
1782
+ *
1783
+ * In Stencil v5, these are no longer top-level config options. They belong on
1784
+ * the `loader-bundle` and `www` output targets, which are the only outputs that
1785
+ * are served directly in the browser and benefit from content-hash caching.
1786
+ *
1787
+ * This migration:
1788
+ * 1. Removes them from the top-level config
1789
+ * 2. Injects them into any `loader-bundle` and `www` output targets found in the same file
1790
+ */
1791
+ const hashFileNamesRule = {
1792
+ id: "hash-file-names",
1793
+ name: "Hash File Names Config Move",
1794
+ description: "Move hashFileNames and hashedFileNameLength from top-level config to loader-bundle and www output targets",
1795
+ fromVersion: "4.x",
1796
+ toVersion: "5.x",
1797
+ detect(sourceFile) {
1798
+ const matches = [];
1799
+ const visit = (node) => {
1800
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && (node.name.text === "hashFileNames" || node.name.text === "hashedFileNameLength")) {
1801
+ const parent = node.parent;
1802
+ if (ts.isObjectLiteralExpression(parent)) {
1803
+ if (!parent.properties.some((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "type")) {
1804
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
1805
+ matches.push({
1806
+ node,
1807
+ message: `'${node.name.text}' is no longer a top-level config option. Move it to your 'loader-bundle' and/or 'www' output targets.`,
1808
+ line: line + 1,
1809
+ column: character + 1
1810
+ });
1811
+ }
1812
+ }
1813
+ }
1814
+ ts.forEachChild(node, visit);
1815
+ };
1816
+ visit(sourceFile);
1817
+ return matches;
1818
+ },
1819
+ transform(sourceFile, matches) {
1820
+ if (matches.length === 0) return sourceFile.getFullText();
1821
+ const fullText = sourceFile.getFullText();
1822
+ const propsToInject = matches.map((m) => {
1823
+ const node = m.node;
1824
+ return {
1825
+ name: node.name.text,
1826
+ value: node.initializer.getText(sourceFile)
1827
+ };
1828
+ });
1829
+ const TARGET_TYPES = new Set(["loader-bundle", "www"]);
1830
+ const insertionsByPos = /* @__PURE__ */ new Map();
1831
+ const visit = (node) => {
1832
+ if (ts.isObjectLiteralExpression(node)) {
1833
+ 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))) {
1834
+ const existingPropNames = new Set(node.properties.filter((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name)).map((p) => p.name.text));
1835
+ const objStart = node.getStart(sourceFile);
1836
+ const objLineStart = fullText.lastIndexOf("\n", objStart) + 1;
1837
+ const propIndent = (fullText.slice(objLineStart, objStart).match(/^(\s*)/)?.[1] ?? "") + " ";
1838
+ const closingBracePos = node.getEnd() - 1;
1839
+ const isMultiLine = fullText.slice(objStart, node.getEnd()).includes("\n");
1840
+ let insertPos;
1841
+ if (isMultiLine) insertPos = fullText.lastIndexOf("\n", closingBracePos - 1);
1842
+ else {
1843
+ insertPos = closingBracePos;
1844
+ while (insertPos > 0 && fullText[insertPos - 1] === " ") insertPos--;
1845
+ }
1846
+ const existing = insertionsByPos.get(insertPos) ?? [];
1847
+ for (const prop of propsToInject) if (!existingPropNames.has(prop.name)) existing.push(isMultiLine ? `\n${propIndent}${prop.name}: ${prop.value},` : `, ${prop.name}: ${prop.value}`);
1848
+ if (existing.length > 0) insertionsByPos.set(insertPos, existing);
1849
+ }
1850
+ }
1851
+ ts.forEachChild(node, visit);
1852
+ };
1853
+ visit(sourceFile);
1854
+ const edits = [];
1855
+ for (const match of matches) {
1856
+ const node = match.node;
1857
+ const start = node.getFullStart();
1858
+ const end = node.getEnd();
1859
+ let removeEnd = end;
1860
+ const trailingComma = fullText.slice(end).match(/^\s*,/);
1861
+ if (trailingComma) removeEnd = end + trailingComma[0].length;
1862
+ edits.push({
1863
+ start,
1864
+ end: removeEnd,
1865
+ replacement: ""
1866
+ });
1867
+ }
1868
+ for (const [pos, insertions] of insertionsByPos) edits.push({
1869
+ start: pos,
1870
+ end: pos,
1871
+ replacement: insertions.join("")
1872
+ });
1873
+ edits.sort((a, b) => b.start - a.start);
1874
+ let text = fullText;
1875
+ for (const edit of edits) text = text.slice(0, edit.start) + edit.replacement + text.slice(edit.end);
1876
+ return text;
1877
+ }
1878
+ };
1879
+ //#endregion
1880
+ //#region src/migrations/rules/light-dom-patches.ts
1881
+ /**
1882
+ * Migration rule for slot-fix extras → `lightDomPatches`.
1883
+ *
1884
+ * In v5, the individual slot-fix flags and `experimentalSlotFixes` umbrella are replaced
1885
+ * by a single `lightDomPatches` option which defaults to `true`.
1886
+ *
1887
+ * Migration mapping:
1888
+ * - `experimentalSlotFixes: true` → remove (new default is `true`)
1889
+ * - `experimentalSlotFixes: false` → `lightDomPatches: false`
1890
+ * - Individual flags only → `lightDomPatches: { <new names> }`
1891
+ *
1892
+ * Old → new individual key names:
1893
+ * appendChildSlotFix → domMutations
1894
+ * cloneNodeFix → cloneNode
1895
+ * scopedSlotTextContentFix → textContent
1896
+ * slotChildNodesFix → childNodes
1897
+ */
1898
+ const lightDomPatchesRule = {
1899
+ id: "light-dom-patches",
1900
+ name: "Light DOM Patches Migration",
1901
+ description: "Migrate experimentalSlotFixes / individual slot-fix flags to lightDomPatches",
1902
+ fromVersion: "4.x",
1903
+ toVersion: "5.x",
1904
+ detect(sourceFile) {
1905
+ const matches = [];
1906
+ const oldKeys = new Set([
1907
+ "experimentalSlotFixes",
1908
+ "appendChildSlotFix",
1909
+ "cloneNodeFix",
1910
+ "scopedSlotTextContentFix",
1911
+ "slotChildNodesFix"
1912
+ ]);
1913
+ const visit = (node) => {
1914
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && oldKeys.has(node.name.text)) {
1915
+ const parent = node.parent;
1916
+ if (ts.isObjectLiteralExpression(parent)) {
1917
+ const grandparent = parent.parent;
1918
+ if (ts.isPropertyAssignment(grandparent) && ts.isIdentifier(grandparent.name) && grandparent.name.text === "extras") {
1919
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
1920
+ matches.push({
1921
+ node,
1922
+ message: `extras.${node.name.text} is removed. Use 'extras.lightDomPatches' instead.`,
1923
+ line: line + 1,
1924
+ column: character + 1
1925
+ });
1926
+ }
1927
+ }
1928
+ }
1929
+ ts.forEachChild(node, visit);
1930
+ };
1931
+ visit(sourceFile);
1932
+ return matches;
1933
+ },
1934
+ transform(sourceFile, matches) {
1935
+ if (matches.length === 0) return sourceFile.getFullText();
1936
+ const oldKeyMap = {};
1937
+ for (const match of matches) {
1938
+ const node = match.node;
1939
+ const key = node.name.text;
1940
+ const init = node.initializer;
1941
+ oldKeyMap[key] = init.kind === ts.SyntaxKind.TrueKeyword ? true : init.kind === ts.SyntaxKind.FalseKeyword ? false : void 0;
1942
+ }
1943
+ const keyRename = {
1944
+ appendChildSlotFix: "domMutations",
1945
+ cloneNodeFix: "cloneNode",
1946
+ scopedSlotTextContentFix: "textContent",
1947
+ slotChildNodesFix: "childNodes"
1948
+ };
1949
+ const experimentalValue = oldKeyMap["experimentalSlotFixes"];
1950
+ const hasIndividualKeys = matches.some((m) => {
1951
+ return m.node.name.text !== "experimentalSlotFixes";
1952
+ });
1953
+ let replacement = null;
1954
+ if (experimentalValue === true && !hasIndividualKeys) replacement = null;
1955
+ else if (experimentalValue === false && !hasIndividualKeys) replacement = "lightDomPatches: false";
1956
+ else if (experimentalValue === true && hasIndividualKeys) replacement = null;
1957
+ else {
1958
+ const parts = [];
1959
+ for (const [oldKey, newKey] of Object.entries(keyRename)) {
1960
+ const val = oldKeyMap[oldKey];
1961
+ if (val === true) parts.push(`${newKey}: true`);
1962
+ else if (val === false) parts.push(`${newKey}: false`);
1963
+ }
1964
+ if (parts.length > 0) replacement = `lightDomPatches: { ${parts.join(", ")} }`;
1965
+ }
1966
+ const sorted = [...matches].sort((a, b) => b.node.getStart() - a.node.getStart());
1967
+ let text = sourceFile.getFullText();
1968
+ let replacementInserted = false;
1969
+ for (const match of sorted) {
1970
+ const node = match.node;
1971
+ let start = node.getStart();
1972
+ let end = node.getEnd();
1973
+ const trailingComma = text.slice(end).match(/^(\s*,)/);
1974
+ if (trailingComma) end += trailingComma[1].length;
1975
+ else {
1976
+ const leadingComma = text.slice(0, start).match(/,\s*$/);
1977
+ if (leadingComma) start -= leadingComma[0].length;
1978
+ }
1979
+ if (!replacementInserted && replacement !== null) {
1980
+ text = text.slice(0, start) + replacement + text.slice(end);
1981
+ replacementInserted = true;
1982
+ } else text = text.slice(0, start) + text.slice(end);
1983
+ }
1984
+ text = cleanupEmptyExtras(text);
1985
+ return text;
1986
+ }
1987
+ };
1988
+ function cleanupEmptyExtras(text) {
1989
+ return text.replace(/,?\s*extras\s*:\s*\{\s*\},?/g, "");
1990
+ }
1991
+ //#endregion
1992
+ //#region src/migrations/rules/output-target-renames.ts
1993
+ /**
1994
+ * Migration rule for output target renames in Stencil v5.
1995
+ *
1996
+ * This migration:
1997
+ * - Renames `dist` → `loader-bundle`
1998
+ * - Renames `dist-custom-elements` → `standalone`
1999
+ * - Renames `dist-hydrate-script` → `ssr`
2000
+ * - Renames `dist-collection` → `collection`
2001
+ * - Renames `dist-types` → `types`
2002
+ * - Extracts `collectionDir` from loader-bundle into separate `collection` output
2003
+ * - Extracts `typesDir` from loader-bundle into separate `types` output
2004
+ * - Renames `esmLoaderPath` → `loaderPath` (applies to all module formats, not just ESM)
2005
+ * - Removes `isPrimaryPackageOutputTarget` (no longer needed, package.json validation auto-detects)
2006
+ * - Removes `generateTypeDeclarations` (types are now auto-generated via the `types` output target)
2007
+ */
2008
+ const outputTargetRenamesRule = {
2009
+ id: "output-target-renames",
2010
+ name: "Output Target Renames",
2011
+ description: "Rename output targets to new v5 names",
2012
+ fromVersion: "4.x",
2013
+ toVersion: "5.x",
2014
+ detect(sourceFile) {
2015
+ const matches = [];
2016
+ const oldToNewNames = {
2017
+ dist: "loader-bundle",
2018
+ "dist-custom-elements": "standalone",
2019
+ "dist-hydrate-script": "ssr",
2020
+ "dist-collection": "collection",
2021
+ "dist-types": "types"
2022
+ };
2023
+ const visit = (node) => {
2024
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === "type" && ts.isStringLiteral(node.initializer)) {
2025
+ const typeValue = node.initializer.text;
2026
+ if (typeValue in oldToNewNames) {
2027
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
2028
+ matches.push({
2029
+ node,
2030
+ message: `Output target type '${typeValue}' → '${oldToNewNames[typeValue]}'`,
2031
+ line: line + 1,
2032
+ column: character + 1
2033
+ });
2034
+ }
2035
+ }
2036
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && (node.name.text === "collectionDir" || node.name.text === "typesDir")) {
2037
+ const parent = node.parent;
2038
+ if (ts.isObjectLiteralExpression(parent)) {
2039
+ if (parent.properties.some((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "type")) {
2040
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
2041
+ const propName = node.name.text;
2042
+ const newType = propName === "collectionDir" ? "collection" : "types";
2043
+ matches.push({
2044
+ node,
2045
+ message: `Property '${propName}' will be extracted to separate '${newType}' output target`,
2046
+ line: line + 1,
2047
+ column: character + 1
2048
+ });
2049
+ }
2050
+ }
2051
+ }
2052
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === "esmLoaderPath") {
2053
+ const parent = node.parent;
2054
+ if (ts.isObjectLiteralExpression(parent)) {
2055
+ if (parent.properties.some((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "type")) {
2056
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
2057
+ matches.push({
2058
+ node,
2059
+ message: `Property 'esmLoaderPath' renamed to 'loaderPath' (applies to all module formats)`,
2060
+ line: line + 1,
2061
+ column: character + 1
2062
+ });
2063
+ }
2064
+ }
2065
+ }
2066
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && (node.name.text === "isPrimaryPackageOutputTarget" || node.name.text === "generateTypeDeclarations")) {
2067
+ const parent = node.parent;
2068
+ if (ts.isObjectLiteralExpression(parent)) {
2069
+ if (parent.properties.some((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "type")) {
2070
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
2071
+ const propName = node.name.text;
2072
+ const reason = propName === "isPrimaryPackageOutputTarget" ? "Package.json validation now auto-detects based on configured outputs" : "Types are now auto-generated via the 'types' output target";
2073
+ matches.push({
2074
+ node,
2075
+ message: `Property '${propName}' is removed in v5. ${reason}`,
2076
+ line: line + 1,
2077
+ column: character + 1
2078
+ });
2079
+ }
2080
+ }
2081
+ }
2082
+ ts.forEachChild(node, visit);
2083
+ };
2084
+ visit(sourceFile);
2085
+ return matches;
2086
+ },
2087
+ transform(sourceFile, matches) {
2088
+ if (matches.length === 0) return sourceFile.getFullText();
2089
+ let text = sourceFile.getFullText();
2090
+ const oldToNewNames = {
2091
+ dist: "loader-bundle",
2092
+ "dist-custom-elements": "standalone",
2093
+ "dist-hydrate-script": "ssr",
2094
+ "dist-collection": "collection",
2095
+ "dist-types": "types"
2096
+ };
2097
+ const outputTargetsToExtract = [];
2098
+ const findOutputTargetsToExtract = (node) => {
2099
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === "outputTargets" && ts.isArrayLiteralExpression(node.initializer)) {
2100
+ for (const element of node.initializer.elements) if (ts.isObjectLiteralExpression(element)) {
2101
+ let collectionDir;
2102
+ let typesDir;
2103
+ for (const prop of element.properties) if (ts.isPropertyAssignment(prop) && ts.isIdentifier(prop.name)) {
2104
+ if (prop.name.text === "collectionDir" && ts.isStringLiteral(prop.initializer)) collectionDir = prop.initializer.text;
2105
+ else if (prop.name.text === "typesDir" && ts.isStringLiteral(prop.initializer)) typesDir = prop.initializer.text;
2106
+ }
2107
+ if (collectionDir || typesDir) outputTargetsToExtract.push({
2108
+ targetNode: element,
2109
+ collectionDir,
2110
+ typesDir
2111
+ });
2112
+ }
2113
+ }
2114
+ ts.forEachChild(node, findOutputTargetsToExtract);
2115
+ };
2116
+ findOutputTargetsToExtract(sourceFile);
2117
+ const modifications = [];
2118
+ for (const match of matches) {
2119
+ const prop = match.node;
2120
+ const propName = prop.name.text;
2121
+ if (propName === "type" && ts.isStringLiteral(prop.initializer)) {
2122
+ const newType = oldToNewNames[prop.initializer.text];
2123
+ if (newType) {
2124
+ const start = prop.initializer.getStart() + 1;
2125
+ const end = prop.initializer.getEnd() - 1;
2126
+ modifications.push({
2127
+ type: "replace",
2128
+ start,
2129
+ end,
2130
+ replacement: newType
2131
+ });
2132
+ }
2133
+ } else if (propName === "esmLoaderPath") {
2134
+ const nameNode = prop.name;
2135
+ modifications.push({
2136
+ type: "replace",
2137
+ start: nameNode.getStart(),
2138
+ end: nameNode.getEnd(),
2139
+ replacement: "loaderPath"
2140
+ });
2141
+ if (ts.isStringLiteral(prop.initializer)) {
2142
+ const newPath = "../" + prop.initializer.text;
2143
+ modifications.push({
2144
+ type: "replace",
2145
+ start: prop.initializer.getStart() + 1,
2146
+ end: prop.initializer.getEnd() - 1,
2147
+ replacement: newPath
2148
+ });
2149
+ }
2150
+ } else if (propName === "collectionDir" || propName === "typesDir" || propName === "isPrimaryPackageOutputTarget" || propName === "generateTypeDeclarations") {
2151
+ const start = prop.getStart();
2152
+ let end = prop.getEnd();
2153
+ const beforeProp = text.slice(0, start).match(/,\s*$/);
2154
+ const afterProp = text.slice(end).match(/^\s*,/);
2155
+ if (afterProp) end = end + afterProp[0].length;
2156
+ else if (beforeProp) {
2157
+ const commaStart = start - beforeProp[0].length;
2158
+ modifications.push({
2159
+ type: "remove",
2160
+ start: commaStart,
2161
+ end
2162
+ });
2163
+ continue;
2164
+ }
2165
+ modifications.push({
2166
+ type: "remove",
2167
+ start,
2168
+ end
2169
+ });
2170
+ }
2171
+ }
2172
+ modifications.sort((a, b) => b.start - a.start);
2173
+ for (const mod of modifications) if (mod.type === "replace") text = text.slice(0, mod.start) + mod.replacement + text.slice(mod.end);
2174
+ else if (mod.type === "remove") text = text.slice(0, mod.start) + text.slice(mod.end);
2175
+ if (outputTargetsToExtract.length > 0) text = addExtractedOutputTargets(text, sourceFile, outputTargetsToExtract);
2176
+ text = text.replace(/,\s*\n\s*\n/g, ",\n");
2177
+ text = text.replace(/{\s*\n\s*\n/g, "{\n");
2178
+ text = text.replace(/,\s*,/g, ",");
2179
+ return text;
2180
+ }
2181
+ };
2182
+ /**
2183
+ * Add new output targets for extracted collectionDir and typesDir.
2184
+ * @param text The original source text
2185
+ * @param sourceFile The TypeScript source file object
2186
+ * @param toExtract An array of objects containing the output target nodes and their collectionDir/typesDir values to extract
2187
+ * @returns The modified source text with new output targets added
2188
+ */
2189
+ function addExtractedOutputTargets(text, sourceFile, toExtract) {
2190
+ let outputTargetsArray = null;
2191
+ const findOutputTargets = (node) => {
2192
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === "outputTargets" && ts.isArrayLiteralExpression(node.initializer)) outputTargetsArray = node.initializer;
2193
+ ts.forEachChild(node, findOutputTargets);
2194
+ };
2195
+ findOutputTargets(sourceFile);
2196
+ if (!outputTargetsArray || toExtract.length === 0) return text;
2197
+ const array = outputTargetsArray;
2198
+ let indent = " ";
2199
+ if (array.elements.length > 0) {
2200
+ const elemStart = array.elements[0].getStart();
2201
+ const lineStart = text.lastIndexOf("\n", elemStart) + 1;
2202
+ const leadingWhitespace = text.slice(lineStart, elemStart);
2203
+ if (/^\s+$/.test(leadingWhitespace)) indent = leadingWhitespace;
2204
+ }
2205
+ const lastElement = array.elements[array.elements.length - 1];
2206
+ if (!lastElement) return text;
2207
+ let insertPos = lastElement.getEnd();
2208
+ const afterLastElement = text.slice(insertPos).match(/^(\s*,)?/);
2209
+ if (afterLastElement && afterLastElement[1]) insertPos += afterLastElement[0].length;
2210
+ const newTargets = [];
2211
+ for (const extracted of toExtract) {
2212
+ if (extracted.collectionDir) newTargets.push(`{\n${indent} type: 'collection',\n${indent} dir: '${extracted.collectionDir}',\n${indent}}`);
2213
+ if (extracted.typesDir) newTargets.push(`{\n${indent} type: 'types',\n${indent} dir: '${extracted.typesDir}',\n${indent}}`);
2214
+ }
2215
+ if (newTargets.length === 0) return text;
2216
+ const insertion = ",\n" + newTargets.map((t) => `${indent}${t}`).join(",\n");
2217
+ text = text.slice(0, insertPos) + insertion + text.slice(insertPos);
2218
+ return text;
2219
+ }
2220
+ //#endregion
2221
+ //#region src/migrations/rules/rolldown-config.ts
2222
+ /**
2223
+ * NodeResolve fields that were valid in @rollup/plugin-node-resolve but don't exist
2224
+ * in rolldown's native resolver and should be removed.
2225
+ */
2226
+ const REMOVED_NODE_RESOLVE_FIELDS = new Set([
2227
+ "browser",
2228
+ "modulePaths",
2229
+ "dedupe",
2230
+ "jail",
2231
+ "modulesOnly",
2232
+ "preferBuiltins",
2233
+ "resolveOnly",
2234
+ "rootDir",
2235
+ "allowExportsFolderMapping"
2236
+ ]);
2237
+ /** Fields renamed between @rollup/plugin-node-resolve and rolldown's native resolver. */
2238
+ const RENAMED_NODE_RESOLVE_FIELDS = {
2239
+ exportConditions: "conditionNames",
2240
+ moduleDirectories: "modules"
2241
+ };
2242
+ function isInsideNodeResolve(node) {
2243
+ const parent = node.parent;
2244
+ if (!ts.isObjectLiteralExpression(parent)) return false;
2245
+ const grandParent = parent.parent;
2246
+ return ts.isPropertyAssignment(grandParent) && ts.isIdentifier(grandParent.name) && grandParent.name.text === "nodeResolve";
2247
+ }
2248
+ /**
2249
+ * Migration rule for rolldown-related config changes in Stencil v5.
2250
+ *
2251
+ * Handles:
2252
+ * - `rollupConfig` → `rolldownConfig` (key rename + flatten `inputOptions`)
2253
+ * - `rolldownConfig: { inputOptions: { ... } }` → `rolldownConfig: { ... }` (flatten)
2254
+ * - `rollupPlugins` → `rolldownPlugins`
2255
+ * - `nodeResolve.exportConditions` → `nodeResolve.conditionNames`
2256
+ * - `nodeResolve.moduleDirectories` → `nodeResolve.modules`
2257
+ * - Removes unsupported `nodeResolve` fields (`browser`, `dedupe`, `jail`, etc.)
2258
+ */
2259
+ const rolldownConfigRule = {
2260
+ id: "rolldown-config",
2261
+ name: "Rolldown Config Migration",
2262
+ description: "Migrate rollup/rolldown config options to v5 rolldown-native API",
2263
+ fromVersion: "4.x",
2264
+ toVersion: "5.x",
2265
+ detect(sourceFile) {
2266
+ const matches = [];
2267
+ const visit = (node) => {
2268
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name)) {
2269
+ const name = node.name.text;
2270
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
2271
+ if (name === "rollupPlugins") matches.push({
2272
+ node,
2273
+ message: `'rollupPlugins' renamed to 'rolldownPlugins'`,
2274
+ line: line + 1,
2275
+ column: character + 1
2276
+ });
2277
+ else if (name === "rollupConfig" || name === "rolldownConfig") {
2278
+ const value = node.initializer;
2279
+ if (name === "rollupConfig" || ts.isObjectLiteralExpression(value) && value.properties.some((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "inputOptions")) matches.push({
2280
+ node,
2281
+ message: name === "rollupConfig" ? `'rollupConfig' renamed to 'rolldownConfig'; 'inputOptions' wrapper removed` : `'rolldownConfig.inputOptions' wrapper removed - options are now top-level`,
2282
+ line: line + 1,
2283
+ column: character + 1
2284
+ });
2285
+ } else if (name in RENAMED_NODE_RESOLVE_FIELDS && isInsideNodeResolve(node)) matches.push({
2286
+ node,
2287
+ message: `'nodeResolve.${name}' renamed to 'nodeResolve.${RENAMED_NODE_RESOLVE_FIELDS[name]}'`,
2288
+ line: line + 1,
2289
+ column: character + 1
2290
+ });
2291
+ else if (REMOVED_NODE_RESOLVE_FIELDS.has(name) && isInsideNodeResolve(node)) matches.push({
2292
+ node,
2293
+ message: `'nodeResolve.${name}' is not supported by rolldown's native resolver and will be removed`,
2294
+ line: line + 1,
2295
+ column: character + 1
2296
+ });
2297
+ }
2298
+ ts.forEachChild(node, visit);
2299
+ };
2300
+ visit(sourceFile);
2301
+ return matches;
2302
+ },
2303
+ transform(sourceFile, matches) {
2304
+ if (matches.length === 0) return sourceFile.getFullText();
2305
+ const edits = [];
2306
+ const fullText = sourceFile.getFullText();
2307
+ for (const match of matches) {
2308
+ const node = match.node;
2309
+ const name = node.name.text;
2310
+ if (name === "rollupPlugins") {
2311
+ const nameStart = node.name.getStart(sourceFile);
2312
+ const nameEnd = node.name.getEnd();
2313
+ edits.push({
2314
+ start: nameStart,
2315
+ end: nameEnd,
2316
+ replacement: "rolldownPlugins"
2317
+ });
2318
+ continue;
2319
+ }
2320
+ if (name in RENAMED_NODE_RESOLVE_FIELDS && isInsideNodeResolve(node)) {
2321
+ const nameStart = node.name.getStart(sourceFile);
2322
+ const nameEnd = node.name.getEnd();
2323
+ edits.push({
2324
+ start: nameStart,
2325
+ end: nameEnd,
2326
+ replacement: RENAMED_NODE_RESOLVE_FIELDS[name]
2327
+ });
2328
+ continue;
2329
+ }
2330
+ if (REMOVED_NODE_RESOLVE_FIELDS.has(name) && isInsideNodeResolve(node)) {
2331
+ const start = node.getFullStart();
2332
+ const end = node.getEnd();
2333
+ const trailingComma = fullText.slice(end).match(/^\s*,/);
2334
+ edits.push({
2335
+ start,
2336
+ end: trailingComma ? end + trailingComma[0].length : end,
2337
+ replacement: ""
2338
+ });
2339
+ continue;
2340
+ }
2341
+ if (name === "rollupConfig" || name === "rolldownConfig") {
2342
+ const value = node.initializer;
2343
+ if (!ts.isObjectLiteralExpression(value)) {
2344
+ if (name === "rollupConfig") {
2345
+ const nameStart = node.name.getStart(sourceFile);
2346
+ edits.push({
2347
+ start: nameStart,
2348
+ end: node.name.getEnd(),
2349
+ replacement: "rolldownConfig"
2350
+ });
2351
+ }
2352
+ continue;
2353
+ }
2354
+ const inputOptionsProp = value.properties.find((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "inputOptions");
2355
+ if (!inputOptionsProp) {
2356
+ if (name === "rollupConfig") {
2357
+ const nameStart = node.name.getStart(sourceFile);
2358
+ edits.push({
2359
+ start: nameStart,
2360
+ end: node.name.getEnd(),
2361
+ replacement: "rolldownConfig"
2362
+ });
2363
+ }
2364
+ continue;
2365
+ }
2366
+ const newValueText = inputOptionsProp.initializer.getText(sourceFile);
2367
+ const keyStart = node.name.getStart(sourceFile);
2368
+ edits.push({
2369
+ start: keyStart,
2370
+ end: node.getEnd(),
2371
+ replacement: `rolldownConfig: ${newValueText}`
2372
+ });
2373
+ }
2374
+ }
2375
+ edits.sort((a, b) => b.start - a.start);
2376
+ let text = fullText;
2377
+ for (const edit of edits) text = text.slice(0, edit.start) + edit.replacement + text.slice(edit.end);
2378
+ return text;
2379
+ }
2380
+ };
2381
+ //#endregion
2382
+ //#region src/migrations/rules/service-worker-default.ts
2383
+ /**
2384
+ * Migration rule for `serviceWorker: null` / `serviceWorker: false` on `www` output targets.
2385
+ *
2386
+ * In Stencil v5, `serviceWorker` defaults to `null` (disabled). Explicit `null` or `false`
2387
+ * values on `www` output targets are now redundant and can be removed.
2388
+ */
2389
+ const serviceWorkerDefaultRule = {
2390
+ id: "service-worker-default",
2391
+ name: "Service Worker Default Cleanup",
2392
+ description: "Remove redundant 'serviceWorker: null' / 'serviceWorker: false' from www output targets - null is now the default",
2393
+ fromVersion: "4.x",
2394
+ toVersion: "5.x",
2395
+ detect(sourceFile) {
2396
+ const matches = [];
2397
+ const visit = (node) => {
2398
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === "serviceWorker") {
2399
+ const init = node.initializer;
2400
+ if (init.kind === ts.SyntaxKind.NullKeyword || init.kind === ts.SyntaxKind.FalseKeyword) {
2401
+ const parent = node.parent;
2402
+ if (ts.isObjectLiteralExpression(parent)) {
2403
+ if (parent.properties.some((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "type" && ts.isStringLiteral(p.initializer) && p.initializer.text === "www")) {
2404
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
2405
+ matches.push({
2406
+ node,
2407
+ message: `'serviceWorker: ${init.kind === ts.SyntaxKind.NullKeyword ? "null" : "false"}' is now the default on www output targets and can be removed`,
2408
+ line: line + 1,
2409
+ column: character + 1
2410
+ });
2411
+ }
2412
+ }
2413
+ }
2414
+ }
2415
+ ts.forEachChild(node, visit);
2416
+ };
2417
+ visit(sourceFile);
2418
+ return matches;
2419
+ },
2420
+ transform(sourceFile, matches) {
2421
+ if (matches.length === 0) return sourceFile.getFullText();
2422
+ let text = sourceFile.getFullText();
2423
+ for (const match of [...matches].reverse()) {
2424
+ const node = match.node;
2425
+ let start = node.getFullStart();
2426
+ const end = node.getEnd();
2427
+ let removeEnd = end;
2428
+ const trailingComma = text.slice(end).match(/^\s*,/);
2429
+ if (trailingComma) removeEnd = end + trailingComma[0].length;
2430
+ else {
2431
+ const leadingComma = text.slice(0, start).match(/,\s*$/);
2432
+ if (leadingComma) start -= leadingComma[0].length;
2433
+ }
2434
+ text = text.slice(0, start) + text.slice(removeEnd);
2435
+ }
2436
+ return text;
2437
+ }
2438
+ };
2439
+ //#endregion
2440
+ //#region src/migrations/index.ts
2441
+ /**
2442
+ * Build a map of local import names to their original names from @stencil/core.
2443
+ * Handles aliased imports like `import { Component as Cmp } from '@stencil/core'`.
2444
+ * Also handles multiple imports from @stencil/core (e.g., separate type and value imports).
648
2445
  *
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
2446
+ * @param sourceFile The TypeScript source file to analyze
2447
+ * @returns Map where keys are local names and values are original imported names
651
2448
  */
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.`);
2449
+ const getStencilCoreImportMap = (sourceFile) => {
2450
+ const importMap = /* @__PURE__ */ new Map();
2451
+ for (const statement of sourceFile.statements) if (ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier) && statement.moduleSpecifier.text === "@stencil/core") {
2452
+ const namedBindings = statement.importClause?.namedBindings;
2453
+ if (namedBindings && ts.isNamedImports(namedBindings)) for (const element of namedBindings.elements) {
2454
+ const localName = element.name.text;
2455
+ const originalName = element.propertyName?.text ?? element.name.text;
2456
+ importMap.set(localName, originalName);
2457
+ }
662
2458
  }
2459
+ return importMap;
663
2460
  };
664
- //#endregion
665
- //#region src/merge-flags.ts
666
2461
  /**
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.?
2462
+ * Check if a decorator identifier refers to a specific @stencil/core export.
2463
+ * Handles aliased imports like `import { Component as Cmp } from '@stencil/core'`.
672
2464
  *
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
2465
+ * @param decoratorName The identifier used in the decorator
2466
+ * @param expectedOriginalName The original export name (e.g., 'Component')
2467
+ * @param importMap The import map from getStencilCoreImportMap
2468
+ * @returns True if the decorator refers to the expected export
676
2469
  */
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;
2470
+ const isStencilDecorator = (decoratorName, expectedOriginalName, importMap) => {
2471
+ return importMap.get(decoratorName) === expectedOriginalName;
701
2472
  };
702
- //#endregion
703
- //#region src/check-version.ts
704
2473
  /**
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`
2474
+ * Registry of all available migration rules.
2475
+ * Rules are applied in order, so add new rules at the end.
710
2476
  */
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;
2477
+ const migrationRules = [
2478
+ encapsulationApiRule,
2479
+ formAssociatedRule,
2480
+ buildDistDocsRule,
2481
+ outputTargetRenamesRule,
2482
+ devModeRule,
2483
+ globalStyleInjectRule,
2484
+ lightDomPatchesRule,
2485
+ extrasToCompatRule,
2486
+ externalRuntimeRule,
2487
+ hashFileNamesRule,
2488
+ rolldownConfigRule,
2489
+ serviceWorkerDefaultRule
2490
+ ];
2491
+ /**
2492
+ * Get all migration rules for a specific version upgrade.
2493
+ * @param fromVersion Source version (e.g., '4')
2494
+ * @param toVersion Target version (e.g., '5')
2495
+ * @returns Filtered list of applicable rules
2496
+ */
2497
+ const getRulesForVersionUpgrade = (fromVersion, toVersion) => {
2498
+ return migrationRules.filter((rule) => rule.fromVersion.startsWith(fromVersion) && rule.toVersion.startsWith(toVersion));
714
2499
  };
2500
+ //#endregion
2501
+ //#region src/task-migrate.ts
715
2502
  /**
716
- * Print the results of running the provided `versionChecker`.
2503
+ * Run the migration task to update Stencil components from v4 to v5 API.
717
2504
  *
718
- * Does not print if no `versionChecker` is provided.
2505
+ * @param coreCompiler the Stencil compiler instance
2506
+ * @param config the validated Stencil config
2507
+ * @param flags CLI flags (includes dryRun option)
2508
+ */
2509
+ const taskMigrate = async (coreCompiler, config, flags) => {
2510
+ const logger = config.logger;
2511
+ const sys = config.sys;
2512
+ const dryRun = flags.dryRun ?? false;
2513
+ const currentMajor = coreCompiler.version.split(".")[0];
2514
+ const fromVersion = String(Number(currentMajor) - 1);
2515
+ const toVersion = currentMajor;
2516
+ const rules = getRulesForVersionUpgrade(fromVersion, toVersion);
2517
+ if (rules.length === 0) {
2518
+ logger.info(`No migration rules found for ${fromVersion}.x → ${toVersion}.x upgrade.`);
2519
+ return;
2520
+ }
2521
+ logger.info(`${logger.emoji("🔄 ")}Stencil Migration Tool (v${fromVersion} → v${toVersion})`);
2522
+ logger.info(`Scanning for components that need migration...`);
2523
+ if (dryRun) logger.info(logger.cyan("Dry run mode - no files will be modified"));
2524
+ const tsFiles = await getTypeScriptFiles(config, sys, logger);
2525
+ if (tsFiles.length === 0) {
2526
+ logger.info(`No TypeScript files found. Check your tsconfig.json configuration.`);
2527
+ return;
2528
+ }
2529
+ logger.info(`Found ${tsFiles.length} TypeScript files to scan`);
2530
+ const results = [];
2531
+ for (const filePath of tsFiles) {
2532
+ let content = await sys.readFile(filePath);
2533
+ if (!content) continue;
2534
+ for (const rule of rules) {
2535
+ const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);
2536
+ const matches = rule.detect(sourceFile);
2537
+ if (matches.length > 0) {
2538
+ const relPath = relative$1(config.rootDir, filePath);
2539
+ logger.info(`\n${logger.cyan(relPath)}`);
2540
+ logger.info(` ${logger.yellow(`[${rule.id}]`)} ${rule.name}`);
2541
+ for (const match of matches) logger.info(` Line ${match.line}: ${match.message}`);
2542
+ if (!dryRun) {
2543
+ const transformed = rule.transform(sourceFile, matches);
2544
+ await sys.writeFile(filePath, transformed);
2545
+ content = transformed;
2546
+ results.push({
2547
+ filePath,
2548
+ rule,
2549
+ matches,
2550
+ transformed: true
2551
+ });
2552
+ logger.info(` ${logger.green("✓")} Migrated`);
2553
+ } else results.push({
2554
+ filePath,
2555
+ rule,
2556
+ matches,
2557
+ transformed: false
2558
+ });
2559
+ }
2560
+ }
2561
+ }
2562
+ logger.info("\n" + logger.bold("Migration Summary"));
2563
+ logger.info("─".repeat(40));
2564
+ const totalMatches = results.reduce((sum, r) => sum + r.matches.length, 0);
2565
+ const filesAffected = new Set(results.map((r) => r.filePath)).size;
2566
+ if (totalMatches === 0) logger.info(logger.green("No migrations needed - your code is up to date!"));
2567
+ else {
2568
+ logger.info(`Found ${totalMatches} item(s) to migrate in ${filesAffected} file(s)`);
2569
+ if (dryRun) logger.info(logger.yellow("\nRun without --dry-run to apply the migrations"));
2570
+ else logger.info(logger.green(`\n✓ Successfully migrated ${totalMatches} item(s)`));
2571
+ }
2572
+ const byRule = /* @__PURE__ */ new Map();
2573
+ for (const result of results) {
2574
+ const existing = byRule.get(result.rule.id) || [];
2575
+ existing.push(result);
2576
+ byRule.set(result.rule.id, existing);
2577
+ }
2578
+ if (byRule.size > 0) {
2579
+ logger.info("\nBy migration rule:");
2580
+ for (const [ruleId, ruleResults] of byRule) {
2581
+ const rule = rules.find((r) => r.id === ruleId);
2582
+ const count = ruleResults.reduce((sum, r) => sum + r.matches.length, 0);
2583
+ logger.info(` ${rule?.name || ruleId}: ${count} item(s)`);
2584
+ }
2585
+ }
2586
+ };
2587
+ /**
2588
+ * Detect available migrations without applying them.
2589
+ * Used by the build task to check if migrations might help fix build errors.
719
2590
  *
720
- * @param versionChecker the function to invoke.
2591
+ * @param coreCompiler the Stencil compiler instance
2592
+ * @param config the validated Stencil config
2593
+ * @returns detection result with migration information
721
2594
  */
722
- const printCheckVersionResults = async (versionChecker) => {
723
- if (versionChecker) {
724
- const checkVersionResults = await versionChecker;
725
- if (isFunction(checkVersionResults)) checkVersionResults();
2595
+ const detectMigrations = async (coreCompiler, config) => {
2596
+ const sys = config.sys;
2597
+ const logger = config.logger;
2598
+ const currentMajor = coreCompiler.version.split(".")[0];
2599
+ const rules = getRulesForVersionUpgrade(String(Number(currentMajor) - 1), currentMajor);
2600
+ if (rules.length === 0) return {
2601
+ hasMigrations: false,
2602
+ totalMatches: 0,
2603
+ filesAffected: 0,
2604
+ migrations: [],
2605
+ rules: []
2606
+ };
2607
+ const tsFiles = await getTypeScriptFiles(config, sys, logger);
2608
+ if (tsFiles.length === 0) return {
2609
+ hasMigrations: false,
2610
+ totalMatches: 0,
2611
+ filesAffected: 0,
2612
+ migrations: [],
2613
+ rules
2614
+ };
2615
+ const migrations = [];
2616
+ for (const filePath of tsFiles) {
2617
+ const content = await sys.readFile(filePath);
2618
+ if (!content) continue;
2619
+ for (const rule of rules) {
2620
+ const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);
2621
+ const matches = rule.detect(sourceFile);
2622
+ if (matches.length > 0) migrations.push({
2623
+ filePath,
2624
+ rule,
2625
+ matches
2626
+ });
2627
+ }
726
2628
  }
2629
+ const totalMatches = migrations.reduce((sum, m) => sum + m.matches.length, 0);
2630
+ const filesAffected = new Set(migrations.map((m) => m.filePath)).size;
2631
+ return {
2632
+ hasMigrations: migrations.length > 0,
2633
+ totalMatches,
2634
+ filesAffected,
2635
+ migrations,
2636
+ rules
2637
+ };
727
2638
  };
2639
+ /**
2640
+ * Get TypeScript files using the project's tsconfig.json.
2641
+ * Uses the same approach as the Stencil compiler.
2642
+ *
2643
+ * @param config the validated Stencil config
2644
+ * @param sys the compiler system for file operations
2645
+ * @param logger the logger for output
2646
+ * @returns array of absolute paths to TypeScript files
2647
+ */
2648
+ async function getTypeScriptFiles(config, sys, logger) {
2649
+ let tsconfigPath;
2650
+ if (config.tsconfig) tsconfigPath = isAbsolute(config.tsconfig) ? config.tsconfig : join$1(config.rootDir, config.tsconfig);
2651
+ else tsconfigPath = join$1(config.rootDir, "tsconfig.json");
2652
+ logger.debug(`Using tsconfig: ${tsconfigPath}`);
2653
+ const tsconfigContent = await sys.readFile(tsconfigPath);
2654
+ if (!tsconfigContent) {
2655
+ logger.error(`tsconfig not found: ${tsconfigPath}`);
2656
+ return [];
2657
+ }
2658
+ const host = {
2659
+ ...ts.sys,
2660
+ readFile: (p) => {
2661
+ if (p === tsconfigPath) return tsconfigContent;
2662
+ return ts.sys.readFile(p);
2663
+ },
2664
+ onUnRecoverableConfigFileDiagnostic: (diagnostic) => {
2665
+ logger.error(ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"));
2666
+ }
2667
+ };
2668
+ const results = ts.getParsedCommandLineOfConfigFile(tsconfigPath, {}, host);
2669
+ if (!results) {
2670
+ logger.error(`Failed to parse tsconfig: ${tsconfigPath}`);
2671
+ return [];
2672
+ }
2673
+ if (results.errors && results.errors.length > 0) for (const err of results.errors) logger.warn(ts.flattenDiagnosticMessageText(err.messageText, "\n"));
2674
+ const files = results.fileNames.filter((f) => (f.endsWith(".ts") || f.endsWith(".tsx")) && !f.endsWith(".d.ts"));
2675
+ const configFile = config.configPath;
2676
+ if (configFile && (configFile.endsWith(".ts") || configFile.endsWith(".mts"))) {
2677
+ if (!files.includes(configFile)) files.push(configFile);
2678
+ const configContent = await sys.readFile(configFile);
2679
+ if (configContent) {
2680
+ const configSourceFile = ts.createSourceFile(configFile, configContent, ts.ScriptTarget.Latest, true);
2681
+ const configDir = dirname$1(configFile);
2682
+ for (const statement of configSourceFile.statements) if (ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier)) {
2683
+ const specifier = statement.moduleSpecifier.text;
2684
+ if (!specifier.startsWith("./") && !specifier.startsWith("../")) continue;
2685
+ const basePath = join$1(configDir, specifier);
2686
+ const candidates = basePath.endsWith(".ts") || basePath.endsWith(".tsx") ? [basePath] : [`${basePath}.ts`, `${basePath}.tsx`];
2687
+ for (const candidate of candidates) if (!candidate.endsWith(".d.ts") && !files.includes(candidate) && candidate.startsWith(config.rootDir)) {
2688
+ if (await sys.readFile(candidate)) {
2689
+ files.push(candidate);
2690
+ break;
2691
+ }
2692
+ }
2693
+ }
2694
+ }
2695
+ }
2696
+ return files;
2697
+ }
728
2698
  //#endregion
729
2699
  //#region src/task-prerender.ts
730
2700
  const taskPrerender = async (coreCompiler, config, flags) => {
731
2701
  startupCompilerLog(coreCompiler, config);
732
- const hydrateAppFilePath = flags.unknownArgs[0];
733
- if (typeof hydrateAppFilePath !== "string") {
2702
+ const ssrAppFilePath = flags.unknownArgs[0];
2703
+ if (typeof ssrAppFilePath !== "string") {
734
2704
  config.logger.error(`Missing hydrate app script path`);
735
2705
  return config.sys.exit(1);
736
2706
  }
737
2707
  const srcIndexHtmlPath = config.srcIndexHtml;
738
- const diagnostics = await runPrerenderTask(coreCompiler, config, hydrateAppFilePath, void 0, srcIndexHtmlPath);
2708
+ const diagnostics = await runPrerenderTask(coreCompiler, config, ssrAppFilePath, void 0, srcIndexHtmlPath);
739
2709
  config.logger.printDiagnostics(diagnostics);
740
2710
  if (diagnostics.some((d) => d.level === "error")) return config.sys.exit(1);
741
2711
  };
742
- const runPrerenderTask = async (coreCompiler, config, hydrateAppFilePath, componentGraph, srcIndexHtmlPath) => {
2712
+ const runPrerenderTask = async (coreCompiler, config, ssrAppFilePath, componentGraph, srcIndexHtmlPath) => {
743
2713
  const diagnostics = [];
744
2714
  try {
745
2715
  const results = await (await coreCompiler.createPrerenderer(config)).start({
746
- hydrateAppFilePath,
2716
+ ssrAppFilePath,
747
2717
  componentGraph,
748
2718
  srcIndexHtmlPath
749
2719
  });
@@ -848,8 +2818,8 @@ function hasVerbose(flags) {
848
2818
  }
849
2819
  //#endregion
850
2820
  //#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"}`);
2821
+ const isTest = () => process.env.JEST_WORKER_ID !== void 0;
2822
+ const defaultConfig = (sys) => sys.resolvePath(`${sys.homeDir()}/.ionic/${isTest() ? "tmp-config.json" : "config.json"}`);
853
2823
  const defaultConfigDirectory = (sys) => sys.resolvePath(`${sys.homeDir()}/.ionic`);
854
2824
  /**
855
2825
  * Reads an Ionic configuration file from disk, parses it, and performs any necessary corrections to it if certain
@@ -1000,9 +2970,9 @@ function getActiveTargets(config) {
1000
2970
  * @returns a Promise wrapping data for the telemetry endpoint
1001
2971
  */
1002
2972
  const prepareData = async (coreCompiler, config, sys, flags, duration_ms, component_count = void 0) => {
1003
- const { typescript, rollup } = coreCompiler.versions || {
2973
+ const { typescript, rolldown } = coreCompiler.versions || {
1004
2974
  typescript: "unknown",
1005
- rollup: "unknown"
2975
+ rolldown: "unknown"
1006
2976
  };
1007
2977
  const { packages, packagesNoVersions } = await getInstalledPackages(sys, flags);
1008
2978
  const targets = getActiveTargets(config);
@@ -1027,7 +2997,7 @@ const prepareData = async (coreCompiler, config, sys, flags, duration_ms, compon
1027
2997
  os_version,
1028
2998
  packages,
1029
2999
  packages_no_versions: packagesNoVersions,
1030
- rollup,
3000
+ rolldown,
1031
3001
  stencil,
1032
3002
  system,
1033
3003
  system_major: getMajorVersion(system),
@@ -1051,13 +3021,11 @@ const CONFIG_PROPS_TO_ANONYMIZE = [
1051
3021
  "tsconfig"
1052
3022
  ];
1053
3023
  const CONFIG_PROPS_TO_DELETE = [
1054
- "commonjs",
1055
3024
  "devServer",
1056
3025
  "env",
1057
3026
  "logger",
1058
- "rollupConfig",
3027
+ "rolldownConfig",
1059
3028
  "sys",
1060
- "testing",
1061
3029
  "tsCompilerOptions"
1062
3030
  ];
1063
3031
  /**
@@ -1077,7 +3045,7 @@ const anonymizeConfigForTelemetry = (config) => {
1077
3045
  if (OUTPUT_TARGET_KEYS_TO_KEEP.includes(key)) return value;
1078
3046
  return "omitted";
1079
3047
  }));
1080
- if (isOutputTargetHydrate(target) && target.external) anonymizedOT["external"] = target.external.concat();
3048
+ if (isOutputTargetSsr(target) && target.external) anonymizedOT["external"] = target.external.concat();
1081
3049
  return anonymizedOT;
1082
3050
  });
1083
3051
  for (const prop of CONFIG_PROPS_TO_DELETE) delete anonymizedConfig[prop];
@@ -1271,14 +3239,59 @@ const taskBuild = async (coreCompiler, config, flags) => {
1271
3239
  let exitCode = 0;
1272
3240
  try {
1273
3241
  startupCompilerLog(coreCompiler, config);
3242
+ const preBuildMigrationResult = await detectMigrations(coreCompiler, config);
3243
+ if (preBuildMigrationResult.hasMigrations) {
3244
+ const action = await promptForMigration(config, preBuildMigrationResult, "pre-build");
3245
+ if (action === "run") {
3246
+ await taskMigrate(coreCompiler, config, {
3247
+ ...flags,
3248
+ dryRun: false
3249
+ });
3250
+ config.logger.info("\nMigrations applied. Starting build...\n");
3251
+ } else if (action === "dry-run") {
3252
+ await taskMigrate(coreCompiler, config, {
3253
+ ...flags,
3254
+ dryRun: true
3255
+ });
3256
+ return config.sys.exit(1);
3257
+ } else return config.sys.exit(1);
3258
+ }
1274
3259
  const versionChecker = startCheckVersion(config, coreCompiler.version, flags);
1275
3260
  const compiler = await coreCompiler.createCompiler(config);
1276
3261
  const results = await compiler.build();
1277
3262
  await telemetryBuildFinishedAction(config.sys, config, coreCompiler, results, flags);
1278
3263
  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);
3264
+ if (results.hasError) {
3265
+ const migrationResult = await detectMigrations(coreCompiler, config);
3266
+ if (migrationResult.hasMigrations) {
3267
+ const action = await promptForMigration(config, migrationResult, "post-error");
3268
+ if (action === "run") {
3269
+ await taskMigrate(coreCompiler, config, {
3270
+ ...flags,
3271
+ dryRun: false
3272
+ });
3273
+ config.logger.info("\nRe-running build after migrations...\n");
3274
+ const newCompiler = await coreCompiler.createCompiler(config);
3275
+ const newResults = await newCompiler.build();
3276
+ await newCompiler.destroy();
3277
+ if (!newResults.hasError) {
3278
+ exitCode = 0;
3279
+ if (flags.prerender) {
3280
+ const prerenderDiagnostics = await runPrerenderTask(coreCompiler, config, newResults.ssrAppFilePath, newResults.componentGraph, void 0);
3281
+ config.logger.printDiagnostics(prerenderDiagnostics);
3282
+ if (prerenderDiagnostics.some((d) => d.level === "error")) exitCode = 1;
3283
+ }
3284
+ } else exitCode = 1;
3285
+ } else if (action === "dry-run") {
3286
+ await taskMigrate(coreCompiler, config, {
3287
+ ...flags,
3288
+ dryRun: true
3289
+ });
3290
+ exitCode = 1;
3291
+ } else exitCode = 1;
3292
+ } else exitCode = 1;
3293
+ } else if (flags.prerender) {
3294
+ const prerenderDiagnostics = await runPrerenderTask(coreCompiler, config, results.ssrAppFilePath, results.componentGraph, void 0);
1282
3295
  config.logger.printDiagnostics(prerenderDiagnostics);
1283
3296
  if (prerenderDiagnostics.some((d) => d.level === "error")) exitCode = 1;
1284
3297
  }
@@ -1289,6 +3302,50 @@ const taskBuild = async (coreCompiler, config, flags) => {
1289
3302
  }
1290
3303
  if (exitCode > 0) return config.sys.exit(exitCode);
1291
3304
  };
3305
+ /**
3306
+ * Prompt the user about available migrations.
3307
+ * Shows what migrations are available and lets them choose to run them.
3308
+ * @param config the Stencil config
3309
+ * @param migrationResult the result of migration detection with available migrations
3310
+ * @param context whether this is a pre-build check or post-error check
3311
+ * @returns the user's chosen action for handling migrations
3312
+ */
3313
+ async function promptForMigration(config, migrationResult, context) {
3314
+ const logger = config.logger;
3315
+ logger.info("");
3316
+ logger.info(logger.bold(logger.yellow("Migrations Required")));
3317
+ logger.info("─".repeat(40));
3318
+ logger.info(`Found ${migrationResult.totalMatches} item(s) in ${migrationResult.filesAffected} file(s) that need to be migrated for Stencil v5.`);
3319
+ for (const migration of migrationResult.migrations) {
3320
+ const relPath = relative$1(config.rootDir, migration.filePath);
3321
+ logger.info(` ${logger.cyan(relPath)}: ${migration.matches.length} item(s)`);
3322
+ }
3323
+ logger.info("");
3324
+ if (context === "pre-build") logger.info("Your config contains deprecated options that must be migrated before building.");
3325
+ else logger.info("These migrations may help resolve the build errors above.");
3326
+ const action = await select({
3327
+ message: "What would you like to do?",
3328
+ options: [
3329
+ {
3330
+ value: "run",
3331
+ label: "Run migration",
3332
+ hint: "Apply migrations and re-run build"
3333
+ },
3334
+ {
3335
+ value: "dry-run",
3336
+ label: "Dry run",
3337
+ hint: "Preview changes without modifying files"
3338
+ },
3339
+ {
3340
+ value: "exit",
3341
+ label: "Exit",
3342
+ hint: "Exit without making changes"
3343
+ }
3344
+ ]
3345
+ });
3346
+ if (isCancel(action)) return "exit";
3347
+ return action;
3348
+ }
1292
3349
  //#endregion
1293
3350
  //#region src/task-docs.ts
1294
3351
  const taskDocs = async (coreCompiler, config) => {
@@ -1302,276 +3359,109 @@ const taskDocs = async (coreCompiler, config) => {
1302
3359
  };
1303
3360
  //#endregion
1304
3361
  //#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
- */
3362
+ async function resolveFileTemplates(contrib, ctx) {
3363
+ const { fileTemplates } = contrib;
3364
+ if (!fileTemplates) return [];
3365
+ return typeof fileTemplates === "function" ? fileTemplates(ctx) : fileTemplates;
3366
+ }
1315
3367
  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).");
3368
+ const srcDir = config.srcDir;
3369
+ if (!srcDir || !existsSync(srcDir)) {
3370
+ config.logger.error("Please run this command in your project root directory.");
1318
3371
  return config.sys.exit(1);
1319
3372
  }
1320
- const absoluteSrcDir = config.srcDir;
1321
- if (!absoluteSrcDir) {
1322
- config.logger.error(`Stencil's srcDir was not specified.`);
1323
- return config.sys.exit(1);
3373
+ const generateContribs = (await discoverPlugins(config.rootDir)).flatMap((d) => d.plugin.generate ? [d.plugin.generate] : []);
3374
+ p.intro("stencil generate");
3375
+ const rawInput = flags.unknownArgs.find((arg) => !arg.startsWith("-"));
3376
+ let input;
3377
+ if (rawInput) input = rawInput;
3378
+ else {
3379
+ const tagName = await p.text({
3380
+ message: "Component tag name (dash-case):",
3381
+ validate: (value) => validateComponentTag(value ?? "")
3382
+ });
3383
+ cancelIfAborted(tagName);
3384
+ input = tagName;
1324
3385
  }
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
3386
  const { dir, base: componentName } = parse(input);
1333
3387
  const tagError = validateComponentTag(componentName);
1334
3388
  if (tagError) {
1335
3389
  config.logger.error(tagError);
1336
3390
  return config.sys.exit(1);
1337
3391
  }
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);
3392
+ const styleOptions = [
3393
+ {
3394
+ value: "css",
3395
+ label: "CSS (.css)"
3396
+ },
3397
+ ...[...new Set(generateContribs.flatMap((c) => c.styleExtensions ?? []))].map((ext) => ({
3398
+ value: ext,
3399
+ label: `${ext.toUpperCase()} (.${ext})`
3400
+ })),
3401
+ {
3402
+ value: "",
3403
+ label: "None"
3404
+ }
3405
+ ];
3406
+ const stylePick = await p.select({
3407
+ message: "Stylesheet format:",
3408
+ options: styleOptions
3409
+ });
3410
+ cancelIfAborted(stylePick);
3411
+ const styleExtension = stylePick || void 0;
3412
+ const generateCtx = {
3413
+ tagName: componentName,
3414
+ config: toProjectConfig(config),
3415
+ prompts: p,
3416
+ nypm
3417
+ };
3418
+ const allFileTemplates = [];
3419
+ for (const contrib of generateContribs) allFileTemplates.push(...await resolveFileTemplates(contrib, generateCtx));
3420
+ let pickedExtensions = [];
3421
+ if (allFileTemplates.length > 0) {
3422
+ const filePick = await p.multiselect({
3423
+ message: "Additional files:",
3424
+ options: allFileTemplates.map((ft) => ({
3425
+ value: ft.extension,
3426
+ label: ft.label
3427
+ })),
3428
+ initialValues: allFileTemplates.filter((ft) => ft.selectedByDefault !== false).map((ft) => ft.extension),
3429
+ required: false
3430
+ });
3431
+ cancelIfAborted(filePick);
3432
+ pickedExtensions = filePick;
1458
3433
  }
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}".`);
3434
+ const outDir = join(srcDir, "components", dir, componentName);
3435
+ const className = toPascalCase(componentName);
3436
+ const filesToWrite = [];
3437
+ filesToWrite.push({
3438
+ absPath: normalizePath(join(outDir, `${componentName}.tsx`)),
3439
+ content: getComponentBoilerplate(componentName, styleExtension)
3440
+ });
3441
+ if (styleExtension) filesToWrite.push({
3442
+ absPath: normalizePath(join(outDir, `${componentName}.${styleExtension}`)),
3443
+ content: getStyleBoilerplate(styleExtension)
3444
+ });
3445
+ for (const ext of pickedExtensions) {
3446
+ const tmpl = allFileTemplates.find((ft) => ft.extension === ext);
3447
+ const absPath = normalizePath(join(outDir, tmpl.subdirectory ?? "", `${componentName}.${ext}`));
3448
+ filesToWrite.push({
3449
+ absPath,
3450
+ content: tmpl.template(componentName, className)
3451
+ });
1488
3452
  }
3453
+ const wouldOverwrite = (await Promise.all(filesToWrite.map(async ({ absPath }) => await config.sys.readFile(absPath) !== void 0 ? absPath : null))).filter((f) => f !== null);
3454
+ if (wouldOverwrite.length > 0) {
3455
+ config.logger.error("Generating code would overwrite the following files:", ...wouldOverwrite.map((path) => " " + normalizePath(path)));
3456
+ await config.sys.exit(1);
3457
+ return;
3458
+ }
3459
+ const dirs = [...new Set(filesToWrite.map(({ absPath }) => normalizePath(join(absPath, ".."))))];
3460
+ await Promise.all(dirs.map((d) => config.sys.createDir(d, { recursive: true })));
3461
+ await Promise.all(filesToWrite.map(({ absPath, content }) => config.sys.writeFile(absPath, content)));
3462
+ p.note(filesToWrite.map(({ absPath }) => relative(config.rootDir, absPath)).join("\n"), "Generated");
3463
+ p.outro(`stencil generate ${input}`);
1489
3464
  };
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
3465
  //#endregion
1576
3466
  //#region src/task-telemetry.ts
1577
3467
  /**
@@ -1680,11 +3570,345 @@ const taskInfo = (coreCompiler, sys, logger) => {
1680
3570
  console.log(`${logger.cyan(" Build:")} ${coreCompiler.buildId}`);
1681
3571
  console.log(`${logger.cyan(" Stencil:")} ${coreCompiler.version}${logger.emoji(" " + coreCompiler.vermoji)}`);
1682
3572
  console.log(`${logger.cyan(" TypeScript:")} ${versions.typescript}`);
1683
- console.log(`${logger.cyan(" Rollup:")} ${versions.rollup}`);
3573
+ console.log(`${logger.cyan(" Rolldown:")} ${versions.rolldown}`);
1684
3574
  console.log(`${logger.cyan(" Terser:")} ${versions.terser}`);
1685
3575
  console.log(``);
1686
3576
  };
1687
3577
  //#endregion
3578
+ //#region src/wizard/init/apply.ts
3579
+ /**
3580
+ * Copy component-starter template into rootDir, interpolating project name and namespace.
3581
+ *
3582
+ * @param rootDir - Destination directory (typically `process.cwd()`).
3583
+ * @param projectName - Value to substitute for `{{PROJECT_NAME}}` placeholders.
3584
+ * @param namespace - Value to substitute for `{{NAMESPACE}}` placeholders.
3585
+ * @param stencilVersion - Optional version to substitute for `{{STENCIL_VERSION}}` placeholders.
3586
+ */
3587
+ async function copyTemplate(rootDir, projectName, namespace, stencilVersion) {
3588
+ const templateDir = getTemplatePath("component-starter");
3589
+ const entries = await readdir(templateDir, {
3590
+ recursive: true,
3591
+ withFileTypes: true
3592
+ });
3593
+ const resolvedStencilVersion = stencilVersion ? `^${stencilVersion}` : "^5.0.0";
3594
+ for (const entry of entries) {
3595
+ if (!entry.isFile()) continue;
3596
+ const srcPath = join(entry.parentPath, entry.name);
3597
+ const relPath = relative(templateDir, srcPath);
3598
+ const destPath = join(rootDir, relPath);
3599
+ await mkdir(dirname(destPath), { recursive: true });
3600
+ const content = (await readFile(srcPath, "utf8")).replace(/\{\{PROJECT_NAME\}\}/g, projectName).replace(/\{\{NAMESPACE\}\}/g, namespace).replace(/\{\{STENCIL_VERSION\}\}/g, resolvedStencilVersion);
3601
+ if (relPath === "package.json") await mergePackageJson(destPath, content);
3602
+ else if (relPath === "tsconfig.json") await mergeTsConfig(destPath, content);
3603
+ else if (relPath === ".gitignore") await mergeGitignore(destPath, content);
3604
+ else await writeIfAbsent(destPath, content);
3605
+ }
3606
+ }
3607
+ async function writeIfAbsent(destPath, content) {
3608
+ try {
3609
+ await writeFile(destPath, content, {
3610
+ encoding: "utf8",
3611
+ flag: "wx"
3612
+ });
3613
+ } catch (e) {
3614
+ if (e.code !== "EEXIST") throw e;
3615
+ }
3616
+ }
3617
+ async function mergePackageJson(destPath, templateContent) {
3618
+ const template = JSON.parse(templateContent);
3619
+ let existing;
3620
+ try {
3621
+ existing = JSON.parse(await readFile(destPath, "utf8"));
3622
+ } catch {
3623
+ await writeFile(destPath, templateContent, "utf8");
3624
+ return;
3625
+ }
3626
+ const dependencies = mergeStringRecord(template.dependencies, existing.dependencies);
3627
+ const devDependencies = mergeStringRecord(template.devDependencies, existing.devDependencies);
3628
+ for (const pkg of Object.keys(devDependencies)) if (pkg in dependencies) delete devDependencies[pkg];
3629
+ const merged = {
3630
+ ...template,
3631
+ ...existing,
3632
+ scripts: mergeStringRecord(template.scripts, existing.scripts),
3633
+ dependencies,
3634
+ devDependencies
3635
+ };
3636
+ await writeFile(destPath, JSON.stringify(merged, null, 2) + "\n", "utf8");
3637
+ }
3638
+ async function mergeTsConfig(destPath, templateContent) {
3639
+ const template = JSON.parse(templateContent);
3640
+ let existing;
3641
+ try {
3642
+ existing = JSON.parse(await readFile(destPath, "utf8"));
3643
+ } catch {
3644
+ await writeFile(destPath, templateContent, "utf8");
3645
+ return;
3646
+ }
3647
+ const merged = {
3648
+ ...template,
3649
+ ...existing,
3650
+ compilerOptions: mergeStringRecord(template.compilerOptions, existing.compilerOptions)
3651
+ };
3652
+ await writeFile(destPath, JSON.stringify(merged, null, 2) + "\n", "utf8");
3653
+ }
3654
+ async function mergeGitignore(destPath, templateContent) {
3655
+ let existing;
3656
+ try {
3657
+ existing = await readFile(destPath, "utf8");
3658
+ } catch {
3659
+ await writeFile(destPath, templateContent, "utf8");
3660
+ return;
3661
+ }
3662
+ const existingEntries = new Set(existing.split("\n").map((l) => l.trim()).filter(Boolean));
3663
+ const missing = templateContent.split("\n").filter((line) => line.trim() && !existingEntries.has(line.trim()));
3664
+ if (missing.length === 0) return;
3665
+ const separator = existing.endsWith("\n") ? "" : "\n";
3666
+ await writeFile(destPath, existing + separator + missing.join("\n") + "\n", "utf8");
3667
+ }
3668
+ function mergeStringRecord(base, override) {
3669
+ const toObj = (v) => v !== null && typeof v === "object" ? v : {};
3670
+ return {
3671
+ ...toObj(base),
3672
+ ...toObj(override)
3673
+ };
3674
+ }
3675
+ async function writeStencilConfig(rootDir, content) {
3676
+ await writeFile(join(rootDir, "stencil.config.ts"), content, "utf8");
3677
+ }
3678
+ async function writeGlobalStyle(rootDir) {
3679
+ const path = join(rootDir, "src", "global.css");
3680
+ await mkdir(dirname(path), { recursive: true });
3681
+ await writeIfAbsent(path, `@import "stencil-globals";\n@import "stencil-hydrate";\n`);
3682
+ }
3683
+ async function writeGlobalScript(rootDir) {
3684
+ const path = join(rootDir, "src", "global.ts");
3685
+ await mkdir(dirname(path), { recursive: true });
3686
+ await writeIfAbsent(path, `export default function (): void {}\n`);
3687
+ }
3688
+ function workspaceBuildScript(pm) {
3689
+ switch (pm) {
3690
+ case "pnpm": return "pnpm -r build";
3691
+ case "yarn": return "yarn workspaces run build";
3692
+ case "bun": return "bun run --filter \"*\" build";
3693
+ default: return "npm run build --workspaces --if-present";
3694
+ }
3695
+ }
3696
+ /**
3697
+ * Scaffold a workspace root in `cwd`: creates `packages/`, writes the appropriate
3698
+ * workspace manifest (`pnpm-workspace.yaml` for pnpm, `workspaces` field in
3699
+ * `package.json` for npm / yarn / bun), and ensures a root `package.json` exists.
3700
+ * @param cwd - Absolute path to the workspace root (where `package.json` will be created).
3701
+ * @param projectName - Name to use for the root package.json (typically the project name).
3702
+ * @returns A promise that resolves when the workspace root has been scaffolded.
3703
+ */
3704
+ async function scaffoldWorkspaceRoot(cwd, projectName) {
3705
+ await mkdir(join(cwd, "packages"), { recursive: true });
3706
+ const pm = await detectPackageManager(cwd);
3707
+ const usePnpmYaml = pm?.name === "pnpm";
3708
+ const pkgPath = join(cwd, "package.json");
3709
+ let pkg;
3710
+ try {
3711
+ pkg = JSON.parse(await readFile(pkgPath, "utf8"));
3712
+ } catch {
3713
+ pkg = {};
3714
+ }
3715
+ pkg.name ??= `${projectName}-workspace`;
3716
+ pkg.version ??= "0.0.1";
3717
+ pkg.private = true;
3718
+ pkg.scripts ??= { build: workspaceBuildScript(pm?.name) };
3719
+ if (!usePnpmYaml) pkg.workspaces = ["packages/*"];
3720
+ delete pkg.dependencies;
3721
+ delete pkg.devDependencies;
3722
+ await writeFile(pkgPath, JSON.stringify(pkg, null, 2) + "\n", "utf8");
3723
+ if (usePnpmYaml) {
3724
+ const yamlPath = join(cwd, "pnpm-workspace.yaml");
3725
+ try {
3726
+ await writeFile(yamlPath, `packages:\n - 'packages/*'\n`, {
3727
+ encoding: "utf8",
3728
+ flag: "wx"
3729
+ });
3730
+ } catch (e) {
3731
+ if (e.code !== "EEXIST") throw e;
3732
+ }
3733
+ }
3734
+ }
3735
+ /**
3736
+ * Write output-driven distributable fields (type, module, types) into package.json.
3737
+ * These fields depend on which outputs the user selected, so they cannot be static in the template.
3738
+ * Skips if fields is empty (e.g. www-only project).
3739
+ *
3740
+ * @param rootDir - Absolute path to the project root.
3741
+ * @param fields - Fields to write, from generatePackageJsonFields().
3742
+ */
3743
+ async function applyPackageJsonFields(rootDir, fields) {
3744
+ if (Object.keys(fields).length === 0) return;
3745
+ const pkgPath = join(rootDir, "package.json");
3746
+ const pkg = JSON.parse(await readFile(pkgPath, "utf8"));
3747
+ Object.assign(pkg, fields);
3748
+ await writeFile(pkgPath, JSON.stringify(pkg, null, 2) + "\n", "utf8");
3749
+ }
3750
+ //#endregion
3751
+ //#region src/task-init.ts
3752
+ function outputKeysToTargets(keys) {
3753
+ const map = {
3754
+ loader: "loader-bundle",
3755
+ standalone: "standalone",
3756
+ ssr: "ssr",
3757
+ "ssr-wasm": "ssr-wasm",
3758
+ www: "www"
3759
+ };
3760
+ return keys.length > 0 ? keys.map((k) => ({ type: map[k] })) : [{ type: "loader-bundle" }];
3761
+ }
3762
+ async function taskInit(coreCompiler, strictConfig, loadProjectConfig) {
3763
+ const cwd = process.cwd();
3764
+ const isExistingProject = await isExistingStencilProject(cwd);
3765
+ printSplash();
3766
+ p.intro(`stencil init`);
3767
+ if (process.env.STENCIL_WIZARD_DEV) p.log.warn(`Dev mode: loading wizards from ${process.env.STENCIL_WIZARD_DEV}`);
3768
+ if (isCI) {
3769
+ p.log.warn("Running in CI - non-interactive mode is not yet supported for `stencil init`.");
3770
+ process.exit(1);
3771
+ }
3772
+ if (isExistingProject) {
3773
+ await addCapabilities(cwd, strictConfig);
3774
+ return;
3775
+ }
3776
+ const projectName = await promptProjectName();
3777
+ const namespace = toNamespace(projectName);
3778
+ const outputs = await promptOutputs();
3779
+ const features = await promptFeatures();
3780
+ const docs = await promptDocs();
3781
+ const selectedIntegrations = await promptIntegrations();
3782
+ let monorepo = false;
3783
+ let coreName = "";
3784
+ if (hasFrameworkTargets(selectedIntegrations)) {
3785
+ monorepo = await promptMonorepo();
3786
+ if (monorepo) coreName = await promptWorkspaceCoreName();
3787
+ }
3788
+ const configSource = generateStencilConfig({
3789
+ namespace,
3790
+ outputs,
3791
+ signals: features.signals,
3792
+ docs
3793
+ }) ?? (needsStencilConfig(selectedIntegrations) ? `import { Config } from '@stencil/core';\n\nexport const config: Config = {\n namespace: '${namespace}',\n outputTargets: [{ type: 'loader-bundle' }],\n};\n` : null);
3794
+ const summaryLines = [
3795
+ `Template: component-starter`,
3796
+ `Name: ${projectName}`,
3797
+ `Namespace: ${namespace}`,
3798
+ `Config: ${configSource ? "stencil.config.ts" : "zero-config (loader default)"}`
3799
+ ];
3800
+ if (monorepo) {
3801
+ summaryLines.push(`Structure: monorepo workspace`);
3802
+ summaryLines.push(`Core: packages/${coreName}/`);
3803
+ }
3804
+ if (selectedIntegrations.length > 0) summaryLines.push(`Add: ${selectedIntegrations.map((i) => i.displayName).join(", ")}`);
3805
+ p.note(summaryLines.join("\n"), "Summary");
3806
+ const coreDir = monorepo ? join(cwd, "packages", coreName) : cwd;
3807
+ const s1 = p.spinner();
3808
+ s1.start("Scaffolding project files");
3809
+ if (monorepo) await scaffoldWorkspaceRoot(cwd, projectName);
3810
+ await copyTemplate(coreDir, projectName, namespace, coreCompiler?.version);
3811
+ await applyPackageJsonFields(coreDir, generatePackageJsonFields(outputs));
3812
+ if (configSource) await writeStencilConfig(coreDir, configSource);
3813
+ if (features.globalStyle) await writeGlobalStyle(coreDir);
3814
+ if (features.globalScript) await writeGlobalScript(coreDir);
3815
+ s1.stop("Project files created");
3816
+ const s2 = p.spinner();
3817
+ s2.start("Installing dependencies");
3818
+ await installDependencies({
3819
+ cwd,
3820
+ silent: true
3821
+ });
3822
+ s2.stop("Dependencies installed");
3823
+ if (selectedIntegrations.length > 0) {
3824
+ const s3 = p.spinner();
3825
+ const pkgs = selectedIntegrations.map((i) => i.package);
3826
+ s3.start(`Installing ${pkgs.join(", ")}`);
3827
+ await addDevDependency(pkgs, {
3828
+ cwd: coreDir,
3829
+ silent: true
3830
+ });
3831
+ s3.stop("Integrations installed");
3832
+ }
3833
+ if (selectedIntegrations.length > 0) {
3834
+ const discovered = await discoverPlugins(coreDir);
3835
+ const selectedPkgs = new Set(selectedIntegrations.map((i) => i.package));
3836
+ const resolvedValidated = loadProjectConfig && configSource ? await loadProjectConfig(join(coreDir, "stencil.config.ts")) : coreCompiler ? coreCompiler.validateConfig({
3837
+ rootDir: coreDir,
3838
+ outputTargets: outputKeysToTargets(outputs),
3839
+ ...configSource ? { namespace } : {}
3840
+ }, {}).config : null;
3841
+ const projectConfig = resolvedValidated ? {
3842
+ ...toProjectConfig(resolvedValidated),
3843
+ rootDir: coreDir
3844
+ } : defaultProjectConfig(coreDir, { namespace });
3845
+ for (const d of discovered) if (selectedPkgs.has(d.packageName) && d.plugin.init?.run) await d.plugin.init.run({
3846
+ isNewProject: true,
3847
+ prompts: p,
3848
+ nypm,
3849
+ config: projectConfig,
3850
+ workspaceRoot: monorepo ? cwd : void 0
3851
+ });
3852
+ }
3853
+ const pm = (await nypm.detectPackageManager(cwd))?.name ?? "npm";
3854
+ const devDir = monorepo ? `packages/${coreName}` : null;
3855
+ const devCmd = `${pm} run dev`;
3856
+ p.outro(devDir ? `Your project is ready!\n cd ${devDir}\n ${devCmd}` : `Your project is ready! Run: ${devCmd}`);
3857
+ }
3858
+ async function addCapabilities(cwd, strictConfig) {
3859
+ const workspaceRoot = await detectWorkspaceRoot(cwd);
3860
+ const raw = JSON.parse(await readFile(join(cwd, "package.json"), "utf8"));
3861
+ const installed = new Set([...Object.keys(raw.dependencies ?? {}), ...Object.keys(raw.devDependencies ?? {})]);
3862
+ const discovered = await discoverPlugins(cwd);
3863
+ const configurable = discovered.filter((d) => d.plugin.init);
3864
+ const installable = KNOWN_INTEGRATIONS.filter((i) => !installed.has(i.package));
3865
+ if (installable.length === 0 && configurable.length === 0) {
3866
+ p.log.info("All known integrations are already installed and configured.");
3867
+ p.outro("Nothing to do.");
3868
+ return;
3869
+ }
3870
+ const { toInstall, toConfigure } = await promptAddCapabilities(installable, configurable);
3871
+ if (toInstall.length === 0 && toConfigure.length === 0) {
3872
+ p.outro("No changes made.");
3873
+ return;
3874
+ }
3875
+ const summaryLines = [];
3876
+ for (const i of toInstall) summaryLines.push(`Install: ${i.displayName}`);
3877
+ for (const d of toConfigure) summaryLines.push(`Configure: ${d.plugin.init.displayName}`);
3878
+ p.note(summaryLines.join("\n"), "Summary");
3879
+ const confirmed = await p.confirm({ message: "Apply changes?" });
3880
+ cancelIfAborted(confirmed);
3881
+ if (!confirmed) {
3882
+ p.cancel("Cancelled.");
3883
+ process.exit(0);
3884
+ }
3885
+ if (toInstall.length > 0) {
3886
+ const s = p.spinner();
3887
+ const pkgs = toInstall.map((i) => i.package);
3888
+ s.start(`Installing ${pkgs.join(", ")}`);
3889
+ await addDevDependency(pkgs, {
3890
+ cwd,
3891
+ silent: true
3892
+ });
3893
+ s.stop("Dependencies installed");
3894
+ }
3895
+ const allDiscovered = toInstall.length > 0 ? await discoverPlugins(cwd) : discovered;
3896
+ const newlyInstalledPkgs = new Set(toInstall.map((i) => i.package));
3897
+ const toRun = [...allDiscovered.filter((d) => newlyInstalledPkgs.has(d.packageName)), ...toConfigure].filter((d) => d.plugin.init?.run);
3898
+ const projectConfig = strictConfig ? toProjectConfig(strictConfig) : defaultProjectConfig(cwd);
3899
+ for (const d of toRun) await d.plugin.init.run({
3900
+ isNewProject: false,
3901
+ prompts: p,
3902
+ nypm,
3903
+ config: projectConfig,
3904
+ workspaceRoot
3905
+ });
3906
+ p.outro("Done! Run pnpm run dev to continue.");
3907
+ }
3908
+ function toNamespace(name) {
3909
+ return toPascalCase(name.replace(/^@[^/]+\//, "").replace(/[/_]/g, "-"));
3910
+ }
3911
+ //#endregion
1688
3912
  //#region src/task-serve.ts
1689
3913
  const taskServe = async (config, flags) => {
1690
3914
  config.suppressLogs = true;
@@ -1740,6 +3964,41 @@ const run = async (init) => {
1740
3964
  }), logger, sys);
1741
3965
  return;
1742
3966
  }
3967
+ if (task === "add" || task === "init") {
3968
+ const coreCompiler = await loadCoreCompiler(sys);
3969
+ const rootDir = sys.getCurrentDirectory();
3970
+ const findConfigResults = await findConfig({
3971
+ sys,
3972
+ configPath: flags.config
3973
+ });
3974
+ let strictConfig;
3975
+ const foundConfigPath = !findConfigResults.isErr ? result.unwrap(findConfigResults).configPath : null;
3976
+ if (foundConfigPath) {
3977
+ const loaded = await coreCompiler.loadConfig({
3978
+ config: { rootDir: dirname(foundConfigPath) },
3979
+ configPath: foundConfigPath,
3980
+ logger,
3981
+ sys
3982
+ });
3983
+ strictConfig = coreCompiler.validateConfig(loaded.config, {}).config;
3984
+ } else strictConfig = coreCompiler.validateConfig({ rootDir }, {}).config;
3985
+ if (task === "add") await taskAdd(flags.unknownArgs, strictConfig);
3986
+ else {
3987
+ const loadProjectConfig = async (configPath) => {
3988
+ const derivedRootDir = configPath ? dirname(configPath) : rootDir;
3989
+ const loaded = await coreCompiler.loadConfig({
3990
+ config: { rootDir: derivedRootDir },
3991
+ configPath,
3992
+ logger,
3993
+ sys
3994
+ });
3995
+ if (loaded.diagnostics.length > 0) logger.printDiagnostics(loaded.diagnostics);
3996
+ return coreCompiler.validateConfig(loaded.config ?? { rootDir: derivedRootDir }, {}).config;
3997
+ };
3998
+ await taskInit(coreCompiler, strictConfig, loadProjectConfig);
3999
+ }
4000
+ return;
4001
+ }
1743
4002
  startupLog(logger, task);
1744
4003
  const findConfigResults = await findConfig({
1745
4004
  sys,
@@ -1760,7 +4019,7 @@ const run = async (init) => {
1760
4019
  const configWithFlags = mergeFlags({}, flags);
1761
4020
  const validated = await coreCompiler.loadConfig({
1762
4021
  config: configWithFlags,
1763
- configPath: foundConfig.configPath,
4022
+ configPath: foundConfig.configPath ?? void 0,
1764
4023
  logger,
1765
4024
  sys
1766
4025
  });
@@ -1797,6 +4056,9 @@ const runTask = async (coreCompiler, config, task, sys, flags) => {
1797
4056
  if (!configWithFlags.sys) configWithFlags.sys = sys;
1798
4057
  const strictConfig = coreCompiler.validateConfig(configWithFlags, {}).config;
1799
4058
  switch (task) {
4059
+ case "add":
4060
+ await taskAdd(resolvedFlags.unknownArgs ?? [], strictConfig);
4061
+ break;
1800
4062
  case "build":
1801
4063
  await taskBuild(coreCompiler, strictConfig, resolvedFlags);
1802
4064
  break;
@@ -1810,6 +4072,12 @@ const runTask = async (coreCompiler, config, task, sys, flags) => {
1810
4072
  case "help":
1811
4073
  await taskHelp(resolvedFlags, strictConfig.logger, sys);
1812
4074
  break;
4075
+ case "init":
4076
+ await taskInit(coreCompiler, strictConfig);
4077
+ break;
4078
+ case "migrate":
4079
+ await taskMigrate(coreCompiler, strictConfig, resolvedFlags);
4080
+ break;
1813
4081
  case "prerender":
1814
4082
  await taskPrerender(coreCompiler, strictConfig, resolvedFlags);
1815
4083
  break;