@stencil/cli 5.0.0-alpha.8 → 5.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,17 +1,19 @@
1
1
  import { LOG_LEVELS } from "@stencil/core/compiler";
2
- import { buildError, catchError, hasError, isFunction, isOutputTargetDocs, isOutputTargetSsr, isOutputTargetWww, isString, normalizePath, readOnlyArrayHasStringMember, result, shouldIgnoreError, toCamelCase, validateComponentTag } from "@stencil/core/compiler/utils";
3
- import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
2
+ import { buildError, catchError, hasError, isFunction, isOutputTargetDistLazy, isOutputTargetDocs, isOutputTargetSsr, isOutputTargetStandalone, isOutputTargetWww, isString, normalizePath, readOnlyArrayHasStringMember, result, shouldIgnoreError, toCamelCase, validateComponentTag } from "@stencil/core/compiler/utils";
4
3
  import { basename, dirname, join, parse, relative, resolve } from "node:path";
4
+ import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
5
5
  import * as p from "@clack/prompts";
6
6
  import { cancel, isCancel, select } from "@clack/prompts";
7
7
  import * as nypm from "nypm";
8
- import { addDevDependency, installDependencies } from "nypm";
8
+ import { addDevDependency, detectPackageManager } from "nypm";
9
9
  import { isCI } from "std-env";
10
+ import ts from "typescript";
10
11
  import { pathToFileURL } from "node:url";
12
+ import { getPackageInfo } from "local-pkg";
11
13
  import { existsSync } from "node:fs";
14
+ import { homedir } from "node:os";
12
15
  import { dirname as dirname$1, isAbsolute, join as join$1, relative as relative$1 } from "path";
13
- import ts from "typescript";
14
- import { generatePackageJsonFields, generateStencilConfig, getComponentBoilerplate, getStyleBoilerplate, getTemplatePath, toPascalCase } from "@stencil/templates";
16
+ import { generateIndexHtml, generatePackageJsonFields, generateStencilConfig, getComponentBoilerplate, getPreviewHtmlBoilerplate, getStyleBoilerplate, getTemplatePath, getUsageExampleBoilerplate, toPascalCase } from "@stencil/templates";
15
17
  import { start } from "@stencil/dev-server";
16
18
  //#region src/config-flags.ts
