@drupal-canvas/create 1.5.0 → 1.6.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/README.md CHANGED
@@ -28,30 +28,86 @@ You can also provide the project name as an argument:
28
28
  npx @drupal-canvas/create@latest my-project
29
29
  ```
30
30
 
31
+ Experimental features are documented in
32
+ [`docs/experimental.md`](docs/experimental.md).
33
+
31
34
  ### Options
32
35
 
33
- | Option | Description |
34
- | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
35
- | `--template -t` | Template to use when scaffolding the project. One of the predefined templates (currently available: `acquia-nebula`, `balintbrews-canvas-starter`) or URL to custom template's Git repository. |
36
- | `--ref <ref>` | Custom Git ref to use when cloning the template repository. For example, a branch name or a tag. |
37
- | `--agents -a` | Comma-separated list of additional agents to support, or `none` to skip compatibility symlink creation. |
36
+ | Option | Description |
37
+ | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
38
+ | `--template -t` | Template to use when scaffolding the project. One of the predefined templates in `templates.json` or a URL to a custom template's Git repository. |
39
+ | `--ref <ref>` | Custom Git ref to use when cloning the template repository. For example, a branch name or a tag. |
40
+ | `--agents -a` | Comma-separated list of additional agents to support, or `none` to skip compatibility symlink creation. |
41
+ | `--site-name <name>` | Site name to slugify and suggest as the interactive project name. |
42
+ | `--site-url <url>` | Canvas site URL to write to the generated `.env`. Takes precedence over `CANVAS_SITE_URL`. |
43
+
44
+ ### Interactive and non-interactive input
45
+
46
+ A run is interactive when both standard input and output are attached to a
47
+ terminal. Non-interactive runs never prompt.
48
+
49
+ | Input | CLI input | Interactive when omitted | Non-interactive when omitted |
50
+ | ------------ | --------------------------------- | ------------------------------------------------ | --------------------------------------- |
51
+ | Project name | Positional `[project-name]` | Prompted | Error |
52
+ | Template | `--template`, `-t` | Default frontend selected automatically | Default frontend selected automatically |
53
+ | Site name | `--site-name` | Used to suggest the project name | Ignored |
54
+ | Site URL | `--site-url` or `CANVAS_SITE_URL` | Prompted | Optional; no `.env` when omitted |
55
+ | Git ref | `--ref`, `-r` | Template default applies | Template default applies |
56
+ | Agents | `--agents`, `-a` | Prompted when the template includes agent skills | Optional; compatibility is skipped |
38
57
 
39
58
  ### Example
40
59
 
41
60
  ```bash
42
- npx @drupal-canvas/create@latest my-project --template acquia-nebula
61
+ npx @drupal-canvas/create@latest my-project --template default
62
+ ```
63
+
64
+ The previous `acquia-nebula` template ID remains supported as an alias.
65
+
66
+ Use a site name to suggest an editable project name when the positional project
67
+ name is omitted:
68
+
69
+ ```bash
70
+ npx @drupal-canvas/create@latest --site-name 'My Drupal Site'
71
+ ```
72
+
73
+ Provide the Canvas site URL with a flag:
74
+
75
+ ```bash
76
+ npx @drupal-canvas/create@latest my-project \
77
+ --site-url https://canvas.example.com
78
+ ```
79
+
80
+ The `CANVAS_SITE_URL` environment variable can be used instead. The flag takes
81
+ precedence when both are provided:
82
+
83
+ ```bash
84
+ CANVAS_SITE_URL='https://canvas.example.com' \
85
+ npx @drupal-canvas/create@latest my-project
43
86
  ```
44
87
 
88
+ When neither value is provided, interactive runs prompt for the site URL.
89
+ Non-interactive runs continue without creating `.env`. When a URL is provided
90
+ and the template includes `.env.example`, the CLI copies it to `.env` and
91
+ updates or appends `CANVAS_SITE_URL`. Otherwise, it creates a new `.env`. If
92
+ `.env` already exists, the CLI adds or fills `CANVAS_SITE_URL`; when a non-empty
93
+ value is already configured, it keeps that value. The CLI prints a message for
94
+ each outcome and ensures `.env` is listed in `.gitignore`.
95
+
96
+ Non-interactive runs require a positional project name. When multiple templates
97
+ are enabled, `--template` is also required. The `--site-name` option does not
98
+ replace the positional project name in this mode. Missing site URLs and agent
99
+ selections remain optional and do not prompt.
100
+
45
101
  Explicitly skip additional agent compatibility symlinks:
46
102
 
47
103
  ```bash
48
- npx @drupal-canvas/create@latest my-project --template acquia-nebula --agents none
104
+ npx @drupal-canvas/create@latest my-project --template default --agents none
49
105
  ```
50
106
 
51
107
  Provide additional agent compatibility symlinks without prompting:
52
108
 
53
109
  ```bash
54
- npx @drupal-canvas/create@latest my-project --template acquia-nebula --agents claude-code,roo
110
+ npx @drupal-canvas/create@latest my-project --template default --agents claude-code,roo
55
111
  ```
56
112
 
57
113
  If `--agents` is omitted, the CLI keeps the current interactive prompt on TTY
@@ -86,6 +142,24 @@ Drupal Canvas Create is designed to be easily extendable with new templates.
86
142
  references a Git repository that will be cloned to provide the initial codebase.
87
143
  To add a template, edit `templates.json` in the package root.
88
144
 
145
+ A repository can contain multiple templates. Set the optional repository `path`
146
+ to use a directory within the cloned repository as the project root:
147
+
148
+ ```json
149
+ {
150
+ "id": "company-starter",
151
+ "label": "company/canvas-starter",
152
+ "repository": {
153
+ "url": "https://github.com/company/canvas-templates.git",
154
+ "ref": "main",
155
+ "path": "templates/starter"
156
+ }
157
+ }
158
+ ```
159
+
160
+ The path must identify a directory within the repository. Files outside that
161
+ directory are not included in the created project.
162
+
89
163
  ### Working with the codebase
90
164
 
91
165
  First, build the project:
package/dist/index.js CHANGED
@@ -1,34 +1,68 @@
1
1
  #!/usr/bin/env node
2
2
  import chalk2 from 'chalk';
3
3
  import { Command } from 'commander';
4
- import * as p4 from '@clack/prompts';
5
- import { readFile, writeFile, access, readdir, mkdir, symlink } from 'fs/promises';
4
+ import * as p5 from '@clack/prompts';
5
+ import { mkdtemp, readFile, writeFile, lstat, rename, access, readdir, mkdir, symlink } from 'fs/promises';
6
6
  import { platform } from 'os';
7
- import { join, dirname, relative } from 'path';
7
+ import { join, resolve, relative, sep, isAbsolute, dirname } from 'path';
8
8
  import * as readline from 'readline';
9
9
  import { Writable } from 'stream';
10
10
  import pc from 'picocolors';
11
11
  import spawn from 'cross-spawn';
12
12
  import { rimraf } from 'rimraf';
13
13
  import { simpleGit } from 'simple-git';
14
+ import slugify from '@sindresorhus/slugify';
14
15
  import validate from 'validate-npm-package-name';
15
16
 
16
17
  // templates.json
17
18
  var templates_default = [
18
19
  {
19
- id: "acquia-nebula",
20
- label: "acquia/nebula",
20
+ id: "default",
21
+ aliases: ["acquia-nebula"],
22
+ label: "Default (Canvas-rendered React)",
21
23
  repository: {
22
24
  url: "https://github.com/acquia/nebula.git",
23
25
  ref: "main"
24
26
  }
25
27
  },
26
28
  {
27
- id: "balintbrews-canvas-starter",
28
- label: "balintbrews/canvas-starter",
29
+ id: "nextjs",
30
+ label: "Next.js",
31
+ experimental: true,
29
32
  repository: {
30
- url: "https://github.com/balintbrews/canvas-starter.git",
31
- ref: "main"
33
+ url: "https://github.com/drupal-canvas/headless-templates.git",
34
+ ref: "main",
35
+ path: "nextjs"
36
+ }
37
+ },
38
+ {
39
+ id: "astro",
40
+ label: "Astro",
41
+ experimental: true,
42
+ repository: {
43
+ url: "https://github.com/drupal-canvas/headless-templates.git",
44
+ ref: "main",
45
+ path: "astro"
46
+ }
47
+ },
48
+ {
49
+ id: "nuxt",
50
+ label: "Nuxt",
51
+ experimental: true,
52
+ repository: {
53
+ url: "https://github.com/drupal-canvas/headless-templates.git",
54
+ ref: "main",
55
+ path: "nuxt"
56
+ }
57
+ },
58
+ {
59
+ id: "tanstack-start",
60
+ label: "TanStack Start",
61
+ experimental: true,
62
+ repository: {
63
+ url: "https://github.com/drupal-canvas/headless-templates.git",
64
+ ref: "main",
65
+ path: "tanstack-start"
32
66
  }
33
67
  }
34
68
  ];
@@ -344,7 +378,7 @@ async function searchMultiselect(options) {
344
378
  required = false,
345
379
  lockedSection
346
380
  } = options;
347
- return new Promise((resolve) => {
381
+ return new Promise((resolve2) => {
348
382
  const rl = readline.createInterface({
349
383
  input: process.stdin,
350
384
  output: silentOutput,
@@ -472,12 +506,12 @@ async function searchMultiselect(options) {
472
506
  }
473
507
  render("submit");
474
508
  cleanup();
475
- resolve([...lockedValues, ...Array.from(selected)]);
509
+ resolve2([...lockedValues, ...Array.from(selected)]);
476
510
  };
477
511
  const cancel2 = () => {
478
512
  render("cancel");
479
513
  cleanup();
480
- resolve(cancelSymbol);
514
+ resolve2(cancelSymbol);
481
515
  };
482
516
  const keypressHandler = (_str, key) => {
483
517
  if (!key) return;
@@ -538,8 +572,8 @@ function pluralize(word, count) {
538
572
  // src/lib/agent-skills-setup.ts
539
573
  var DEFAULT_SKILLS_DIR = ".agents/skills";
540
574
  async function setupAgentSkills(projectDir, options = {}) {
541
- const info = options.onInfo ?? p4.log.info;
542
- const warning = options.onWarning ?? p4.log.warn;
575
+ const info = options.onInfo ?? p5.log.info;
576
+ const warning = options.onWarning ?? p5.log.warn;
543
577
  const interactive = options.interactive ?? true;
544
578
  const hasExplicitSelection = options.selectedAgents !== void 0;
545
579
  try {
@@ -565,7 +599,7 @@ async function setupAgentSkills(projectDir, options = {}) {
565
599
  const promptForAgents = options.promptForAgents ?? defaultPromptForAgents;
566
600
  selected = await promptForAgents();
567
601
  }
568
- if (p4.isCancel(selected) || typeof selected === "symbol") {
602
+ if (p5.isCancel(selected) || typeof selected === "symbol") {
569
603
  info("Skipped compatibility setup.");
570
604
  return;
571
605
  }
@@ -610,7 +644,7 @@ ${nonUniversalAgents.map(
610
644
  );
611
645
  }
612
646
  } catch (error) {
613
- const warning2 = options.onWarning ?? p4.log.warn;
647
+ const warning2 = options.onWarning ?? p5.log.warn;
614
648
  const message = error instanceof Error ? error.message : "Unknown error during compatibility setup";
615
649
  warning2(`Compatibility setup skipped: ${message}`);
616
650
  }
@@ -618,7 +652,7 @@ ${nonUniversalAgents.map(
618
652
  async function defaultPromptForAgents() {
619
653
  const universalAgents = getUniversalAgents();
620
654
  const additionalAgents = getNonUniversalAgents();
621
- p4.log.message("");
655
+ p5.log.message("");
622
656
  const selected = await searchMultiselect({
623
657
  message: "Which AI coding agents should this codebase support?",
624
658
  items: additionalAgents.map((agent) => ({
@@ -682,6 +716,16 @@ async function pathExists(path) {
682
716
  return false;
683
717
  }
684
718
  }
719
+ var DRUPAL_BLUE = "#009CDE";
720
+ var DRUPAL_NAVY = "#12285F";
721
+ var DRUPAL_PURPLE = "#CCBAF4";
722
+ function commandIntro(commandName) {
723
+ return `${chalk2.bgHex(DRUPAL_BLUE).hex(DRUPAL_NAVY)(" Drupal Canvas ")}${chalk2.bgHex(DRUPAL_PURPLE).hex(DRUPAL_NAVY)(` ${commandName} `)}`;
724
+ }
725
+ function printCommandIntro(commandName) {
726
+ console.log();
727
+ p5.intro(commandIntro(commandName));
728
+ }
685
729
 
686
730
  // src/agents.ts
687
731
  function agentsCommand(program2) {
@@ -691,7 +735,7 @@ function agentsCommand(program2) {
691
735
  "[agents]",
692
736
  'comma-separated list of additional agents to support, or "none" to skip compatibility symlinks'
693
737
  ).action(async (agentsArg) => {
694
- p4.intro(chalk2.bold("Drupal Canvas Create - agents setup"));
738
+ printCommandIntro("create agents");
695
739
  try {
696
740
  const selectedAgents = parseAgentSelection(agentsArg, "agents");
697
741
  const projectDir = process.cwd();
@@ -699,12 +743,12 @@ function agentsCommand(program2) {
699
743
  selectedAgents,
700
744
  interactive: Boolean(process.stdin.isTTY && process.stdout.isTTY)
701
745
  });
702
- p4.outro("Agent compatibility setup complete.");
746
+ p5.outro("Agent compatibility setup complete.");
703
747
  } catch (error) {
704
748
  if (error instanceof Error) {
705
- p4.log.error(`Error: ${error.message}`);
749
+ p5.log.error(`Error: ${error.message}`);
706
750
  } else {
707
- p4.log.error(`Unknown error: ${String(error)}`);
751
+ p5.log.error(`Unknown error: ${String(error)}`);
708
752
  }
709
753
  process.exit(1);
710
754
  }
@@ -729,13 +773,185 @@ function detectPackageManager() {
729
773
  // package.json
730
774
  var package_default = {
731
775
  name: "@drupal-canvas/create",
732
- version: "1.5.0",
776
+ version: "1.6.0",
733
777
  description: "CLI to scaffold a codebase for working with Drupal Canvas Code Components"};
734
778
 
735
779
  // src/lib/meta-info.ts
736
780
  var getName = () => package_default.name;
737
781
  var getDescription = () => package_default.description;
738
782
  var getVersion = () => package_default.version;
783
+ async function moveTemplateDirectory(repositoryDir, projectDir, repositoryPath) {
784
+ const templateDir = resolve(repositoryDir, repositoryPath);
785
+ const relativeTemplateDir = relative(repositoryDir, templateDir);
786
+ if (!relativeTemplateDir || relativeTemplateDir === ".." || relativeTemplateDir.startsWith(`..${sep}`) || isAbsolute(relativeTemplateDir)) {
787
+ throw new Error(
788
+ `Template repository path "${repositoryPath}" must be a relative path within the repository`
789
+ );
790
+ }
791
+ let templateStats;
792
+ try {
793
+ templateStats = await lstat(templateDir);
794
+ } catch (error) {
795
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") {
796
+ throw new Error(
797
+ `Template repository path "${repositoryPath}" does not exist`
798
+ );
799
+ }
800
+ throw error;
801
+ }
802
+ if (!templateStats.isDirectory()) {
803
+ throw new Error(
804
+ `Template repository path "${repositoryPath}" must point to a directory`
805
+ );
806
+ }
807
+ try {
808
+ await lstat(projectDir);
809
+ throw new Error(`Project directory "${projectDir}" already exists`);
810
+ } catch (error) {
811
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") ; else {
812
+ throw error;
813
+ }
814
+ }
815
+ await rename(templateDir, projectDir);
816
+ }
817
+ var ENV_FILENAME = ".env";
818
+ var ENV_EXAMPLE_FILENAME = ".env.example";
819
+ var ENV_VARIABLE = "CANVAS_SITE_URL";
820
+ function isNodeError(error) {
821
+ return error instanceof Error && "code" in error;
822
+ }
823
+ function validateSiteUrl(value) {
824
+ if (!value) return "Canvas site URL is required";
825
+ try {
826
+ const url = new URL(value);
827
+ if ((url.protocol === "http:" || url.protocol === "https:") && url.hostname) {
828
+ return;
829
+ }
830
+ } catch {
831
+ }
832
+ return "Canvas site URL must be an http:// or https:// URL";
833
+ }
834
+ async function ensureEnvIsIgnored(projectDir) {
835
+ const gitignorePath = join(projectDir, ".gitignore");
836
+ let gitignore = "";
837
+ try {
838
+ gitignore = await readFile(gitignorePath, "utf-8");
839
+ } catch (error) {
840
+ if (!isNodeError(error) || error.code !== "ENOENT") {
841
+ throw error;
842
+ }
843
+ }
844
+ const ignoresEnv = gitignore.split(/\r?\n/).some((line) => line.trim() === ENV_FILENAME);
845
+ if (ignoresEnv) return;
846
+ const separator = gitignore.length > 0 && !gitignore.endsWith("\n") ? "\n" : "";
847
+ await writeFile(
848
+ gitignorePath,
849
+ `${gitignore}${separator}${ENV_FILENAME}
850
+ `,
851
+ "utf-8"
852
+ );
853
+ }
854
+ async function readOptionalFile(path) {
855
+ try {
856
+ return await readFile(path, "utf-8");
857
+ } catch (error) {
858
+ if (isNodeError(error) && error.code === "ENOENT") {
859
+ return;
860
+ }
861
+ throw error;
862
+ }
863
+ }
864
+ function splitEnv(content) {
865
+ const eol = content.includes("\r\n") ? "\r\n" : "\n";
866
+ const hasFinalEol = content.endsWith("\n");
867
+ const lines = content.split(/\r?\n/);
868
+ if (hasFinalEol) lines.pop();
869
+ return { lines, eol, hasFinalEol };
870
+ }
871
+ function joinEnv({ lines, eol, hasFinalEol }) {
872
+ return `${lines.join(eol)}${hasFinalEol ? eol : ""}`;
873
+ }
874
+ function findAssignments(lines) {
875
+ const assignmentPattern = new RegExp(
876
+ `^(\\s*(?:export\\s+)?${ENV_VARIABLE}\\s*=\\s*)(.*)$`
877
+ );
878
+ return lines.flatMap((line, index) => {
879
+ const match = line.match(assignmentPattern);
880
+ return match ? [{ index, prefix: match[1], value: match[2] }] : [];
881
+ });
882
+ }
883
+ function setAssignment(env, siteUrl, assignment) {
884
+ const value = `${ENV_VARIABLE}=${JSON.stringify(siteUrl)}`;
885
+ if (assignment) {
886
+ env.lines[assignment.index] = `${assignment.prefix}${JSON.stringify(siteUrl)}`;
887
+ } else if (env.lines.length === 1 && env.lines[0] === "") {
888
+ env.lines[0] = value;
889
+ } else {
890
+ env.lines.push(value);
891
+ }
892
+ }
893
+ function createEnvFromExample(example, siteUrl) {
894
+ const env = splitEnv(example);
895
+ const assignments = findAssignments(env.lines);
896
+ if (assignments.length > 1) {
897
+ throw new Error(
898
+ `${ENV_EXAMPLE_FILENAME} contains more than one ${ENV_VARIABLE} assignment`
899
+ );
900
+ }
901
+ setAssignment(env, siteUrl, assignments[0]);
902
+ return joinEnv(env);
903
+ }
904
+ function hasConfiguredValue(assignment) {
905
+ const value = assignment.value.trim();
906
+ return value !== "" && value !== '""' && value !== "''" && !value.startsWith("#");
907
+ }
908
+ function updateExistingEnv(content, siteUrl) {
909
+ const env = splitEnv(content);
910
+ const assignments = findAssignments(env.lines);
911
+ const effectiveAssignment = assignments.at(-1);
912
+ if (effectiveAssignment && hasConfiguredValue(effectiveAssignment)) {
913
+ return { content, result: "existing-site-url" };
914
+ }
915
+ setAssignment(env, siteUrl, effectiveAssignment);
916
+ return { content: joinEnv(env), result: "configured-existing" };
917
+ }
918
+ function normalizeSiteUrl(siteUrl) {
919
+ const { protocol, hostname } = new URL(siteUrl);
920
+ if (protocol === "https:" && (hostname === "ddev.site" || hostname.endsWith(".ddev.site"))) {
921
+ return siteUrl.replace(/^https:\/\//i, "http://");
922
+ }
923
+ return siteUrl;
924
+ }
925
+ async function writeSiteUrlEnv(projectDir, siteUrl) {
926
+ const validationError = validateSiteUrl(siteUrl);
927
+ if (validationError) throw new Error(validationError);
928
+ siteUrl = normalizeSiteUrl(siteUrl);
929
+ const envPath = join(projectDir, ENV_FILENAME);
930
+ const existingEnv = await readOptionalFile(envPath);
931
+ if (existingEnv !== void 0) {
932
+ const updated = updateExistingEnv(existingEnv, siteUrl);
933
+ await ensureEnvIsIgnored(projectDir);
934
+ if (updated.content !== existingEnv) {
935
+ await writeFile(envPath, updated.content, "utf-8");
936
+ }
937
+ return updated.result;
938
+ }
939
+ const example = await readOptionalFile(
940
+ join(projectDir, ENV_EXAMPLE_FILENAME)
941
+ );
942
+ const envContent = example === void 0 ? `${ENV_VARIABLE}=${JSON.stringify(siteUrl)}
943
+ ` : createEnvFromExample(example, siteUrl);
944
+ await ensureEnvIsIgnored(projectDir);
945
+ try {
946
+ await writeFile(envPath, envContent, { encoding: "utf-8", flag: "wx" });
947
+ } catch (error) {
948
+ if (isNodeError(error) && error.code === "EEXIST") {
949
+ return writeSiteUrlEnv(projectDir, siteUrl);
950
+ }
951
+ throw error;
952
+ }
953
+ return example === void 0 ? "created" : "copied-example";
954
+ }
739
955
  var GIT_TERMINAL_PROMPT = 0;
740
956
  var unsafe = {
741
957
  allowUnsafeEditor: true,
@@ -749,10 +965,10 @@ var use_git_default = (baseDir) => {
749
965
 
750
966
  // src/create.ts
751
967
  async function createProject(ctx) {
752
- const { template, projectName, selectedAgents } = ctx;
968
+ const { template, projectName, siteUrl, selectedAgents, interactive } = ctx;
753
969
  const projectDir = `${process.cwd()}/${projectName}`;
754
970
  try {
755
- const s1 = p4.spinner();
971
+ const s1 = p5.spinner();
756
972
  s1.start("Fetching template");
757
973
  const hasCommitSHARef = /^[a-f0-9]{40}$/i.test(template.repository.ref);
758
974
  const git = use_git_default();
@@ -762,13 +978,35 @@ async function createProject(ctx) {
762
978
  if (template.repository.ref !== "HEAD" && !hasCommitSHARef) {
763
979
  options["--branch"] = template.repository.ref;
764
980
  }
765
- await git.clone(template.repository.url, projectName, options);
766
- const gitProjectDir = use_git_default(projectDir);
767
- if (hasCommitSHARef) {
768
- await gitProjectDir.fetch("origin", template.repository.ref);
769
- await gitProjectDir.checkout(template.repository.ref);
981
+ const repositoryPath = template.repository.path;
982
+ let temporaryCloneDir;
983
+ let cloneDir = projectDir;
984
+ if (repositoryPath) {
985
+ temporaryCloneDir = await mkdtemp(
986
+ join(process.cwd(), ".canvas-template-")
987
+ );
988
+ cloneDir = temporaryCloneDir;
989
+ }
990
+ try {
991
+ await git.clone(template.repository.url, cloneDir, options);
992
+ const gitCloneDir = use_git_default(cloneDir);
993
+ if (hasCommitSHARef) {
994
+ await gitCloneDir.fetch("origin", template.repository.ref);
995
+ await gitCloneDir.checkout(template.repository.ref);
996
+ }
997
+ if (repositoryPath) {
998
+ await moveTemplateDirectory(cloneDir, projectDir, repositoryPath);
999
+ await rimraf(cloneDir);
1000
+ temporaryCloneDir = void 0;
1001
+ }
1002
+ } catch (error) {
1003
+ if (temporaryCloneDir) {
1004
+ await rimraf(temporaryCloneDir);
1005
+ }
1006
+ throw error;
770
1007
  }
771
- await rimraf(`${projectDir}/.git`);
1008
+ const gitProjectDir = use_git_default(projectDir);
1009
+ await rimraf(join(projectDir, ".git"));
772
1010
  const packageJsonPath = join(projectDir, "package.json");
773
1011
  const packageJsonContent = await readFile(packageJsonPath, "utf-8");
774
1012
  const packageJson = JSON.parse(packageJsonContent);
@@ -777,15 +1015,35 @@ async function createProject(ctx) {
777
1015
  packageJsonPath,
778
1016
  JSON.stringify(packageJson, null, 2) + "\n"
779
1017
  );
1018
+ const siteUrlEnvResult = siteUrl ? await writeSiteUrlEnv(projectDir, siteUrl) : void 0;
780
1019
  s1.stop(chalk2.green("Fetched template"));
1020
+ switch (siteUrlEnvResult) {
1021
+ case "created":
1022
+ p5.log.info("Created .env.");
1023
+ break;
1024
+ case "copied-example":
1025
+ p5.log.info("Created .env from .env.example.");
1026
+ break;
1027
+ case "configured-existing":
1028
+ p5.log.info("Updated .env with CANVAS_SITE_URL.");
1029
+ break;
1030
+ case "existing-site-url":
1031
+ p5.log.info("Kept existing CANVAS_SITE_URL in .env.");
1032
+ break;
1033
+ case void 0:
1034
+ p5.log.warn(
1035
+ "No site URL provided. Set CANVAS_SITE_URL in .env to connect the project to your Drupal site."
1036
+ );
1037
+ break;
1038
+ }
781
1039
  await setupAgentSkills(projectDir, {
782
1040
  selectedAgents,
783
- interactive: Boolean(process.stdin.isTTY && process.stdout.isTTY)
1041
+ interactive
784
1042
  });
785
- const s2 = p4.spinner();
1043
+ const s2 = p5.spinner();
786
1044
  const packageManager = detectPackageManager();
787
1045
  s2.start(`Installing dependencies with ${packageManager}`);
788
- await new Promise((resolve, reject) => {
1046
+ await new Promise((resolve2, reject) => {
789
1047
  const child = spawn(packageManager, ["install"], {
790
1048
  cwd: `./${projectName}`,
791
1049
  stdio: ["ignore", "ignore", "pipe"],
@@ -814,25 +1072,27 @@ ${stderrOutput}` : ""}`
814
1072
  )
815
1073
  );
816
1074
  } else {
817
- resolve();
1075
+ resolve2();
818
1076
  }
819
1077
  });
820
1078
  });
821
1079
  s2.stop(chalk2.green(`Installed dependencies with ${packageManager}`));
822
- const s3 = p4.spinner();
1080
+ const s3 = p5.spinner();
823
1081
  s3.start("Initializing Git repository");
824
1082
  await git.init(["--initial-branch=main", projectName]);
825
1083
  await gitProjectDir.add(["--all"]);
1084
+ const repositoryPathMessage = template.repository.path ? `
1085
+ Path: ${template.repository.path}` : "";
826
1086
  await gitProjectDir.commit(
827
1087
  `Init project using ${getName()}@${getVersion()}