17
19
  /**
@@ -20,23 +22,18 @@ import { start } from "@stencil/dev-server";
20
22
  const BOOLEAN_CLI_FLAGS = [
21
23
  "build",
22
24
  "cache",
23
- "checkVersion",
24
25
  "ci",
25
- "compare",
26
26
  "debug",
27
27
  "dev",
28
- "devtools",
29
28
  "docs",
30
29
  "dryRun",
31
30
  "help",
32
31
  "log",
33
32
  "open",
34
33
  "prerender",
35
- "prerenderExternal",
36
34
  "profile",
37
35
  "serviceWorker",
38
36
  "serve",
39
- "skipNodeCheck",
40
37
  "ssr",
41
38
  "verbose",
42
39
  "version",
@@ -52,9 +49,7 @@ const NUMBER_CLI_FLAGS = ["port"];
52
49
  const STRING_CLI_FLAGS = [
53
50
  "address",
54
51
  "config",
55
- "docsApi",
56
52
  "docsJson",
57
- "emulate",
58
53
  "root"
59
54
  ];
60
55
  const STRING_ARRAY_CLI_FLAGS = [];
@@ -196,8 +191,10 @@ const parseCLITerm = (flags, args) => {
196
191
  const [originalArg, value] = parseEqualsArg(arg);
197
192
  setCLIArg(flags, desugarRawAlias(originalArg), normalizeFlagName(originalArg), value);
198
193
  } else if (CLI_FLAG_REGEX.test(arg)) setCLIArg(flags, desugarRawAlias(arg), normalizeFlagName(arg), parseCLIValue(args));
199
- else if (arg.startsWith("--no-") && arg.length > 5) setCLIArg(flags, arg, normalizeNegativeFlagName(arg), "");
200
- else if (arg.startsWith("--no") && (isNegatedBoolean || isNegatedBooleanOrString)) setCLIArg(flags, arg, normalizeNegativeFlagName(arg), "");
194
+ else if (arg.startsWith("--no-") && arg.length > 5) {
195
+ const normalized = normalizeNegativeFlagName(arg);
196
+ setCLIArg(flags, arg, normalized, "");
197
+ } else if (arg.startsWith("--no") && (isNegatedBoolean || isNegatedBooleanOrString)) setCLIArg(flags, arg, normalizeNegativeFlagName(arg), "");
201
198
  else if (arg.startsWith("--") && arg.length > 2) setCLIArg(flags, arg, normalizeFlagName(arg), parseCLIValue(args));
202
199
  else flags.unknownArgs.push(arg);
203
200
  };
@@ -250,52 +247,58 @@ const setCLIArg = (flags, rawArg, normalizedArg, value) => {
250
247
  flags[normalizedArg] = typeof value === "string" ? value === "true" : true;
251
248
  flags.knownArgs.push(rawArg);
252
249
  if (typeof value === "string" && value !== "") flags.knownArgs.push(value);
253
- } else if (readOnlyArrayHasStringMember(STRING_CLI_FLAGS, normalizedArg)) if (typeof value === "string") {
254
- flags[normalizedArg] = value;
255
- flags.knownArgs.push(rawArg);
256
- flags.knownArgs.push(value);
257
- } else throwCLIParsingError(rawArg, "expected a string argument but received nothing");
258
- else if (STRING_ARRAY_CLI_FLAGS.length > 0 && readOnlyArrayHasStringMember(STRING_ARRAY_CLI_FLAGS, normalizedArg)) if (typeof value === "string") {
259
- const flagsRecord = flags;
260
- if (!Array.isArray(flagsRecord[normalizedArg])) flagsRecord[normalizedArg] = [];
261
- const targetArray = flagsRecord[normalizedArg];
262
- if (Array.isArray(targetArray)) {
263
- targetArray.push(value);
250
+ } else if (readOnlyArrayHasStringMember(STRING_CLI_FLAGS, normalizedArg)) {
251
+ if (typeof value === "string") {
252
+ flags[normalizedArg] = value;
264
253
  flags.knownArgs.push(rawArg);
265
254
  flags.knownArgs.push(value);
266
- }
267
- } else throwCLIParsingError(rawArg, "expected a string argument but received nothing");
268
- else if (readOnlyArrayHasStringMember(NUMBER_CLI_FLAGS, normalizedArg)) if (typeof value === "string") {
269
- const parsed = parseInt(value, 10);
270
- if (isNaN(parsed)) throwNumberParsingError(rawArg, value);
271
- else {
272
- flags[normalizedArg] = parsed;
255
+ } else throwCLIParsingError(rawArg, "expected a string argument but received nothing");
256
+ } else if (STRING_ARRAY_CLI_FLAGS.length > 0 && readOnlyArrayHasStringMember(STRING_ARRAY_CLI_FLAGS, normalizedArg)) {
257
+ if (typeof value === "string") {
258
+ const flagsRecord = flags;
259
+ if (!Array.isArray(flagsRecord[normalizedArg])) flagsRecord[normalizedArg] = [];
260
+ const targetArray = flagsRecord[normalizedArg];
261
+ if (Array.isArray(targetArray)) {
262
+ targetArray.push(value);
263
+ flags.knownArgs.push(rawArg);
264
+ flags.knownArgs.push(value);
265
+ }
266
+ } else throwCLIParsingError(rawArg, "expected a string argument but received nothing");
267
+ } else if (readOnlyArrayHasStringMember(NUMBER_CLI_FLAGS, normalizedArg)) {
268
+ if (typeof value === "string") {
269
+ const parsed = parseInt(value, 10);
270
+ if (isNaN(parsed)) throwNumberParsingError(rawArg, value);
271
+ else {
272
+ flags[normalizedArg] = parsed;
273
+ flags.knownArgs.push(rawArg);
274
+ flags.knownArgs.push(value);
275
+ }
276
+ } else throwCLIParsingError(rawArg, "expected a number argument but received nothing");
277
+ } else if (readOnlyArrayHasStringMember(STRING_NUMBER_CLI_FLAGS, normalizedArg)) {
278
+ if (typeof value === "string") {
279
+ if (CLI_ARG_STRING_REGEX.test(value)) flags[normalizedArg] = value;
280
+ else {
281
+ const parsed = Number(value);
282
+ if (isNaN(parsed)) throwNumberParsingError(rawArg, value);
283
+ else flags[normalizedArg] = parsed;
284
+ }
273
285
  flags.knownArgs.push(rawArg);
274
286
  flags.knownArgs.push(value);
275
- }
276
- } else throwCLIParsingError(rawArg, "expected a number argument but received nothing");
277
- else if (readOnlyArrayHasStringMember(STRING_NUMBER_CLI_FLAGS, normalizedArg)) if (typeof value === "string") {
278
- if (CLI_ARG_STRING_REGEX.test(value)) flags[normalizedArg] = value;
279
- else {
280
- const parsed = Number(value);
281
- if (isNaN(parsed)) throwNumberParsingError(rawArg, value);
282
- else flags[normalizedArg] = parsed;
283
- }
284
- flags.knownArgs.push(rawArg);
285
- flags.knownArgs.push(value);
286
- } else throwCLIParsingError(rawArg, "expected a string or a number but received nothing");
287
- else if (readOnlyArrayHasStringMember(BOOLEAN_STRING_CLI_FLAGS, normalizedArg)) {
287
+ } else throwCLIParsingError(rawArg, "expected a string or a number but received nothing");
288
+ } else if (readOnlyArrayHasStringMember(BOOLEAN_STRING_CLI_FLAGS, normalizedArg)) {
288
289
  const derivedValue = typeof value === "string" ? value ? value : false : true;
289
290
  flags[normalizedArg] = derivedValue;
290
291
  flags.knownArgs.push(rawArg);
291
292
  if (typeof derivedValue === "string" && derivedValue) flags.knownArgs.push(derivedValue);
292
- } else if (readOnlyArrayHasStringMember(LOG_LEVEL_CLI_FLAGS, normalizedArg)) if (typeof value === "string") if (isLogLevel(value)) {
293
- flags[normalizedArg] = value;
294
- flags.knownArgs.push(rawArg);
295
- flags.knownArgs.push(value);
296
- } else throwCLIParsingError(rawArg, `expected to receive a valid log level but received "${String(value)}"`);
297
- else throwCLIParsingError(rawArg, "expected to receive a valid log level but received nothing");
298
- else {
293
+ } else if (readOnlyArrayHasStringMember(LOG_LEVEL_CLI_FLAGS, normalizedArg)) {
294
+ if (typeof value === "string") {
295
+ if (isLogLevel(value)) {
296
+ flags[normalizedArg] = value;
297
+ flags.knownArgs.push(rawArg);
298
+ flags.knownArgs.push(value);
299
+ } else throwCLIParsingError(rawArg, `expected to receive a valid log level but received "${String(value)}"`);
300
+ } else throwCLIParsingError(rawArg, "expected to receive a valid log level but received nothing");
301
+ } else {
299
302
  flags.unknownArgs.push(rawArg);
300
303
  if (typeof value === "string") flags.unknownArgs.push(value);
301
304
  }
@@ -446,9 +449,10 @@ const findConfig = async (opts) => {
446
449
  const cwd = sys.getCurrentDirectory();
447
450
  const rootDir = normalizePath(cwd);
448
451
  let configPath = opts.configPath;
449
- if (isString(configPath)) if (!sys.platformPath.isAbsolute(configPath)) configPath = normalizePath(sys.platformPath.join(cwd, configPath));
450
- else configPath = normalizePath(configPath);
451
- else configPath = rootDir;
452
+ if (isString(configPath)) {
453
+ if (!sys.platformPath.isAbsolute(configPath)) configPath = normalizePath(sys.platformPath.join(cwd, configPath));
454
+ else configPath = normalizePath(configPath);
455
+ } else configPath = rootDir;
452
456
  const results = {
453
457
  configPath: null,
454
458
  rootDir: normalizePath(cwd)
@@ -601,6 +605,166 @@ const mergeFlags = (config, flags) => {
601
605
  return merged;
602
606
  };
603
607
  //#endregion
608
+ //#region src/wizard/config-editor.ts
609
+ async function openStencilConfig(configPath) {
610
+ let text = await readFile(configPath, "utf8");
611
+ const parse = () => ts.createSourceFile(configPath, text, ts.ScriptTarget.Latest, true);
612
+ function findArray(sf, propName) {
613
+ let found;
614
+ const visit = (node) => {
615
+ if (!found && ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === propName && ts.isArrayLiteralExpression(node.initializer)) found = node.initializer;
616
+ else ts.forEachChild(node, visit);
617
+ };
618
+ visit(sf);
619
+ return found;
620
+ }
621
+ function findConfigObject(sf) {
622
+ for (const stmt of sf.statements) if (ts.isVariableStatement(stmt)) {
623
+ for (const decl of stmt.declarationList.declarations) if (ts.isIdentifier(decl.name) && decl.name.text === "config" && decl.initializer && ts.isObjectLiteralExpression(decl.initializer)) return decl.initializer;
624
+ }
625
+ let found;
626
+ const visit = (node) => {
627
+ if (found) return;
628
+ if (ts.isObjectLiteralExpression(node)) {
629
+ if (node.properties.some((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "namespace")) {
630
+ found = node;
631
+ return;
632
+ }
633
+ }
634
+ ts.forEachChild(node, visit);
635
+ };
636
+ visit(sf);
637
+ return found;
638
+ }
639
+ function replaceInArray(arr, substring, expression) {
640
+ for (const element of arr.elements) if (text.slice(element.getStart(), element.getEnd()).includes(substring)) {
641
+ const lineStart = text.lastIndexOf("\n", element.getStart()) + 1;
642
+ const indent = text.slice(lineStart, element.getStart()).match(/^\s+/)?.[0] ?? "";
643
+ const indentedExpression = indent ? expression.replace(/\n/g, `\n${indent}`) : expression;
644
+ text = text.slice(0, element.getStart()) + indentedExpression + text.slice(element.getEnd());
645
+ return true;
646
+ }
647
+ return false;
648
+ }
649
+ function removeFromArray(arr, substring) {
650
+ const idx = arr.elements.findIndex((element) => text.slice(element.getStart(), element.getEnd()).includes(substring));
651
+ if (idx === -1) return false;
652
+ const element = arr.elements[idx];
653
+ if (arr.elements.length > 0 && text.slice(arr.getStart(), arr.elements[0].getStart()).includes("\n")) {
654
+ const lineStart = text.lastIndexOf("\n", element.getStart());
655
+ let end = element.getEnd();
656
+ const trailingComma = text.slice(end).match(/^\s*,/);
657
+ if (trailingComma) end += trailingComma[0].length;
658
+ text = text.slice(0, lineStart) + text.slice(end);
659
+ } else {
660
+ let start = element.getStart();
661
+ let end = element.getEnd();
662
+ if (idx < arr.elements.length - 1) {
663
+ const trailingMatch = text.slice(end).match(/^,\s*/);
664
+ if (trailingMatch) end += trailingMatch[0].length;
665
+ } else if (idx > 0) {
666
+ const precedingMatch = text.slice(0, start).match(/,\s*$/);
667
+ if (precedingMatch) start -= precedingMatch[0].length;
668
+ }
669
+ text = text.slice(0, start) + text.slice(end);
670
+ }
671
+ return true;
672
+ }
673
+ function appendToArray(arr, code) {
674
+ if (arr.elements.length === 0) {
675
+ const insertPos = arr.getEnd() - 1;
676
+ text = text.slice(0, insertPos) + code + text.slice(insertPos);
677
+ return;
678
+ }
679
+ let insertPos = arr.elements[arr.elements.length - 1].getEnd();
680
+ const trailingComma = text.slice(insertPos).match(/^\s*,/);
681
+ if (trailingComma) insertPos += trailingComma[0].length;
682
+ const separator = trailingComma ? "" : ",";
683
+ const firstElemStart = arr.elements[0].getStart();
684
+ if (text.slice(arr.getStart(), firstElemStart).includes("\n")) {
685
+ const lineStart = text.lastIndexOf("\n", firstElemStart) + 1;
686
+ const indent = text.slice(lineStart, firstElemStart).match(/^\s+/)?.[0] ?? " ";
687
+ const indentedCode = code.replace(/\n/g, `\n${indent}`);
688
+ text = `${text.slice(0, insertPos)}${separator}\n${indent}${indentedCode}${text.slice(insertPos)}`;
689
+ } else text = `${text.slice(0, insertPos)}${separator} ${code}${text.slice(insertPos)}`;
690
+ }
691
+ function addArrayProp(sf, propName, code) {
692
+ const configObj = findConfigObject(sf);
693
+ if (!configObj) throw new Error("Could not find Stencil config object in stencil.config.ts");
694
+ let propIndent = " ";
695
+ if (configObj.properties.length > 0) {
696
+ const firstPropStart = configObj.properties[0].getStart();
697
+ const lineStart = text.lastIndexOf("\n", firstPropStart) + 1;
698
+ propIndent = text.slice(lineStart, firstPropStart).match(/^\s+/)?.[0] ?? " ";
699
+ }
700
+ const elemIndent = propIndent + " ";
701
+ const newProp = `${propName}: [\n${elemIndent}${code.replace(/\n/g, `\n${elemIndent}`)},\n${propIndent}]`;
702
+ const lastProp = configObj.properties[configObj.properties.length - 1];
703
+ if (lastProp) {
704
+ let insertPos = lastProp.getEnd();
705
+ const trailingComma = text.slice(insertPos).match(/^\s*,/);
706
+ const separator = trailingComma ? "" : ",";
707
+ if (trailingComma) insertPos += trailingComma[0].length;
708
+ text = `${text.slice(0, insertPos)}${separator}\n${propIndent}${newProp}${text.slice(insertPos)}`;
709
+ } else {
710
+ const insertPos = configObj.getEnd() - 1;
711
+ text = `${text.slice(0, insertPos)}\n${propIndent}${newProp},\n${text.slice(insertPos)}`;
712
+ }
713
+ }
714
+ return {
715
+ hasImport(moduleSpecifier) {
716
+ return parse().statements.some((s) => ts.isImportDeclaration(s) && ts.isStringLiteral(s.moduleSpecifier) && s.moduleSpecifier.text === moduleSpecifier);
717
+ },
718
+ addImport(moduleSpecifier, namedImports) {
719
+ const sf = parse();
720
+ if (sf.statements.some((s) => ts.isImportDeclaration(s) && ts.isStringLiteral(s.moduleSpecifier) && s.moduleSpecifier.text === moduleSpecifier)) return;
721
+ let insertPos = 0;
722
+ for (const s of sf.statements) if (ts.isImportDeclaration(s)) insertPos = s.getEnd();
723
+ const decl = `\nimport { ${namedImports.join(", ")} } from '${moduleSpecifier}';`;
724
+ text = insertPos > 0 ? text.slice(0, insertPos) + decl + text.slice(insertPos) : decl + "\n" + text;
725
+ },
726
+ outputTargetsContains(substring) {
727
+ const arr = findArray(parse(), "outputTargets");
728
+ return arr ? text.slice(arr.getStart(), arr.getEnd()).includes(substring) : false;
729
+ },
730
+ addOutputTarget(expression) {
731
+ const sf = parse();
732
+ const arr = findArray(sf, "outputTargets");
733
+ if (arr) appendToArray(arr, expression);
734
+ else addArrayProp(sf, "outputTargets", expression);
735
+ },
736
+ replaceOutputTarget(substring, expression) {
737
+ const arr = findArray(parse(), "outputTargets");
738
+ return arr ? replaceInArray(arr, substring, expression) : false;
739
+ },
740
+ removeOutputTarget(substring) {
741
+ const arr = findArray(parse(), "outputTargets");
742
+ return arr ? removeFromArray(arr, substring) : false;
743
+ },
744
+ pluginsContains(substring) {
745
+ const arr = findArray(parse(), "plugins");
746
+ return arr ? text.slice(arr.getStart(), arr.getEnd()).includes(substring) : false;
747
+ },
748
+ addPlugin(expression) {
749
+ const sf = parse();
750
+ const arr = findArray(sf, "plugins");
751
+ if (arr) appendToArray(arr, expression);
752
+ else addArrayProp(sf, "plugins", expression);
753
+ },
754
+ replacePlugin(substring, expression) {
755
+ const arr = findArray(parse(), "plugins");
756
+ return arr ? replaceInArray(arr, substring, expression) : false;
757
+ },
758
+ removePlugin(substring) {
759
+ const arr = findArray(parse(), "plugins");
760
+ return arr ? removeFromArray(arr, substring) : false;
761
+ },
762
+ async save() {
763
+ await writeFile(configPath, text, "utf8");
764
+ }
765
+ };
766
+ }
767
+ //#endregion
604
768
  //#region src/wizard/discover.ts
605
769
  function toStringRecord(val) {
606
770
  return val !== null && typeof val === "object" ? val : {};
@@ -613,9 +777,11 @@ async function readJson$1(filePath) {
613
777
  }
614
778
  }