828
1088
 
829
1089
  Template repository: ${template.repository.url}
830
- Ref: ${template.repository.ref}`
1090
+ Ref: ${template.repository.ref}${repositoryPathMessage}`
831
1091
  );
832
1092
  s3.stop(
833
1093
  chalk2.green("Initialized Git repository on main with initial commit")
834
1094
  );
835
- p4.note(
1095
+ p5.note(
836
1096
  `Created project in ./${projectName}
837
1097
 
838
1098
  Next steps:
@@ -840,12 +1100,12 @@ Next steps:
840
1100
  ${packageManager} run dev`,
841
1101
  "Get started"
842
1102
  );
843
- p4.outro("Canvas project created successfully.");
1103
+ p5.outro("Canvas project created successfully.");
844
1104
  } catch (error) {
845
1105
  if (error instanceof Error) {
846
- p4.log.error(`Error: ${error.message}`);
1106
+ p5.log.error(`Error: ${error.message}`);
847
1107
  } else {
848
- p4.log.error(`Unknown error: ${String(error)}`);
1108
+ p5.log.error(`Unknown error: ${String(error)}`);
849
1109
  }
850
1110
  process.exit(1);
851
1111
  }
@@ -864,6 +1124,38 @@ function validateName(name) {
864
1124
  };