615
779
  async function loadOne(rootDir, packageName, loader) {
616
- const wizardEntry = ((await readJson$1(join(rootDir, "node_modules", packageName, "package.json")))?.stencil)?.wizard;
780
+ const info = await getPackageInfo(packageName, { paths: [rootDir] });
781
+ if (!info) return null;
782
+ const wizardEntry = info.packageJson.stencil?.wizard;
617
783
  if (!wizardEntry) return null;
618
- const wizardPath = join(rootDir, "node_modules", packageName, wizardEntry);
784
+ const wizardPath = join(info.rootPath, wizardEntry);
619
785
  let mod;
620
786
  try {
621
787
  mod = await loader(pathToFileURL(wizardPath).href);
@@ -645,15 +811,18 @@ async function loadOne(rootDir, packageName, loader) {
645
811
  async function discoverPlugins(rootDir, loader = (url) => import(url)) {
646
812
  const pkg = await readJson$1(join(rootDir, "package.json"));
647
813
  if (!pkg) return [];
648
- const depNames = [...new Set([...Object.keys(toStringRecord(pkg.dependencies)), ...Object.keys(toStringRecord(pkg.devDependencies))])];
814
+ const depNames = [.../* @__PURE__ */ new Set([...Object.keys(toStringRecord(pkg.dependencies)), ...Object.keys(toStringRecord(pkg.devDependencies))])];
649
815
  const plugins = (await Promise.allSettled(depNames.map((name) => loadOne(rootDir, name, loader)))).filter((r) => r.status === "fulfilled" && r.value !== null).map((r) => r.value);
650
- const devPath = process.env.STENCIL_WIZARD_DEV;
651
- if (devPath) {
652
- const devPlugin = await loadDevPlugin(resolve(rootDir, devPath), loader);
653
- if (devPlugin) {
654
- const deduped = plugins.filter((p) => p.packageName !== devPlugin.packageName);
655
- plugins.length = 0;
656
- plugins.push(devPlugin, ...deduped);
816
+ const devEnv = process.env.STENCIL_WIZARD_DEV;
817
+ if (devEnv) {
818
+ const devPaths = devEnv.split(",").map((s) => s.trim()).filter(Boolean);
819
+ for (const devPath of devPaths) {
820
+ const devPlugin = await loadDevPlugin(resolve(rootDir, devPath), loader);
821
+ if (devPlugin) {
822
+ const idx = plugins.findIndex((p) => p.packageName === devPlugin.packageName);
823
+ if (idx >= 0) plugins.splice(idx, 1, devPlugin);
824
+ else plugins.unshift(devPlugin);
825
+ }
657
826
  }
658
827
  }
659
828
  return plugins;
@@ -719,45 +888,61 @@ const KNOWN_INTEGRATIONS = [
719
888
  package: "@stencil/sass",
720
889
  displayName: "Sass",
721
890
  description: "Sass/SCSS styles",
722
- group: "Styling"
891
+ group: "Styling",
892
+ requiresStencilConfig: true
723
893
  },
724
894
  {
725
895
  package: "@stencil/eslint-plugin",
726
896
  displayName: "ESLint Plugin",
727
- description: "Stencil-aware lint rules (ESLint, oxlint, Biome)",
728
- group: "Linting"
897
+ description: "Stencil-aware lint rules (ESLint or oxlint)",
898
+ group: "Tooling"
729
899
  },
730
900
  {
731
901
  package: "@stencil/storybook-plugin",
732
902
  displayName: "Storybook",
733
903
  description: "Component development & documentation",
734
- group: "Tooling"
904
+ group: "Tooling",
905
+ versionRange: ">=1.0.0-0"
735
906
  },
736
907
  {
737
908
  package: "@stencil/types-output-target",
738
909
  displayName: "Types",
739
910
  description: "TypeScript types for React, Vue, Solid, Svelte, Preact",
740
- group: "Framework integrations"
911
+ group: "Framework integrations",
912
+ requiresStencilConfig: true
741
913
  },
742
914
  {
743
915
  package: "@stencil/react-output-target",
744
916
  displayName: "React",
745
917
  description: "React component wrappers",
746
- group: "Framework integrations"
918
+ group: "Framework integrations",
919
+ requiresStencilConfig: true,
920
+ needsWorkspace: true
747
921
  },
748
922
  {
749
923
  package: "@stencil/angular-output-target",
750
924
  displayName: "Angular",
751
925
  description: "Angular component wrappers",
752
- group: "Framework integrations"
926
+ group: "Framework integrations",
927
+ requiresStencilConfig: true,
928
+ needsWorkspace: true
753
929
  },
754
930
  {
755
931
  package: "@stencil/vue-output-target",
756
932
  displayName: "Vue",
757
933
  description: "Vue component wrappers",
758
- group: "Framework integrations"
934
+ group: "Framework integrations",
935
+ requiresStencilConfig: true,
936
+ needsWorkspace: true
759
937
  }
760
938
  ];
939
+ const versionRangeByPackage = new Map(KNOWN_INTEGRATIONS.filter((i) => i.versionRange).map((i) => [i.package, i.versionRange]));
940
+ function withVersionRanges(packages) {
941
+ return packages.map((pkg) => {
942
+ const range = versionRangeByPackage.get(pkg);
943
+ return range ? `${pkg}@${range}` : pkg;
944
+ });
945
+ }
761
946
  async function promptOutputs() {
762
947
  const picks = await p.multiselect({
763
948
  message: "Outputs:",
@@ -837,13 +1022,17 @@ async function promptDocs() {
837
1022
  label: "JSON",
838
1023
  hint: "docs.json - Stencil / Ionic centric schema"
839
1024
  },
1025
+ {
1026
+ value: "skill",
1027
+ label: "AI Skill",
1028
+ hint: "dist/skill/SKILL.md - Agent Skill (agentskills.io) reference for AI coding agents"
1029
+ },
840
1030
  {
841
1031
  value: "vscode",
842
1032
  label: "VS Code",
843
1033
  hint: "vscode-data.json - editor autocomplete for your components"
844
1034
  }
845
1035
  ],
846
- initialValues: ["cem"],
847
1036
  required: false
848
1037
  });
849
1038
  cancelIfAborted(picks);
@@ -887,6 +1076,29 @@ async function promptIntegrations() {
887
1076
  cancelIfAborted(picks);
888
1077
  return KNOWN_INTEGRATIONS.filter((i) => picks.includes(i.package));
889
1078
  }
1079
+ function hasFrameworkTargets(integrations) {
1080
+ return integrations.some((i) => i.needsWorkspace);
1081
+ }
1082
+ function needsStencilConfig(integrations) {
1083
+ return integrations.some((i) => i.requiresStencilConfig);
1084
+ }
1085
+ async function promptMonorepo() {
1086
+ const answer = await p.confirm({
1087
+ message: "Set up as a monorepo workspace? (recommended for publishing framework wrappers)",
1088
+ initialValue: true
1089
+ });
1090
+ cancelIfAborted(answer);
1091
+ return answer;
1092
+ }
1093
+ async function promptWorkspaceCoreName() {
1094
+ const name = await p.text({
1095
+ message: "Core package directory name:",
1096
+ defaultValue: "core",
1097
+ placeholder: "core"
1098
+ });
1099
+ cancelIfAborted(name);
1100
+ return name || "core";
1101
+ }
890
1102
  /**
891
1103
  * Prompt for actions on an existing project: install new integrations and/or
892
1104
  * run init wizards for already-installed packages with wizard contributions.
@@ -958,6 +1170,27 @@ function defaultProjectConfig(rootDir, overrides) {
958
1170
  };
959
1171
  }
960
1172
  /**
1173
+ * Walk up from `startDir` looking for a monorepo workspace root — a directory
1174
+ * containing `pnpm-workspace.yaml` or a `package.json` with a `workspaces` field.
1175
+ * Stops at the home directory or filesystem root. Returns `undefined` if none found.
1176
+ * @param startDir The directory to start searching from.
1177
+ * @returns A promise that resolves to the workspace root directory, or undefined if none found.
1178
+ */
1179
+ async function detectWorkspaceRoot(startDir) {
1180
+ const home = homedir();
1181
+ let dir = startDir;
1182
+ while (true) {
1183
+ if (existsSync(join(dir, "pnpm-workspace.yaml"))) return dir;
1184
+ try {
1185
+ const pkg = JSON.parse(await readFile(join(dir, "package.json"), "utf8"));
1186
+ if (Array.isArray(pkg.workspaces)) return dir;
1187
+ } catch {}
1188
+ const parent = dirname(dir);
1189
+ if (parent === dir || dir === home) return void 0;
1190
+ dir = parent;
1191
+ }
1192
+ }
1193
+ /**
961
1194
  * Returns true if the directory looks like an existing Stencil project:
962
1195
  * - has an explicit `stencil.config.ts`, OR
963
1196
  * - has `.tsx` files under `src/` (zero-config project).
@@ -977,7 +1210,7 @@ async function isExistingStencilProject(dir) {
977
1210
  }
978
1211
  //#endregion
979
1212
  //#region src/wizard/splash.ts
980
- const CLI_VERSION = "5.0.0-alpha.8";
1213
+ const CLI_VERSION = "5.0.0-beta.0";
981
1214
  const isTTY = process.stdout.isTTY;
982
1215
  const noColor = !isTTY || "NO_COLOR" in process.env;
983
1216
  const RESET = noColor ? "" : "\x1B[0m";
@@ -1035,7 +1268,7 @@ async function getInstalledPackageNames(rootDir) {
1035
1268
  try {
1036
1269
  const pkg = JSON.parse(await readFile(join(rootDir, "package.json"), "utf8"));
1037
1270
  const keys = (v) => Object.keys(v !== null && typeof v === "object" ? v : {});
1038
- return new Set([...keys(pkg.dependencies), ...keys(pkg.devDependencies)]);
1271
+ return /* @__PURE__ */ new Set([...keys(pkg.dependencies), ...keys(pkg.devDependencies)]);
1039
1272
  } catch {
1040
1273
  return /* @__PURE__ */ new Set();
1041
1274
  }
@@ -1073,21 +1306,28 @@ async function taskAdd(packages, strictConfig) {
1073
1306
  p.outro("Nothing to do.");
1074
1307
  return;
1075
1308
  }
1076
- 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}`);
1077
- else {
1078
- const s = p.spinner();
1079
- s.start(`Installing ${packagesToInstall.join(", ")}`);
1080
- await addDevDependency(packagesToInstall, {
1081
- cwd,
1082
- silent: true
1083
- });
1084
- s.stop("Installed");
1309
+ if (packagesToInstall.length > 0) {
1310
+ if (process.env.STENCIL_WIZARD_DEV) p.log.warn(`Dev mode: skipping install, loading wizard from ${process.env.STENCIL_WIZARD_DEV}`);
1311
+ else {
1312
+ const s = p.spinner();
1313
+ s.start(`Installing ${packagesToInstall.join(", ")}`);
1314
+ await addDevDependency(withVersionRanges(packagesToInstall), {
1315
+ cwd,
1316
+ silent: true
1317
+ });
1318
+ s.stop("Installed");
1319
+ }
1085
1320
  }
1321
+ const config = strictConfig ? toProjectConfig(strictConfig) : defaultProjectConfig(cwd);
1322
+ const workspaceRoot = await detectWorkspaceRoot(cwd);
1086
1323
  const context = {
1087
1324
  isNewProject: false,
1088
1325
  prompts: p,
1089
1326
  nypm,
1090
- config: strictConfig ? toProjectConfig(strictConfig) : defaultProjectConfig(cwd)
1327
+ config,
1328
+ workspaceRoot,
1329
+ ts,
1330
+ openStencilConfig: () => openStencilConfig(join(config.rootDir, "stencil.config.ts"))
1091
1331
  };
1092
1332
  if (packagesToInstall.length > 0) {
1093
1333
  const discovered = await discoverPlugins(cwd);
@@ -1233,6 +1473,78 @@ const buildDistDocsRule = {
1233
1473
  }
1234
1474
  };
1235
1475
  //#endregion
1476
+ //#region src/migrations/rules/css-import-query-param.ts
1477
+ /**
1478
+ * Ambient module extensions Stencil declares its own type for. In v5 these
1479
+ * now require a `?stencil` query-param marker (see `stencil-ext-modules.d.ts`)
1480
+ * so the ambient declaration doesn't clash with other `*.css` etc. typings in
1481
+ * a monorepo.
1482
+ */
1483
+ const AMBIENT_ASSET_EXTS = [
1484
+ ".css",
1485
+ ".svg",
1486
+ ".txt",
1487
+ ".frag",
1488
+ ".vert"
1489
+ ];
1490
+ const needsStencilMarker = (specifier) => {
1491
+ if (specifier.includes("?")) return false;
1492
+ const lower = specifier.toLowerCase();
1493
+ return AMBIENT_ASSET_EXTS.some((ext) => lower.endsWith(ext));
1494
+ };
1495
+ /**
1496
+ * Migration rule appending `?stencil` to raw asset import specifiers.
1497
+ *
1498
+ * Migrates:
1499
+ * - `import styles from './my-component.css'` → `import styles from './my-component.css?stencil'`
1500
+ * - `import logo from './logo.svg'` → `import logo from './logo.svg?stencil'`
1501
+ *
1502
+ * Does not touch `styleUrl`/`styleUrls` values in `@Component()` options - those are
1503
+ * compiler-resolved filenames, not import specifiers, and are never typed against the
1504
+ * ambient module declarations.
1505
+ */
1506
+ const cssImportQueryParamRule = {
1507
+ id: "css-import-query-param",
1508
+ name: "Asset Import Query Param",
1509
+ description: "Append '?stencil' to raw *.css/*.svg/*.txt/*.frag/*.vert imports so they match Stencil's ambient module types",
1510
+ fromVersion: "4.x",
1511
+ toVersion: "5.x",
1512
+ detect(sourceFile) {
1513
+ const matches = [];
1514
+ const visit = (node) => {
1515
+ let specifierNode;
1516
+ if ((ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) && node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) specifierNode = node.moduleSpecifier;
1517
+ else if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword && node.arguments.length > 0 && ts.isStringLiteral(node.arguments[0])) specifierNode = node.arguments[0];
1518
+ if (specifierNode && needsStencilMarker(specifierNode.text)) {
1519
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(specifierNode.getStart());
1520
+ matches.push({
1521
+ node: specifierNode,
1522
+ message: `Raw asset import '${specifierNode.text}' needs a '?stencil' suffix to match Stencil's ambient module type`,
1523
+ line: line + 1,
1524
+ column: character + 1
1525
+ });
1526
+ }
1527
+ ts.forEachChild(node, visit);
1528
+ };
1529
+ visit(sourceFile);
1530
+ return matches;
1531
+ },
1532
+ transform(sourceFile, matches) {
1533
+ if (matches.length === 0) return sourceFile.getFullText();
1534
+ let text = sourceFile.getFullText();
1535
+ const sortedMatches = [...matches].sort((a, b) => b.node.getStart() - a.node.getStart());
1536
+ for (const match of sortedMatches) {
1537
+ const node = match.node;
1538
+ const start = node.getStart();
1539
+ const end = node.getEnd();
1540
+ const quote = node.getText(sourceFile)[0];
1541
+ const updated = `${quote}${node.text}?stencil${quote}`;
1542
+ text = text.slice(0, start) + updated + text.slice(end);
1543
+ }
1544
+ return text;
1545
+ }
1546
+ };
1547
+ //#endregion
1236
1548
  //#region src/migrations/rules/dev-mode.ts
1237
1549
  /**
1238
1550
  * Migration rule for `devMode` config option removal.
@@ -1282,6 +1594,66 @@ const devModeRule = {
1282
1594
  }
1283
1595
  };
1284
1596
  //#endregion
1597
+ //#region src/migrations/rules/enable-import-injection-default.ts
1598
+ /**
1599
+ * Migration rule: drop `extras.enableImportInjection: true`.
1600
+ *
1601
+ * In v4 this flag defaulted to `false`, so an explicit `true` was meaningful. In v5 it
1602
+ * defaults to `true`, so an explicit `true` is now a no-op. `false` (opting out) is left alone.
1603
+ */
1604
+ const enableImportInjectionDefaultRule = {
1605
+ id: "enable-import-injection-default",
1606
+ name: "Drop redundant enableImportInjection: true",
1607
+ description: "Remove 'extras.enableImportInjection: true' now that it's the v5 default",
1608
+ fromVersion: "4.x",
1609
+ toVersion: "5.x",
1610
+ detect(sourceFile) {
1611
+ const matches = [];
1612
+ const visit = (node) => {
1613
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === "enableImportInjection" && node.initializer.kind === ts.SyntaxKind.TrueKeyword) {
1614
+ const parent = node.parent;
1615
+ if (ts.isObjectLiteralExpression(parent)) {
1616
+ const grandparent = parent.parent;
1617
+ if (ts.isPropertyAssignment(grandparent) && ts.isIdentifier(grandparent.name) && grandparent.name.text === "extras") {
1618
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
1619
+ matches.push({
1620
+ node,
1621
+ message: "'extras.enableImportInjection: true' is now the default and can be removed",
1622
+ line: line + 1,
1623
+ column: character + 1
1624
+ });
1625
+ }
1626
+ }
1627
+ }
1628
+ ts.forEachChild(node, visit);
1629
+ };
1630
+ visit(sourceFile);
1631
+ return matches;
1632
+ },
1633
+ transform(sourceFile, matches) {
1634
+ if (matches.length === 0) return sourceFile.getFullText();
1635
+ let text = sourceFile.getFullText();
1636
+ const sorted = [...matches].sort((a, b) => b.node.getStart() - a.node.getStart());
1637
+ for (const match of sorted) {
1638
+ const node = match.node;
1639
+ let start = node.getStart();
1640
+ let end = node.getEnd();
1641
+ const trailingComma = text.slice(end).match(/^(\s*,)/);
1642
+ if (trailingComma) end += trailingComma[1].length;
1643
+ else {
1644
+ const leadingComma = text.slice(0, start).match(/,\s*$/);
1645
+ if (leadingComma) start -= leadingComma[0].length;
1646
+ }
1647
+ text = text.slice(0, start) + text.slice(end);
1648
+ }
1649
+ text = cleanupEmptyExtras$2(text);
1650
+ return text;
1651
+ }
1652
+ };
1653
+ function cleanupEmptyExtras$2(text) {
1654
+ return text.replace(/,?\s*extras\s*:\s*\{\s*\},?/g, "");
1655
+ }
1656
+ //#endregion
1285
1657
  //#region src/migrations/rules/encapsulation-api.ts
1286
1658
  /**
1287
1659
  * Migration rule for the @Component encapsulation API change.
@@ -1339,20 +1711,22 @@ const encapsulationApiRule = {
1339
1711
  const start = prop.getStart();
1340
1712
  const end = prop.getEnd();
1341
1713
  let replacement;
1342
- if (propName === "shadow") if (prop.initializer.kind === ts.SyntaxKind.TrueKeyword) replacement = "encapsulation: { type: 'shadow' }";
1343
- else if (ts.isObjectLiteralExpression(prop.initializer)) {
1344
- const options = [];
1345
- for (const innerProp of prop.initializer.properties) if (ts.isPropertyAssignment(innerProp) && ts.isIdentifier(innerProp.name)) {
1346
- const optName = innerProp.name.text;
1347
- const optValue = innerProp.initializer.getText();
1348
- options.push(`${optName}: ${optValue}`);
1349
- }
1350
- if (options.length > 0) replacement = `encapsulation: { type: 'shadow', ${options.join(", ")} }`;
1351
- else replacement = "encapsulation: { type: 'shadow' }";
1352
- } else replacement = "";
1353
- else if (propName === "scoped") if (prop.initializer.kind === ts.SyntaxKind.TrueKeyword) replacement = "encapsulation: { type: 'scoped' }";
1354
- else replacement = "";
1355
- else continue;
1714
+ if (propName === "shadow") {
1715
+ if (prop.initializer.kind === ts.SyntaxKind.TrueKeyword) replacement = "encapsulation: { type: 'shadow' }";
1716
+ else if (ts.isObjectLiteralExpression(prop.initializer)) {
1717
+ const options = [];
1718
+ for (const innerProp of prop.initializer.properties) if (ts.isPropertyAssignment(innerProp) && ts.isIdentifier(innerProp.name)) {
1719
+ const optName = innerProp.name.text;
1720
+ const optValue = innerProp.initializer.getText();
1721
+ options.push(`${optName}: ${optValue}`);
1722
+ }
1723
+ if (options.length > 0) replacement = `encapsulation: { type: 'shadow', ${options.join(", ")} }`;
1724
+ else replacement = "encapsulation: { type: 'shadow' }";
1725
+ } else replacement = "";
1726
+ } else if (propName === "scoped") {
1727
+ if (prop.initializer.kind === ts.SyntaxKind.TrueKeyword) replacement = "encapsulation: { type: 'scoped' }";
1728
+ else replacement = "";
1729
+ } else continue;
1356
1730
  let endPos = end;
1357
1731
  const afterProp = text.slice(end).match(/^\s*,/);
1358
1732
  if (afterProp && replacement === "") endPos = end + afterProp[0].length;
@@ -1773,7 +2147,7 @@ const hashFileNamesRule = {
1773
2147
  value: node.initializer.getText(sourceFile)
1774
2148
  };
1775
2149
  });
1776
- const TARGET_TYPES = new Set(["loader-bundle", "www"]);
2150
+ const TARGET_TYPES = /* @__PURE__ */ new Set(["loader-bundle", "www"]);
1777
2151
  const insertionsByPos = /* @__PURE__ */ new Map();