865
1125
  }
866
1126
 
1127
+ // src/lib/slugify-project-name.ts
1128
+ var DEFAULT_PROJECT_NAME = "my-canvas-project";
1129
+ var MAX_PACKAGE_NAME_LENGTH = 214;
1130
+ function slugifyProjectName(siteName) {
1131
+ const slug = slugify(siteName).slice(0, MAX_PACKAGE_NAME_LENGTH).replace(/-+$/g, "");
1132
+ if (!slug || !validateName(slug).valid) {
1133
+ return DEFAULT_PROJECT_NAME;
1134
+ }
1135
+ return slug;
1136
+ }
1137
+
1138
+ // src/lib/template-resolution.ts
1139
+ function resolveTemplate(templates, identifier) {
1140
+ return templates.find(
1141
+ (template) => template.id === identifier || template.aliases?.includes(identifier)
1142
+ );
1143
+ }
1144
+ function assertUniqueTemplateIdentifiers(templates) {
1145
+ const identifiers = /* @__PURE__ */ new Map();
1146
+ for (const template of templates) {
1147
+ for (const identifier of [template.id, ...template.aliases ?? []]) {
1148
+ const existingTemplateId = identifiers.get(identifier);
1149
+ if (existingTemplateId) {
1150
+ throw new Error(
1151
+ `Template identifier "${identifier}" is used by both "${existingTemplateId}" and "${template.id}"`
1152
+ );
1153
+ }
1154
+ identifiers.set(identifier, template.id);
1155
+ }
1156
+ }
1157
+ }
1158
+
867
1159
  // src/index.ts
868
1160
  process.on("SIGINT", () => process.exit(0));
869
1161
  process.on("SIGTERM", () => process.exit(0));
@@ -877,14 +1169,30 @@ program.name(getName()).description(getDescription()).version(getVersion()).argu
877
1169
  ).option(
878
1170
  "-a, --agents <agents>",
879
1171
  'comma-separated list of additional agents to support, or "none" to skip compatibility symlinks'
1172
+ ).option(
1173
+ "--experimental-headless",
1174
+ "enable experimental headless frontend templates"
1175
+ ).option(
1176
+ "--site-name <name>",
1177
+ "use slugified site name as the suggested project name"
1178
+ ).option(
1179
+ "--site-url <url>",
1180
+ "use Canvas site URL when configuring the project"
880
1181
  ).action(
881
1182
  async (projectNameArg, options) => {
882
- p4.intro(chalk2.bold("Drupal Canvas Create"));
1183
+ printCommandIntro("create");
883
1184
  try {
1185
+ const interactive = Boolean(
1186
+ process.stdin.isTTY && process.stdout.isTTY
1187
+ );
884
1188
  const selectedAgents = parseAgentSelection(options.agents);
1189
+ const predefinedTemplates = templates_default;
1190
+ assertUniqueTemplateIdentifiers(predefinedTemplates);
1191
+ const availableTemplates = options.experimentalHeadless ? predefinedTemplates : predefinedTemplates.filter((template2) => !template2.experimental);
885
1192
  if (options.template) {
886
- const template2 = templates_default.find(
887
- (t) => t.id === options.template
1193
+ const template2 = resolveTemplate(
1194
+ predefinedTemplates,
1195
+ options.template
888
1196
  );
889
1197
  const isCustomRepositoryUrl = [
890
1198
  // Remote repositories.
@@ -897,7 +1205,7 @@ program.name(getName()).description(getDescription()).version(getVersion()).argu
897
1205
  "/"
898
1206
  ].some((prefix) => options.template?.startsWith(prefix));
899
1207
  if (!template2 && isCustomRepositoryUrl) {
900
- templates_default.push({
1208
+ predefinedTemplates.push({
901
1209
  id: options.template,
902
1210
  label: options.template,
903
1211
  repository: {
@@ -906,20 +1214,24 @@ program.name(getName()).description(getDescription()).version(getVersion()).argu
906
1214
  }
907
1215
  });
908
1216
  } else if (!template2) {
909
- p4.log.error(
1217
+ p5.log.error(
910
1218
  `Template "${options.template}" not found.
911
1219
 
912
1220
  Available templates:
913
- ${templates_default.map((availableTemplate) => `- ${availableTemplate.id}`).join("\n")}`
1221
+ ${availableTemplates.map((availableTemplate) => `- ${availableTemplate.id}`).join("\n")}`
914
1222
  );
915
1223
  process.exit(1);
916
1224
  }
917
1225
  }
918
1226
  let projectName = projectNameArg;
919
1227
  if (!projectName) {
920
- const name = await p4.text({
1228
+ if (!interactive) {
1229
+ p5.log.error("Project name is required in a non-interactive run.");
1230
+ process.exit(1);
1231
+ }
1232
+ const name = await p5.text({
921
1233
  message: "Enter the project name",
922
- initialValue: "my-canvas-project",
1234
+ initialValue: options.siteName === void 0 ? DEFAULT_PROJECT_NAME : slugifyProjectName(options.siteName),
923
1235
  validate: (value) => {
924
1236
  if (!value) return "Project name is required";
925
1237
  const { valid, problems } = validateName(value);
@@ -929,49 +1241,86 @@ ${templates_default.map((availableTemplate) => `- ${availableTemplate.id}`).join
929
1241
  return;
930
1242
  }
931
1243
  });
932
- if (p4.isCancel(name)) {
933
- p4.cancel("Operation cancelled");
1244
+ if (p5.isCancel(name)) {
1245
+ p5.cancel("Operation cancelled");
934
1246
  process.exit(0);
935
1247
  }
936
1248
  projectName = name;
937
1249
  } else {
938
1250
  const { valid, problems } = validateName(projectName);
939
1251
  if (!valid) {
940
- p4.log.error(`Invalid project name: ${problems.join(", ")}`);
1252
+ p5.log.error(`Invalid project name: ${problems.join(", ")}`);
1253
+ process.exit(1);
1254
+ }
1255
+ }
1256
+ let siteUrl = options.siteUrl ?? process.env.CANVAS_SITE_URL;
1257
+ if (!siteUrl?.trim()) {
1258
+ if (interactive) {
1259
+ const enteredSiteUrl = await p5.text({
1260
+ message: "Enter the Drupal site URL",
1261
+ validate: (value) => validateSiteUrl(value.trim())
1262
+ });
1263
+ if (p5.isCancel(enteredSiteUrl)) {
1264
+ p5.cancel("Operation cancelled");
1265
+ process.exit(0);
1266
+ }
1267
+ siteUrl = enteredSiteUrl;
1268
+ } else {
1269
+ siteUrl = void 0;
1270
+ }
1271
+ }
1272
+ if (siteUrl !== void 0) {
1273
+ siteUrl = siteUrl.trim();
1274
+ const siteUrlValidationError = validateSiteUrl(siteUrl);
1275
+ if (siteUrlValidationError) {
1276
+ p5.log.error(siteUrlValidationError);
941
1277
  process.exit(1);
942
1278
  }
943
1279
  }
944
1280
  let templateId = options.template;
945
1281
  if (!templateId) {
946
- if (templates_default.length === 1) {
947
- templateId = templates_default[0].id;
1282
+ if (availableTemplates.length === 1) {
1283
+ templateId = availableTemplates[0].id;
948
1284
  } else {
949
- const selected = await p4.select({
1285
+ if (!interactive) {
1286
+ p5.log.error(
1287
+ "Template is required in a non-interactive run. Use --template."
1288
+ );
1289
+ process.exit(1);
1290
+ }
1291
+ const selected = await p5.select({
950
1292
  message: "Select a template",
951
- options: templates_default.map((t, index) => ({
952
- value: t.id,
953
- label: index === 0 ? `${t.label} (Recommended)` : t.label
1293
+ options: availableTemplates.map((template2) => ({
1294
+ value: template2.id,
1295
+ label: template2.label
954
1296
  }))
955
1297
  });
956
- if (p4.isCancel(selected)) {
957
- p4.cancel("Operation cancelled");
1298
+ if (p5.isCancel(selected)) {
1299
+ p5.cancel("Operation cancelled");
958
1300
  process.exit(0);
959
1301
  }
960
1302
  templateId = selected;
961
1303
  }
962
1304
  }
963
- const template = templates_default.find(
964
- (t) => t.id === templateId
1305
+ const template = resolveTemplate(
1306
+ predefinedTemplates,
1307
+ templateId
965
1308
  );
966
1309
  if (options.ref) {
967
1310
  template.repository.ref = options.ref;
968
1311
  }
969
- await createProject({ template, projectName, selectedAgents });
1312
+ await createProject({
1313
+ template,
1314
+ projectName,
1315
+ siteUrl,
1316
+ selectedAgents,
1317
+ interactive
1318
+ });
970
1319
  } catch (error) {
971
1320
  if (error instanceof Error) {
972
- p4.log.error(`Error: ${error.message}`);
1321
+ p5.log.error(`Error: ${error.message}`);
973
1322
  } else {
974
- p4.log.error(`Unknown error: ${String(error)}`);
1323
+ p5.log.error(`Unknown error: ${String(error)}`);
975
1324
  }
976
1325
  process.exit(1);
977
1326
  }
@@ -0,0 +1,61 @@
1
+ # Experimental features
2
+
3
+ Experimental features may change or be removed without notice.
4
+
5
+ ## Headless frontend templates
6
+
7
+ Without `--experimental-headless`, the CLI automatically uses the default
8
+ frontend template when `--template` is omitted.
9
+
10
+ Pass `--experimental-headless` to show all frontend templates in one interactive
11
+ list:
12
+
13
+ ```bash
14
+ npx @drupal-canvas/create@latest --experimental-headless
15
+ ```
16
+
17
+ ```text
18
+ Select a template
19
+ Default frontend
20
+ Next.js
21
+ Astro
22
+ Nuxt
23
+ TanStack Start
24
+ ```
25
+
26
+ The available experimental template IDs are:
27
+
28
+ | Template ID | Label |
29
+ | ---------------- | -------------- |
30
+ | `nextjs` | Next.js |
31
+ | `astro` | Astro |
32
+ | `nuxt` | Nuxt |
33
+ | `tanstack-start` | TanStack Start |
34
+
35
+ The experimental flag is only needed for interactive discovery. An experimental
36
+ template ID can be provided directly without it:
37
+
38
+ ```bash
39
+ npx @drupal-canvas/create@latest my-project \
40
+ --template nextjs
41
+ ```
42
+
43
+ Non-interactive runs using `--experimental-headless` require both the positional
44
+ project name and `--template`, so they do not use the template prompt. Without
45
+ the flag, the default frontend is selected automatically.
46
+
47
+ Experimental templates set `experimental` in `templates.json`. They can share a
48
+ repository by setting a repository-relative `path`:
49
+
50
+ ```json
51
+ {
52
+ "id": "nextjs",
53
+ "label": "Next.js",
54
+ "experimental": true,
55
+ "repository": {
56
+ "url": "https://github.com/drupal-canvas/headless-templates.git",
57
+ "ref": "main",
58
+ "path": "nextjs"
59
+ }
60
+ }
61
+ ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@drupal-canvas/create",
3
- "version": "1.5.0",
3
+ "version": "1.6.0",
4
4
  "description": "CLI to scaffold a codebase for working with Drupal Canvas Code Components",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -13,6 +13,7 @@
13
13
  "type": "module",
14
14
  "files": [
15
15
  "dist",
16
+ "docs",
16
17
  "templates.json",
17
18
  "README.md"
18
19
  ],
@@ -23,10 +24,11 @@
23
24
  "create"
24
25
  ],
25
26
  "engines": {
26
- "node": ">=18.20.0"
27
+ "node": ">=20.0.0"
27
28
  },
28
29
  "dependencies": {
29
30
  "@clack/prompts": "^0.11.0",
31
+ "@sindresorhus/slugify": "^3.0.0",
30
32
  "chalk": "^5.6.2",
31
33
  "commander": "^14.0.2",
32
34
  "cross-spawn": "^7.0.6",
package/templates.json CHANGED
@@ -1,18 +1,51 @@
1
1
  [
2
2
  {
3
- "id": "acquia-nebula",
4
- "label": "acquia/nebula",
3
+ "id": "default",
4
+ "aliases": ["acquia-nebula"],
5
+ "label": "Default (Canvas-rendered React)",
5
6
  "repository": {
6
7
  "url": "https://github.com/acquia/nebula.git",
7
8
  "ref": "main"
8
9
  }
9
10
  },
10
11
  {
11
- "id": "balintbrews-canvas-starter",
12
- "label": "balintbrews/canvas-starter",
12
+ "id": "nextjs",
13
+ "label": "Next.js",
14
+ "experimental": true,
13
15
  "repository": {
14
- "url": "https://github.com/balintbrews/canvas-starter.git",
15
- "ref": "main"
16
+ "url": "https://github.com/drupal-canvas/headless-templates.git",
17
+ "ref": "main",
18
+ "path": "nextjs"
19
+ }
20
+ },
21
+ {
22
+ "id": "astro",
23
+ "label": "Astro",
24
+ "experimental": true,
25
+ "repository": {
26
+ "url": "https://github.com/drupal-canvas/headless-templates.git",
27
+ "ref": "main",
28
+ "path": "astro"
29
+ }
30
+ },
31
+ {
32
+ "id": "nuxt",
33
+ "label": "Nuxt",
34
+ "experimental": true,
35
+ "repository": {
36
+ "url": "https://github.com/drupal-canvas/headless-templates.git",
37
+ "ref": "main",
38
+ "path": "nuxt"
39
+ }
40
+ },
41
+ {
42
+ "id": "tanstack-start",
43
+ "label": "TanStack Start",
44
+ "experimental": true,
45
+ "repository": {
46
+ "url": "https://github.com/drupal-canvas/headless-templates.git",
47
+ "ref": "main",
48
+ "path": "tanstack-start"
16
49
  }
17
50
  }
18
51
  ]