1778
2152
  const visit = (node) => {
1779
2153
  if (ts.isObjectLiteralExpression(node)) {
@@ -1850,7 +2224,7 @@ const lightDomPatchesRule = {
1850
2224
  toVersion: "5.x",
1851
2225
  detect(sourceFile) {
1852
2226
  const matches = [];
1853
- const oldKeys = new Set([
2227
+ const oldKeys = /* @__PURE__ */ new Set([
1854
2228
  "experimentalSlotFixes",
1855
2229
  "appendChildSlotFix",
1856
2230
  "cloneNodeFix",
@@ -2170,7 +2544,7 @@ function addExtractedOutputTargets(text, sourceFile, toExtract) {
2170
2544
  * NodeResolve fields that were valid in @rollup/plugin-node-resolve but don't exist
2171
2545
  * in rolldown's native resolver and should be removed.
2172
2546
  */
2173
- const REMOVED_NODE_RESOLVE_FIELDS = new Set([
2547
+ const REMOVED_NODE_RESOLVE_FIELDS = /* @__PURE__ */ new Set([
2174
2548
  "browser",
2175
2549
  "modulePaths",
2176
2550
  "dedupe",
@@ -2384,6 +2758,91 @@ const serviceWorkerDefaultRule = {
2384
2758
  }
2385
2759
  };
2386
2760
  //#endregion
2761
+ //#region src/migrations/rules/suppress-warnings-to-compat.ts
2762
+ /**
2763
+ * Migration rule: move `suppressReservedPublicNameWarnings` / `suppressReservedEventNameWarnings`
2764
+ * off the top level of the config and into `compat`, dropping `Reserved` from their names.
2765
+ *
2766
+ * In v5:
2767
+ * suppressReservedPublicNameWarnings → compat.suppressPublicNameWarnings
2768
+ * suppressReservedEventNameWarnings → compat.suppressEventNameWarnings
2769
+ */
2770
+ const KEY_RENAME = {
2771
+ suppressReservedPublicNameWarnings: "suppressPublicNameWarnings",
2772
+ suppressReservedEventNameWarnings: "suppressEventNameWarnings"
2773
+ };
2774
+ const suppressWarningsToCompatRule = {
2775
+ id: "suppress-warnings-to-compat",
2776
+ name: "Suppress Warnings → Compat",
2777
+ description: "Move 'suppressReservedPublicNameWarnings' / 'suppressReservedEventNameWarnings' into 'compat'",
2778
+ fromVersion: "4.x",
2779
+ toVersion: "5.x",
2780
+ detect(sourceFile) {
2781
+ const matches = [];
2782
+ const visit = (node) => {
2783
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text in KEY_RENAME) {
2784
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
2785
+ matches.push({
2786
+ node,
2787
+ message: `'${node.name.text}' has moved to 'compat.${KEY_RENAME[node.name.text]}'`,
2788
+ line: line + 1,
2789
+ column: character + 1
2790
+ });
2791
+ }
2792
+ ts.forEachChild(node, visit);
2793
+ };
2794
+ visit(sourceFile);
2795
+ return matches;
2796
+ },
2797
+ transform(sourceFile, matches) {
2798
+ if (matches.length === 0) return sourceFile.getFullText();
2799
+ const text = sourceFile.getFullText();
2800
+ const edits = [];
2801
+ const newProps = [];
2802
+ for (const match of matches) {
2803
+ const node = match.node;
2804
+ const key = node.name.text;
2805
+ newProps.push(`${KEY_RENAME[key]}: ${node.initializer.getText(sourceFile)}`);
2806
+ let start = node.getStart();
2807
+ let end = node.getEnd();
2808
+ const trailingComma = text.slice(end).match(/^(\s*,)/);
2809
+ if (trailingComma) end += trailingComma[1].length;
2810
+ else {
2811
+ const leadingComma = text.slice(0, start).match(/,\s*$/);
2812
+ if (leadingComma) start -= leadingComma[0].length;
2813
+ }
2814
+ edits.push({
2815
+ start,
2816
+ end,
2817
+ replacement: ""
2818
+ });
2819
+ }
2820
+ const parentObject = matches[0].node.parent;
2821
+ const existingCompat = parentObject.properties.find((p) => ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === "compat" && ts.isObjectLiteralExpression(p.initializer));
2822
+ if (existingCompat) edits.push(insertIntoObjectLiteral(existingCompat.initializer, newProps));
2823
+ else edits.push(insertIntoObjectLiteral(parentObject, [`compat: { ${newProps.join(", ")} }`]));
2824
+ let result = text;
2825
+ for (const edit of edits.sort((a, b) => b.start - a.start)) result = result.slice(0, edit.start) + edit.replacement + result.slice(edit.end);
2826
+ return result;
2827
+ }
2828
+ };
2829
+ function insertIntoObjectLiteral(obj, newProps) {
2830
+ if (obj.properties.length === 0) {
2831
+ const pos = obj.getStart() + 1;
2832
+ return {
2833
+ start: pos,
2834
+ end: pos,
2835
+ replacement: ` ${newProps.join(", ")} `
2836
+ };
2837
+ }
2838
+ const last = obj.properties[obj.properties.length - 1];
2839
+ return {
2840
+ start: last.getEnd(),
2841
+ end: last.getEnd(),
2842
+ replacement: `, ${newProps.join(", ")}`
2843
+ };
2844
+ }
2845
+ //#endregion
2387
2846
  //#region src/migrations/index.ts
2388
2847
  /**
2389
2848
  * Build a map of local import names to their original names from @stencil/core.
@@ -2429,11 +2888,14 @@ const migrationRules = [
2429
2888
  devModeRule,
2430
2889
  globalStyleInjectRule,
2431
2890
  lightDomPatchesRule,
2891
+ enableImportInjectionDefaultRule,
2432
2892
  extrasToCompatRule,
2893
+ suppressWarningsToCompatRule,
2433
2894
  externalRuntimeRule,
2434
2895
  hashFileNamesRule,
2435
2896
  rolldownConfigRule,
2436
- serviceWorkerDefaultRule
2897
+ serviceWorkerDefaultRule,
2898
+ cssImportQueryParamRule
2437
2899
  ];
2438
2900
  /**
2439
2901
  * Get all migration rules for a specific version upgrade.
@@ -2543,7 +3005,8 @@ const detectMigrations = async (coreCompiler, config) => {
2543
3005
  const sys = config.sys;
2544
3006
  const logger = config.logger;
2545
3007
  const currentMajor = coreCompiler.version.split(".")[0];
2546
- const rules = getRulesForVersionUpgrade(String(Number(currentMajor) - 1), currentMajor);
3008
+ const fromVersion = String(Number(currentMajor) - 1);
3009
+ const rules = getRulesForVersionUpgrade(fromVersion, currentMajor);
2547
3010
  if (rules.length === 0) return {
2548
3011
  hasMigrations: false,
2549
3012
  totalMatches: 0,
@@ -3305,6 +3768,48 @@ const taskDocs = async (coreCompiler, config) => {
3305
3768
  await compiler.destroy();
3306
3769
  };
3307
3770
  //#endregion
3771
+ //#region src/resolve-entry-script.ts
3772
+ /**
3773
+ * Resolves the server-relative src for the project's browser entry bundle, from validated
3774
+ * output targets alone (no build required) - the same dev-mode, unhashed filename conventions
3775
+ * the compiler itself uses (see `getAbsoluteBuildDir` in `packages/core/src/compiler/html/html-utils.ts`
3776
+ * and the dev server's `getLoaderUrl` in `packages/dev-server/src/server/dev-preview.ts`, which
3777
+ * this mirrors for use before a build has happened).
3778
+ *
3779
+ * Preference order matches what actually gets built:
3780
+ * 1. `www` - always emits its own entry bundle at `{buildDir}/{fsNamespace}.js`, regardless of
3781
+ * `bundleMode`, so it's resolved directly from the `www` target rather than the `dist-lazy` /
3782
+ * `standalone` target it internally synthesizes.
3783
+ * 2. `loader-bundle` (no `www`) - synthesizes a `dist-lazy` build for CDN usage, servable from
3784
+ * the project root when there's no `www` target to claim the server root instead.
3785
+ * 3. `standalone` with `autoLoader` enabled (the default) - falls back to its auto-loader script.
3786
+ *
3787
+ * Returns `null` if the project has no browser-loadable output target at all (e.g. an SSR-only
3788
+ * project) - the caller should omit the script tag in that case.
3789
+ *
3790
+ * @param config - Validated Stencil config.
3791
+ * @returns Server-relative script src, or `null` if none of the configured output targets
3792
+ * produce a browser-loadable entry.
3793
+ */
3794
+ function resolveEntryScriptSrc(config) {
3795
+ const outputTargets = config.outputTargets;
3796
+ const wwwTarget = outputTargets.find(isOutputTargetWww);
3797
+ if (wwwTarget?.dir && wwwTarget.buildDir) return toUrl(wwwTarget.dir, wwwTarget.buildDir, `${config.fsNamespace}.js`);
3798
+ const distLazyTarget = outputTargets.find(isOutputTargetDistLazy);
3799
+ const distLazyDir = distLazyTarget?.esmDir ?? distLazyTarget?.dir;
3800
+ if (distLazyDir) return toUrl(config.rootDir, distLazyDir, `${config.fsNamespace}.js`);
3801
+ const standaloneTarget = outputTargets.find(isOutputTargetStandalone);
3802
+ if (standaloneTarget?.dir && standaloneTarget.autoLoader !== false) {
3803
+ const fileName = typeof standaloneTarget.autoLoader === "object" ? standaloneTarget.autoLoader.fileName || "loader" : "loader";
3804
+ return toUrl(config.rootDir, standaloneTarget.dir, `${fileName}.js`);
3805
+ }
3806
+ return null;
3807
+ }
3808
+ function toUrl(base, dir, fileName) {
3809
+ const relativeDir = normalizePath(relative(base, dir), false);
3810
+ return `/${relativeDir ? `${relativeDir}/` : ""}${fileName}`;
3811
+ }
3812
+ //#endregion
3308
3813
  //#region src/task-generate.ts
3309
3814
  async function resolveFileTemplates(contrib, ctx) {
3310
3815
  const { fileTemplates } = contrib;
@@ -3356,6 +3861,26 @@ const taskGenerate = async (config, flags) => {
3356
3861
  });
3357
3862
  cancelIfAborted(stylePick);
3358
3863
  const styleExtension = stylePick || void 0;
3864
+ const demoPick = await p.select({
3865
+ message: "Demo:",
3866
+ options: [
3867
+ {
3868
+ value: "usage",
3869
+ label: "Usage example",
3870
+ hint: "usage/example.md - rendered in docs and the dev server auto-preview"
3871
+ },
3872
+ {
3873
+ value: "preview",
3874
+ label: "Preview page",
3875
+ hint: "index.html - full control, opts out of the dev server auto-preview"
3876
+ },
3877
+ {
3878
+ value: "",
3879
+ label: "None"
3880
+ }
3881
+ ]
3882
+ });
3883
+ cancelIfAborted(demoPick);
3359
3884
  const generateCtx = {
3360
3885
  tagName: componentName,
3361
3886
  config: toProjectConfig(config),
@@ -3397,6 +3922,14 @@ const taskGenerate = async (config, flags) => {
3397
3922
  content: tmpl.template(componentName, className)
3398
3923
  });
3399
3924
  }
3925
+ if (demoPick === "usage") filesToWrite.push({
3926
+ absPath: normalizePath(join(outDir, "usage", "example.md")),
3927
+ content: getUsageExampleBoilerplate(componentName)
3928
+ });
3929
+ else if (demoPick === "preview") filesToWrite.push({
3930
+ absPath: normalizePath(join(outDir, "index.html")),
3931
+ content: getPreviewHtmlBoilerplate(componentName, resolveEntryScriptSrc(config))
3932
+ });
3400
3933
  const wouldOverwrite = (await Promise.all(filesToWrite.map(async ({ absPath }) => await config.sys.readFile(absPath) !== void 0 ? absPath : null))).filter((f) => f !== null);
3401
3934
  if (wouldOverwrite.length > 0) {
3402
3935
  config.logger.error("Generating code would overwrite the following files:", ...wouldOverwrite.map((path) => " " + normalizePath(path)));
@@ -3456,44 +3989,88 @@ const taskTelemetry = async (flags, sys, logger) => {
3456
3989
  const taskHelp = async (flags, logger, sys) => {
3457
3990
  const prompt = logger.dim(sys.details?.platform === "windows" ? ">" : "$");
3458
3991
  console.log(`
3992
+ ${logger.bold("Init:")} ${logger.dim("Scaffold a new project, or add capabilities to an existing one.")}
3993
+
3994
+ ${prompt} ${logger.green("stencil init")}
3995
+
3996
+
3997
+ ${logger.bold("Add:")} ${logger.dim("Install and configure an integration (framework wrapper, output target, etc).")}
3998
+
3999
+ ${prompt} ${logger.green("stencil add [package]")}
4000
+
4001
+
4002
+ ${logger.bold("Generate:")} ${logger.dim("Bootstrap a new component.")}
4003
+
4004
+ ${prompt} ${logger.green("stencil generate [name]")} or ${logger.green("stencil g [name]")}
4005
+
4006
+
3459
4007
  ${logger.bold("Build:")} ${logger.dim("Build components for development or production.")}
3460
4008
 
3461
- ${prompt} ${logger.green("stencil build [--dev] [--watch] [--prerender] [--debug]")}
4009
+ ${prompt} ${logger.green("stencil build [--dev] [--watch] [--serve] [--prerender] [--debug]")}
3462
4010
 
3463
4011
  ${logger.cyan("--dev")} ${logger.dim(".............")} Development build
3464
4012
  ${logger.cyan("--watch")} ${logger.dim("...........")} Rebuild when files update
3465
- ${logger.cyan("--serve")} ${logger.dim("...........")} Start the dev-server
4013
+ ${logger.cyan("--serve")} ${logger.dim("...........")} Start the dev-server (requires --watch)
3466
4014
  ${logger.cyan("--prerender")} ${logger.dim(".......")} Prerender the application
3467
4015
  ${logger.cyan("--docs")} ${logger.dim("............")} Generate component readme.md docs
4016
+ ${logger.cyan("--ssr")} ${logger.dim(".............")} Build a server-side-rendering bundle
3468
4017
  ${logger.cyan("--config")} ${logger.dim("..........")} Set stencil config file
4018
+ ${logger.cyan("--maxWorkers")} ${logger.dim("......")} Max number of workers, e.g. --maxWorkers 4 or --maxWorkers 50%
4019
+ ${logger.cyan("--no-cache")} ${logger.dim("........")} Disable the build cache
3469
4020
  ${logger.cyan("--stats")} ${logger.dim("...........")} Write stats, optional file path (default: stencil-stats.json)
3470
4021
  ${logger.cyan("--log")} ${logger.dim(".............")} Write stencil-build.log file
4022
+ ${logger.cyan("--ci")} ${logger.dim("..............")} Run in CI mode (disables colors, version checks)
3471
4023
  ${logger.cyan("--debug")} ${logger.dim("...........")} Set the log level to debug
3472
4024
 
3473
4025
 
3474
- ${logger.bold("Test:")} ${logger.dim("Run unit and end-to-end tests.")}
4026
+ ${logger.bold("Serve:")} ${logger.dim("Start the dev-server without building or watching.")}
4027
+
4028
+ ${prompt} ${logger.green("stencil serve [--root] [--no-open]")}
4029
+
4030
+ ${logger.cyan("--root")} ${logger.dim("............")} Directory to serve (default: current directory)
4031
+ ${logger.cyan("--no-open")} ${logger.dim(".........")} Don't open the browser automatically
3475
4032
 
3476
- ${prompt} ${logger.green("stencil test [--spec] [--e2e]")}
3477
4033
 
3478
- ${logger.cyan("--spec")} ${logger.dim("............")} Run unit tests with Jest
3479
- ${logger.cyan("--e2e")} ${logger.dim(".............")} Run e2e tests with Puppeteer
4034
+ ${logger.bold("Docs:")} ${logger.dim("Generate configured docs output targets.")}
3480
4035
 
4036
+ ${prompt} ${logger.green("stencil docs [--docsJson]")}
3481
4037
 
3482
- ${logger.bold("Generate:")} ${logger.dim("Bootstrap components.")}
4038
+ ${logger.cyan("--docsJson")} ${logger.dim("........")} Write a docs.json file to the given path
3483
4039
 
3484
- ${prompt} ${logger.green("stencil generate")} or ${logger.green("stencil g")}
4040
+
4041
+ ${logger.bold("Prerender:")} ${logger.dim("Prerender a hydrate app script against the source index.html.")}
4042
+
4043
+ ${prompt} ${logger.green("stencil prerender <hydrate-app-path>")}
4044
+
4045
+
4046
+ ${logger.bold("Migrate:")} ${logger.dim("Codemod a project for the latest major version breaking changes.")}
4047
+
4048
+ ${prompt} ${logger.green("stencil migrate [--dry-run]")}
4049
+
4050
+ ${logger.cyan("--dry-run")} ${logger.dim(".........")} Preview changes without modifying files
4051
+
4052
+
4053
+ ${logger.bold("Info:")} ${logger.dim("Print details about the current environment.")}
4054
+
4055
+ ${prompt} ${logger.green("stencil info")}
4056
+
4057
+
4058
+ ${logger.bold("Version:")} ${logger.dim("Print the installed Stencil compiler version.")}
4059
+
4060
+ ${prompt} ${logger.green("stencil version")} or ${logger.green("stencil --version")}
3485
4061
 
3486
4062
  `);
3487
4063
  await taskTelemetry(flags, sys, logger);
3488
4064
  console.log(`
3489
4065
  ${logger.bold("Examples:")}
3490
4066
 
4067
+ ${prompt} ${logger.green("stencil init")}
4068
+ ${prompt} ${logger.green("stencil g my-component")}
3491
4069
  ${prompt} ${logger.green("stencil build --dev --watch --serve")}
3492
4070
  ${prompt} ${logger.green("stencil build --prerender")}
3493
- ${prompt} ${logger.green("stencil test --spec --e2e")}
4071
+ ${prompt} ${logger.green("stencil serve --root www")}
4072
+ ${prompt} ${logger.green("stencil migrate --dry-run")}
3494
4073
  ${prompt} ${logger.green("stencil telemetry on")}
3495
- ${prompt} ${logger.green("stencil generate")}
3496
- ${prompt} ${logger.green("stencil g my-component")}
3497
4074
  `);
3498
4075
  };
3499
4076
  //#endregion
@@ -3529,26 +4106,60 @@ const taskInfo = (coreCompiler, sys, logger) => {
3529
4106
  * @param rootDir - Destination directory (typically `process.cwd()`).
3530
4107
  * @param projectName - Value to substitute for `{{PROJECT_NAME}}` placeholders.
3531
4108
  * @param namespace - Value to substitute for `{{NAMESPACE}}` placeholders.
4109
+ * @param stencilVersion - Optional version to substitute for `{{STENCIL_VERSION}}` placeholders.
3532
4110
  */
3533
- async function copyTemplate(rootDir, projectName, namespace) {
4111
+ async function copyTemplate(rootDir, projectName, namespace, stencilVersion) {
3534
4112
  const templateDir = getTemplatePath("component-starter");
3535
4113
  const entries = await readdir(templateDir, {
3536
4114
  recursive: true,
3537
4115
  withFileTypes: true
3538
4116
  });
4117
+ const resolvedStencilVersion = stencilVersion ?? "^5.0.0";
3539
4118
  for (const entry of entries) {
3540
4119
  if (!entry.isFile()) continue;
3541
4120
  const srcPath = join(entry.parentPath, entry.name);
3542
- const relPath = relative(templateDir, srcPath);
4121
+ let relPath = relative(templateDir, srcPath);
4122
+ if (relPath === "_gitignore") relPath = ".gitignore";
3543
4123
  const destPath = join(rootDir, relPath);
3544
4124
  await mkdir(dirname(destPath), { recursive: true });
3545
- const content = (await readFile(srcPath, "utf8")).replace(/\{\{PROJECT_NAME\}\}/g, projectName).replace(/\{\{NAMESPACE\}\}/g, namespace);
4125
+ const content = (await readFile(srcPath, "utf8")).replace(/\{\{PROJECT_NAME\}\}/g, projectName).replace(/\{\{NAMESPACE\}\}/g, namespace).replace(/\{\{STENCIL_VERSION\}\}/g, resolvedStencilVersion);
3546
4126
  if (relPath === "package.json") await mergePackageJson(destPath, content);
3547
4127
  else if (relPath === "tsconfig.json") await mergeTsConfig(destPath, content);
3548
4128
  else if (relPath === ".gitignore") await mergeGitignore(destPath, content);
3549
4129
  else await writeIfAbsent(destPath, content);
3550
4130
  }
3551
4131
  }
4132
+ const PARCEL_WATCHER_BUILD_ALLOWANCES = [
4133
+ `onlyBuiltDependencies:`,
4134
+ ` - '@parcel/watcher'`,
4135
+ ``,
4136
+ `allowBuilds:`,
4137
+ ` '@parcel/watcher': true`
4138
+ ].join("\n");
4139
+ async function mergePnpmWorkspaceYaml(yamlPath) {
4140
+ let existing = null;
4141
+ try {
4142
+ existing = await readFile(yamlPath, "utf8");
4143
+ } catch {}
4144
+ if (existing === null) {
4145
+ await writeFile(yamlPath, [
4146
+ `packages:`,
4147
+ ` - 'packages/*'`,
4148
+ ``,
4149
+ PARCEL_WATCHER_BUILD_ALLOWANCES,
4150
+ ``
4151
+ ].join("\n"), "utf8");
4152
+ return;
4153
+ }
4154
+ let toAppend = "";
4155
+ if (!existing.includes("packages/*")) toAppend += `\npackages:\n - 'packages/*'\n`;
4156
+ if (!existing.includes("onlyBuiltDependencies:")) toAppend += `\nonlyBuiltDependencies:\n - '@parcel/watcher'\n`;
4157
+ if (!existing.includes("allowBuilds:")) toAppend += `\nallowBuilds:\n '@parcel/watcher': true\n`;
4158
+ if (toAppend) {
4159
+ const separator = existing.endsWith("\n") ? "" : "\n";
4160
+ await writeFile(yamlPath, existing + separator + toAppend, "utf8");
4161
+ }
4162
+ }
3552
4163
  async function writeIfAbsent(destPath, content) {
3553
4164
  try {
3554
4165
  await writeFile(destPath, content, {
@@ -3630,6 +4241,52 @@ async function writeGlobalScript(rootDir) {
3630
4241
  await mkdir(dirname(path), { recursive: true });
3631
4242
  await writeIfAbsent(path, `export default function (): void {}\n`);
3632
4243
  }
4244
+ async function writeIndexHtml(rootDir, content) {
4245
+ const path = join(rootDir, "src", "index.html");
4246
+ await mkdir(dirname(path), { recursive: true });
4247
+ await writeIfAbsent(path, content);
4248
+ }
4249
+ function workspaceBuildScript(pm, coreName) {
4250
+ switch (pm) {
4251
+ case "pnpm": return "pnpm -r build";
4252
+ case "yarn": return "yarn workspaces run build";
4253
+ case "bun": return "bun run --filter \"*\" build";
4254
+ default: return `npm run build -w packages/${coreName} && npm run build --workspaces --if-present`;
4255
+ }
4256
+ }
4257
+ /**
4258
+ * Scaffold a workspace root in `cwd`: creates `packages/`, writes the appropriate
4259
+ * workspace manifest (`pnpm-workspace.yaml` for pnpm, `workspaces` field in
4260
+ * `package.json` for npm / yarn / bun), and ensures a root `package.json` exists.
4261
+ * @param cwd - Absolute path to the workspace root (where `package.json` will be created).
4262
+ * @param projectName - Name to use for the root package.json (typically the project name).
4263
+ * @param coreName - Directory name of the core package under `packages/` (e.g. `core`).
4264
+ * @returns A promise that resolves when the workspace root has been scaffolded.
4265
+ */
4266
+ async function scaffoldWorkspaceRoot(cwd, projectName, coreName) {
4267
+ await mkdir(join(cwd, "packages"), { recursive: true });
4268
+ const pm = await detectPackageManager(cwd);
4269
+ const usePnpmYaml = pm?.name === "pnpm";
4270
+ const pkgPath = join(cwd, "package.json");
4271
+ let pkg;
4272
+ try {
4273
+ pkg = JSON.parse(await readFile(pkgPath, "utf8"));
4274
+ } catch {
4275
+ pkg = {};
4276
+ }
4277
+ pkg.name ??= `${projectName}-workspace`;
4278
+ pkg.version ??= "0.0.1";
4279
+ pkg.private = true;
4280
+ pkg.scripts = {
4281
+ build: workspaceBuildScript(pm?.name, coreName),
4282
+ ...pkg.scripts
4283
+ };
4284
+ if (!usePnpmYaml) pkg.workspaces = ["packages/*"];
4285
+ delete pkg.dependencies;
4286
+ delete pkg.devDependencies;
4287
+ await writeFile(pkgPath, JSON.stringify(pkg, null, 2) + "\n", "utf8");
4288
+ if (usePnpmYaml) await mergePnpmWorkspaceYaml(join(cwd, "pnpm-workspace.yaml"));
4289
+ }
3633
4290
  /**
3634
4291
  * Write output-driven distributable fields (type, module, types) into package.json.
3635
4292
  * These fields depend on which outputs the user selected, so they cannot be static in the template.
@@ -3647,6 +4304,36 @@ async function applyPackageJsonFields(rootDir, fields) {
3647
4304
  }
3648
4305
  //#endregion
3649
4306
  //#region src/task-init.ts
4307
+ /**
4308
+ * Package managers can report success while silently failing to write to node_modules.
4309
+ * Confirms packages actually landed on disk instead of trusting the install call's exit code.
4310
+ *
4311
+ * @param rootDir - directory to resolve packages from.
4312
+ * @param packageNames - packages that were just supposed to be installed.
4313
+ */
4314
+ async function verifyInstalled(rootDir, packageNames) {
4315
+ const missing = [];
4316
+ for (const name of packageNames) if (!await getPackageInfo(name, { paths: [rootDir] })) missing.push(name);
4317
+ if (missing.length === 0) return;
4318
+ p.log.error(`Install reported success but ${missing.join(", ")} could not be found in ${rootDir}. Your package manager may have silently failed to write to node_modules - check its logs and try again.`);
4319
+ process.exit(1);
4320
+ }
4321
+ /**
4322
+ * npm silently omits devDependencies when this CLI is itself running as a nested child
4323
+ * process (e.g. via `npx create-stencil` / `npm init stencil`). Root cause: npm/exec only
4324
+ * needs @stencil/cli's own regular dependencies to resolve+run it, so that install computes
4325
+ * `omit: ['dev']` - and per npm's own config flattening
4326
+ * (@npmcli/config/lib/definitions/definitions.js), whenever `omit` includes 'dev' npm sets
4327
+ * `process.env.NODE_ENV = 'production'` on itself. We inherit that env var from the outer
4328
+ * npm/npx process, and every child process we (or a wizard plugin) spawn from here would
4329
+ * inherit it right back, causing nested `npm install`s to also compute `omit: ['dev']` and
4330
+ * silently drop (or, worse, actively remove) every devDependency in the scaffolded project.
4331
+ * Clearing it once, up front, fixes every install call transitively - ours and every wizard
4332
+ * plugin's - without needing to special-case npm invocations one by one.
4333
+ */
4334
+ function clearInheritedProductionEnv() {
4335
+ if (process.env.NODE_ENV === "production") delete process.env.NODE_ENV;
4336
+ }
3650
4337
  function outputKeysToTargets(keys) {
3651
4338
  const map = {
3652
4339
  loader: "loader-bundle",
@@ -3658,11 +4345,12 @@ function outputKeysToTargets(keys) {
3658
4345
  return keys.length > 0 ? keys.map((k) => ({ type: map[k] })) : [{ type: "loader-bundle" }];
3659
4346
  }
3660
4347
  async function taskInit(coreCompiler, strictConfig, loadProjectConfig) {
4348
+ clearInheritedProductionEnv();
3661
4349
  const cwd = process.cwd();
3662
4350
  const isExistingProject = await isExistingStencilProject(cwd);
3663
4351
  printSplash();
3664
4352
  p.intro(`stencil init`);
3665
- if (process.env.STENCIL_WIZARD_DEV) p.log.warn(`Dev mode: loading wizard from ${process.env.STENCIL_WIZARD_DEV}`);
4353
+ if (process.env.STENCIL_WIZARD_DEV) p.log.warn(`Dev mode: loading wizards from ${process.env.STENCIL_WIZARD_DEV}`);
3666
4354
  if (isCI) {
3667
4355
  p.log.warn("Running in CI - non-interactive mode is not yet supported for `stencil init`.");
3668
4356
  process.exit(1);
@@ -3677,72 +4365,95 @@ async function taskInit(coreCompiler, strictConfig, loadProjectConfig) {
3677
4365
  const features = await promptFeatures();
3678
4366
  const docs = await promptDocs();
3679
4367
  const selectedIntegrations = await promptIntegrations();
4368
+ let monorepo = false;
4369
+ let coreName = "";
4370
+ if (hasFrameworkTargets(selectedIntegrations)) {
4371
+ monorepo = await promptMonorepo();
4372
+ if (monorepo) coreName = await promptWorkspaceCoreName();
4373
+ }
3680
4374
  const configSource = generateStencilConfig({
3681
4375
  namespace,
3682
4376
  outputs,
3683
4377
  signals: features.signals,
3684
4378
  docs
3685
- });
4379
+ }) ?? (needsStencilConfig(selectedIntegrations) ? `import { Config } from '@stencil/core';\n\nexport const config: Config = {\n namespace: '${namespace}',\n outputTargets: [{ type: 'loader-bundle' }],\n};\n` : null);
3686
4380
  const summaryLines = [
3687
4381
  `Template: component-starter`,
3688
4382
  `Name: ${projectName}`,
3689
4383
  `Namespace: ${namespace}`,
3690
4384
  `Config: ${configSource ? "stencil.config.ts" : "zero-config (loader default)"}`
3691
4385
  ];
4386
+ if (monorepo) {
4387
+ summaryLines.push(`Structure: monorepo workspace`);
4388
+ summaryLines.push(`Core: packages/${coreName}/`);
4389
+ }
3692
4390
  if (selectedIntegrations.length > 0) summaryLines.push(`Add: ${selectedIntegrations.map((i) => i.displayName).join(", ")}`);
3693
4391
  p.note(summaryLines.join("\n"), "Summary");
3694
- const confirmed = await p.confirm({ message: "Scaffold project in current directory?" });
3695
- cancelIfAborted(confirmed);
3696
- if (!confirmed) {
3697
- p.cancel("Cancelled.");
3698
- process.exit(0);
3699
- }
4392
+ const coreDir = monorepo ? join(cwd, "packages", coreName) : cwd;
3700
4393
  const s1 = p.spinner();
3701
4394
  s1.start("Scaffolding project files");
3702
- await copyTemplate(cwd, projectName, namespace);
3703
- await applyPackageJsonFields(cwd, generatePackageJsonFields(outputs));
3704
- if (configSource) await writeStencilConfig(cwd, configSource);
3705
- if (features.globalStyle) await writeGlobalStyle(cwd);
3706
- if (features.globalScript) await writeGlobalScript(cwd);
4395
+ if (monorepo) await scaffoldWorkspaceRoot(cwd, projectName, coreName);
4396
+ await copyTemplate(coreDir, projectName, namespace, coreCompiler?.version);
4397
+ await applyPackageJsonFields(coreDir, generatePackageJsonFields(outputs));
4398
+ if (configSource) await writeStencilConfig(coreDir, configSource);
4399
+ if (features.globalStyle) await writeGlobalStyle(coreDir);
4400
+ if (features.globalScript) await writeGlobalScript(coreDir);
4401
+ if (outputs.includes("www")) await writeIndexHtml(coreDir, generateIndexHtml({
4402
+ projectName,
4403
+ namespace,
4404
+ globalStyle: features.globalStyle
4405
+ }));
3707
4406
  s1.stop("Project files created");
3708
4407
  const s2 = p.spinner();
3709
4408
  s2.start("Installing dependencies");
3710
- await installDependencies({
4409
+ await nypm.installDependencies({
3711
4410
  cwd,
3712
4411
  silent: true
3713
4412
  });
3714
4413
  s2.stop("Dependencies installed");
4414
+ await verifyInstalled(coreDir, ["@stencil/core"]);
3715
4415
  if (selectedIntegrations.length > 0) {
3716
4416
  const s3 = p.spinner();
3717
4417
  const pkgs = selectedIntegrations.map((i) => i.package);
3718
4418
  s3.start(`Installing ${pkgs.join(", ")}`);
3719
- await addDevDependency(pkgs, {
3720
- cwd,
4419
+ await nypm.addDevDependency(withVersionRanges(pkgs), {
4420
+ cwd: coreDir,
3721
4421
  silent: true
3722
4422
  });
3723
4423
  s3.stop("Integrations installed");
4424
+ await verifyInstalled(coreDir, pkgs);
3724
4425
  }
3725
4426
  if (selectedIntegrations.length > 0) {
3726
- const discovered = await discoverPlugins(cwd);
4427
+ const discovered = await discoverPlugins(coreDir);
3727
4428
  const selectedPkgs = new Set(selectedIntegrations.map((i) => i.package));
3728
- const resolvedValidated = loadProjectConfig ? await loadProjectConfig(configSource ? join(cwd, "stencil.config.ts") : void 0) : coreCompiler ? coreCompiler.validateConfig({
3729
- rootDir: cwd,
4429
+ const resolvedValidated = loadProjectConfig && configSource ? await loadProjectConfig(join(coreDir, "stencil.config.ts")) : coreCompiler ? coreCompiler.validateConfig({
4430
+ rootDir: coreDir,
3730
4431
  outputTargets: outputKeysToTargets(outputs),
3731
4432
  ...configSource ? { namespace } : {}
3732
4433
  }, {}).config : null;
3733
- const context = {
4434
+ const projectConfig = resolvedValidated ? {
4435
+ ...toProjectConfig(resolvedValidated),
4436
+ rootDir: coreDir
4437
+ } : defaultProjectConfig(coreDir, { namespace });
4438
+ for (const d of discovered) if (selectedPkgs.has(d.packageName) && d.plugin.init?.run) await d.plugin.init.run({
3734
4439
  isNewProject: true,
3735
4440
  prompts: p,
3736
4441
  nypm,
3737
- config: resolvedValidated ? toProjectConfig(resolvedValidated) : defaultProjectConfig(cwd, { namespace })
3738
- };
3739
- for (const d of discovered) if (selectedPkgs.has(d.packageName) && d.plugin.init?.run) await d.plugin.init.run(context);
4442
+ config: projectConfig,
4443
+ workspaceRoot: monorepo ? cwd : void 0,
4444
+ ts,
4445
+ openStencilConfig: () => openStencilConfig(join(projectConfig.rootDir, "stencil.config.ts"))
4446
+ });
3740
4447
  }
3741
- p.outro("Your project is ready! Run: pnpm run dev");
4448
+ const pm = (await nypm.detectPackageManager(cwd))?.name ?? "npm";
4449
+ const devDir = monorepo ? `packages/${coreName}` : null;
4450
+ const devCmd = `${pm} run dev`;
4451
+ p.outro(devDir ? `Your project is ready!\n cd ${devDir}\n ${devCmd}` : `Your project is ready! Run: ${devCmd}`);
3742
4452
  }
3743
4453
  async function addCapabilities(cwd, strictConfig) {
4454
+ const workspaceRoot = await detectWorkspaceRoot(cwd);
3744
4455
  const raw = JSON.parse(await readFile(join(cwd, "package.json"), "utf8"));
3745
- const installed = new Set([...Object.keys(raw.dependencies ?? {}), ...Object.keys(raw.devDependencies ?? {})]);
4456
+ const installed = /* @__PURE__ */ new Set([...Object.keys(raw.dependencies ?? {}), ...Object.keys(raw.devDependencies ?? {})]);
3746
4457
  const discovered = await discoverPlugins(cwd);
3747
4458
  const configurable = discovered.filter((d) => d.plugin.init);
3748
4459
  const installable = KNOWN_INTEGRATIONS.filter((i) => !installed.has(i.package));
@@ -3770,26 +4481,31 @@ async function addCapabilities(cwd, strictConfig) {
3770
4481
  const s = p.spinner();
3771
4482
  const pkgs = toInstall.map((i) => i.package);
3772
4483
  s.start(`Installing ${pkgs.join(", ")}`);
3773
- await addDevDependency(pkgs, {
4484
+ await nypm.addDevDependency(withVersionRanges(pkgs), {
3774
4485
  cwd,
3775
4486
  silent: true
3776
4487
  });
3777
4488
  s.stop("Dependencies installed");
4489
+ await verifyInstalled(cwd, pkgs);
3778
4490
  }
3779
4491
  const allDiscovered = toInstall.length > 0 ? await discoverPlugins(cwd) : discovered;
3780
4492
  const newlyInstalledPkgs = new Set(toInstall.map((i) => i.package));
3781
4493
  const toRun = [...allDiscovered.filter((d) => newlyInstalledPkgs.has(d.packageName)), ...toConfigure].filter((d) => d.plugin.init?.run);
3782
- const context = {
4494
+ const projectConfig = strictConfig ? toProjectConfig(strictConfig) : defaultProjectConfig(cwd);
4495
+ for (const d of toRun) await d.plugin.init.run({
3783
4496
  isNewProject: false,
3784
4497
  prompts: p,
3785
4498
  nypm,
3786
- config: strictConfig ? toProjectConfig(strictConfig) : defaultProjectConfig(cwd)
3787
- };
3788
- for (const d of toRun) await d.plugin.init.run(context);
4499
+ config: projectConfig,
4500
+ workspaceRoot,
4501
+ ts,
4502
+ openStencilConfig: () => openStencilConfig(join(projectConfig.rootDir, "stencil.config.ts"))
4503
+ });
3789
4504
  p.outro("Done! Run pnpm run dev to continue.");
3790
4505
  }
3791
4506
  function toNamespace(name) {
3792
- return toPascalCase(name.replace(/^@[^/]+\//, "").replace(/[/_]/g, "-"));
4507
+ const base = name.replace(/^@[^/]+\//, "");
4508
+ return toPascalCase(base.replace(/[/_]/g, "-"));
3793
4509
  }
3794
4510
  //#endregion
3795
4511
  //#region src/task-serve.ts
@@ -3847,6 +4563,10 @@ const run = async (init) => {
3847
4563
  }), logger, sys);
3848
4564
  return;
3849
4565
  }
4566
+ if (task === "test") {
4567
+ logger.error(`${logger.emoji("❌ ")}The "stencil test" command has been removed. Use ${logger.bold("@stencil/vitest")} for unit tests and ${logger.bold("@stencil/playwright")} for e2e tests instead. See BREAKING_CHANGES.md for migration details.`);
4568
+ return sys.exit(1);
4569
+ }
3850
4570
  if (task === "add" || task === "init") {
3851
4571
  const coreCompiler = await loadCoreCompiler(sys);
3852
4572
  const rootDir = sys.getCurrentDirectory();
@@ -3855,11 +4575,11 @@ const run = async (init) => {
3855
4575
  configPath: flags.config
3856
4576
  });
3857
4577
  let strictConfig;
3858
- if (!findConfigResults.isErr) {
3859
- const foundConfig = result.unwrap(findConfigResults);
4578
+ const foundConfigPath = !findConfigResults.isErr ? result.unwrap(findConfigResults).configPath : null;
4579
+ if (foundConfigPath) {
3860
4580
  const loaded = await coreCompiler.loadConfig({
3861
- config: { rootDir },
3862
- configPath: foundConfig.configPath ?? void 0,
4581
+ config: { rootDir: dirname(foundConfigPath) },
4582
+ configPath: foundConfigPath,
3863
4583
  logger,
3864
4584
  sys
3865
4585
  });
@@ -3868,13 +4588,15 @@ const run = async (init) => {
3868
4588
  if (task === "add") await taskAdd(flags.unknownArgs, strictConfig);
3869
4589
  else {
3870
4590
  const loadProjectConfig = async (configPath) => {
4591
+ const derivedRootDir = configPath ? dirname(configPath) : rootDir;
3871
4592
  const loaded = await coreCompiler.loadConfig({
3872
- config: { rootDir },
4593
+ config: { rootDir: derivedRootDir },
3873
4594
  configPath,
3874
4595
  logger,
3875
4596
  sys
3876
4597
  });
3877
- return coreCompiler.validateConfig(loaded.config, {}).config;
4598
+ if (loaded.diagnostics.length > 0) logger.printDiagnostics(loaded.diagnostics);
4599
+ return coreCompiler.validateConfig(loaded.config ?? { rootDir: derivedRootDir }, {}).config;
3878
4600
  };
3879
4601
  await taskInit(coreCompiler, strictConfig, loadProjectConfig);
3880
4602
  }