create-gtkx 2.0.0-beta.9 → 2.0.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.
Files changed (71) hide show
  1. package/README.md +8 -166
  2. package/dependency-ranges.json +7 -0
  3. package/dist/build-allowance.d.ts +43 -2
  4. package/dist/build-allowance.d.ts.map +1 -1
  5. package/dist/build-allowance.js +360 -9
  6. package/dist/build-allowance.js.map +1 -1
  7. package/dist/cli.js +1 -1
  8. package/dist/cli.js.map +1 -1
  9. package/dist/command.d.ts +3 -2
  10. package/dist/command.d.ts.map +1 -1
  11. package/dist/command.js +93 -90
  12. package/dist/command.js.map +1 -1
  13. package/dist/errors.d.ts.map +1 -1
  14. package/dist/index.d.ts +1 -0
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +1 -0
  17. package/dist/index.js.map +1 -1
  18. package/dist/manifest.d.ts.map +1 -1
  19. package/dist/manifest.js +2 -10
  20. package/dist/manifest.js.map +1 -1
  21. package/dist/package-managers.d.ts +6 -3
  22. package/dist/package-managers.d.ts.map +1 -1
  23. package/dist/package-managers.js +6 -3
  24. package/dist/package-managers.js.map +1 -1
  25. package/dist/project-name.d.ts +4 -2
  26. package/dist/project-name.d.ts.map +1 -1
  27. package/dist/project-name.js +12 -2
  28. package/dist/project-name.js.map +1 -1
  29. package/dist/scaffolder.d.ts.map +1 -1
  30. package/dist/scaffolder.js +199 -199
  31. package/dist/scaffolder.js.map +1 -1
  32. package/dist/templates/.claude/settings.json.ejs +4 -3
  33. package/dist/templates/.gitignore.ejs +4 -0
  34. package/dist/templates/.mcp.json.ejs +1 -1
  35. package/dist/templates/gtkx.config.ts.ejs +2 -2
  36. package/dist/templates/package.json.ejs +4 -1
  37. package/dist/templates/src/app.tsx.ejs +1 -1
  38. package/dist/templates/src/gtkx-env.d.ts.ejs +0 -1
  39. package/dist/templates/tsconfig.json.ejs +4 -2
  40. package/dist/templates.d.ts +3 -0
  41. package/dist/templates.d.ts.map +1 -1
  42. package/dist/templates.js +10 -6
  43. package/dist/templates.js.map +1 -1
  44. package/dist/workspace-mcp.d.ts +33 -0
  45. package/dist/workspace-mcp.d.ts.map +1 -0
  46. package/dist/workspace-mcp.js +75 -0
  47. package/dist/workspace-mcp.js.map +1 -0
  48. package/package.json +20 -39
  49. package/src/build-allowance.ts +486 -9
  50. package/src/cli.ts +1 -1
  51. package/src/command.ts +114 -110
  52. package/src/index.ts +1 -0
  53. package/src/manifest.ts +2 -10
  54. package/src/package-managers.ts +6 -3
  55. package/src/project-name.ts +19 -2
  56. package/src/scaffolder.ts +294 -286
  57. package/src/templates/.claude/settings.json.ejs +4 -3
  58. package/src/templates/.gitignore.ejs +4 -0
  59. package/src/templates/.mcp.json.ejs +1 -1
  60. package/src/templates/gtkx.config.ts.ejs +2 -2
  61. package/src/templates/package.json.ejs +4 -1
  62. package/src/templates/src/app.tsx.ejs +1 -1
  63. package/src/templates/src/gtkx-env.d.ts.ejs +0 -1
  64. package/src/templates/tsconfig.json.ejs +4 -2
  65. package/src/templates.ts +17 -8
  66. package/src/workspace-mcp.ts +111 -0
  67. package/dist/install-hints.d.ts +0 -3
  68. package/dist/install-hints.d.ts.map +0 -1
  69. package/dist/install-hints.js +0 -35
  70. package/dist/install-hints.js.map +0 -1
  71. package/src/install-hints.ts +0 -54
package/src/scaffolder.ts CHANGED
@@ -1,15 +1,21 @@
1
1
  import * as p from "@clack/prompts";
2
2
  import { APPLICATION_ID_MAX_LENGTH, isValidApplicationId } from "@gtkx/config/internal";
3
- import { errorMessage, tryResolveExecutable, upperFirst } from "@gtkx/utils";
3
+ import { errorMessage, HEADLESS_DISPLAY_TOOLS, missingToolLines, tryResolveExecutable, upperFirst } from "@gtkx/utils";
4
4
  import { execFileSync } from "node:child_process";
5
- import { lstatSync, mkdirSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
6
- import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
5
+ import { lstatSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
6
+ import { homedir } from "node:os";
7
+ import { basename, dirname, join, relative, resolve, sep } from "node:path";
7
8
  import { addDependency, detectPackageManager as nypmDetectPackageManager } from "nypm";
8
9
  import { x } from "tinyexec";
9
10
  import packageManifest from "../package.json" with { type: "json" };
10
- import { writeBuildAllowance } from "./build-allowance.js";
11
+ import {
12
+ PACKAGE_MANAGER_CONFIG_FILES,
13
+ enclosingWorkspace,
14
+ packageManagerPin,
15
+ type Workspace,
16
+ writePackageManagerSettings,
17
+ } from "./build-allowance.js";
11
18
  import { OperationCanceledError, ScaffoldAbortedError } from "./errors.js";
12
- import { getInstallHint } from "./install-hints.js";
13
19
  import { updateManifest } from "./manifest.js";
14
20
  import {
15
21
  isKnownPackageManager,
@@ -17,8 +23,9 @@ import {
17
23
  PACKAGE_MANAGERS,
18
24
  type PackageManager,
19
25
  } from "./package-managers.js";
20
- import { isValidProjectName } from "./project-name.js";
26
+ import { isValidPackageName, packageNameFromDirectory, withoutAccents } from "./project-name.js";
21
27
  import { listTemplates, renderFile, type TemplateContext } from "./templates.js";
28
+ import { addWorkspaceMcpServer } from "./workspace-mcp.js";
22
29
 
23
30
  type CreateOptions = {
24
31
  name?: string | undefined;
@@ -35,11 +42,11 @@ type CreateOptions = {
35
42
  type ResolvedOptions = {
36
43
  target: string;
37
44
  root: string;
38
- isCurrentDirectory: boolean;
39
45
  name: string;
40
46
  displayName: string;
41
47
  applicationId: string;
42
48
  packageManager: PackageManager;
49
+ workspace: Workspace | null;
43
50
  isTypescript: boolean;
44
51
  shouldIncludeTesting: boolean;
45
52
  shouldInitializeGit: boolean;
@@ -54,29 +61,12 @@ type ScaffoldPlan = {
54
61
  files: ScaffoldFile[];
55
62
  replaceDestinations: string[];
56
63
  changes: ScaffoldChanges;
64
+ packageManagerPin: string | null;
57
65
  };
58
66
 
59
- type ScaffoldChange = {
60
- destination: string;
61
- relativePath: string;
62
- };
63
-
64
- type InstallDependenciesOptions = {
65
- cwd: string;
66
- packageManager: PackageManager;
67
- dependencies: string[];
68
- isDev: boolean;
69
- };
70
-
71
- type InstallAllOptions = {
72
- resolved: ResolvedOptions;
73
- devDependencies: string[];
74
- };
75
-
76
- type InstallFailureOptions = {
77
- error: unknown;
78
- resolved: ResolvedOptions;
79
- devDependencies: string[];
67
+ type Progress = {
68
+ stop: (message: string) => void;
69
+ error: (message: string) => void;
80
70
  };
81
71
 
82
72
  type SpinnerStep = {
@@ -84,54 +74,60 @@ type SpinnerStep = {
84
74
  done: string;
85
75
  failed: string;
86
76
  run: () => Promise<void> | void;
87
- explain?: ((error: unknown) => void) | undefined;
77
+ explain?: (() => void) | undefined;
88
78
  };
89
79
 
90
80
  const selfVersion = packageManifest.version;
91
81
  const ICON_TEMPLATE_NAME = "icon.svg";
92
82
  const TYPESCRIPT_VERSION = "^6.0.3";
93
-
94
- const GTKX_ENV_MODULE_HEADER = `/**
95
- * Generated by \`gtkx codegen\`, \`gtkx dev\`, and \`gtkx build\`; do not edit.
96
- */`;
83
+ const DEPENDENCY_RANGES: Record<string, string | undefined> = {
84
+ ...(JSON.parse(readFileSync(new URL("../dependency-ranges.json", import.meta.url), "utf8")) as Record<
85
+ string,
86
+ string
87
+ >),
88
+ typescript: TYPESCRIPT_VERSION,
89
+ };
97
90
 
98
91
  const DEPENDENCIES = ["@gtkx/cairo", "@gtkx/css", "@gtkx/runtime", "@gtkx/react", "react"];
99
- const DEV_DEPENDENCIES = ["@gtkx/cli", "@gtkx/config", "@gtkx/mcp", "vite"];
100
- const TYPESCRIPT_DEV_DEPENDENCIES = ["@types/node", "@types/react", "typescript"];
101
- const TESTING_DEV_DEPENDENCIES = ["@gtkx/testing", "vitest"];
92
+ const DEV_DEPENDENCIES = ["@gtkx/cli", "@gtkx/config", "@gtkx/mcp", "@gtkx/testing", "@types/react", "vite"];
93
+ const TYPESCRIPT_DEV_DEPENDENCIES = ["@types/node", "typescript"];
94
+ const TESTING_DEV_DEPENDENCIES = ["vitest"];
102
95
 
103
96
  const DEV_COMMAND: Record<PackageManager, string> = Object.fromEntries(
104
97
  PACKAGE_MANAGERS.map((manager) => [manager.value, manager.devCommand]),
105
98
  ) as Record<PackageManager, string>;
106
99
 
107
- const ADD_COMMAND: Record<PackageManager, string> = Object.fromEntries(
108
- PACKAGE_MANAGERS.map((manager) => [manager.value, manager.addCommand]),
109
- ) as Record<PackageManager, string>;
110
-
111
100
  const INSTALL_COMMAND: Record<PackageManager, string> = Object.fromEntries(
112
101
  PACKAGE_MANAGERS.map((manager) => [manager.value, manager.installCommand]),
113
102
  ) as Record<PackageManager, string>;
114
103
 
104
+ const RUN_COMMAND: Record<PackageManager, string> = Object.fromEntries(
105
+ PACKAGE_MANAGERS.map((manager) => [manager.value, manager.runCommand]),
106
+ ) as Record<PackageManager, string>;
107
+
108
+ const TEST_COMMAND: Record<PackageManager, string> = Object.fromEntries(
109
+ PACKAGE_MANAGERS.map((manager) => [manager.value, manager.testCommand]),
110
+ ) as Record<PackageManager, string>;
111
+
115
112
  const INHERITED_SCRIPT_POLICY_VARS = ["npm_config_allow_scripts", "npm_config_allow-scripts"];
113
+ const LENIENT_PNPM_BUILDS_ENV = { pnpm_config_strict_dep_builds: "false" };
116
114
  const TESTING_TEMPLATES = new Set(["vitest.config.ts", "tests/app.test.tsx"]);
117
115
  const TYPESCRIPT_TEMPLATES = new Set(["tsconfig.json", "src/gtkx-env.d.ts"]);
118
116
 
119
- const HEADLESS_COMPOSITOR_NOTE = `
120
-
121
- To run tests, you need a headless Wayland compositor installed:
122
- Fedora: sudo dnf install sway
123
- Ubuntu: sudo apt install sway`;
124
-
125
- const RECOVERY_HEADING = "Finish the setup by adding the dependencies again, which is safe to repeat:";
126
117
  const APPLICATION_ID_FORMAT_ERROR = "Application ID must be reverse domain notation (e.g., com.example.myapp)";
118
+ const PACKAGE_NAME_FORMAT_ERROR = "Package name must be a valid npm package name: lowercase, no spaces (e.g., my-app)";
127
119
  const APPLICATION_ID_PREFIX = "com.";
128
120
  const APPLICATION_ID_SUFFIX = ".app";
129
121
 
130
- const APPLICATION_ID_SEGMENT_LIMIT = APPLICATION_ID_MAX_LENGTH - APPLICATION_ID_PREFIX.length -
131
- APPLICATION_ID_SUFFIX.length;
122
+ const APPLICATION_ID_SEGMENT_LIMIT =
123
+ APPLICATION_ID_MAX_LENGTH - APPLICATION_ID_PREFIX.length - APPLICATION_ID_SUFFIX.length;
132
124
 
133
- const displayNameFromProjectName = (name: string): string =>
134
- name.split("-").map((part) => upperFirst(part)).join(" ");
125
+ const displayNameFromDirectory = (directoryName: string): string =>
126
+ directoryName
127
+ .split(/[\s._-]+/)
128
+ .filter((part) => part.length > 0)
129
+ .map((part) => upperFirst(part))
130
+ .join(" ");
135
131
 
136
132
  const gitConfigValue = (key: string): string | null => {
137
133
  const git = tryResolveExecutable("git");
@@ -147,30 +143,23 @@ const gitConfigValue = (key: string): string | null => {
147
143
  }
148
144
  };
149
145
 
150
- const applicationIdSegment = (name: string): string => {
151
- const compact = name.replaceAll("-", "");
146
+ const compactIdentifier = (name: string): string => withoutAccents(name).replaceAll(/[^A-Za-z0-9_]/g, "");
147
+
148
+ const applicationIdSegment = (directoryName: string, name: string): string => {
149
+ const compact = compactIdentifier(directoryName) || compactIdentifier(name);
152
150
  const segment = /^[A-Za-z_]/.test(compact) ? compact : `_${compact}`;
153
151
 
154
152
  return segment.slice(0, APPLICATION_ID_SEGMENT_LIMIT);
155
153
  };
156
154
 
157
- const suggestApplicationId = (name: string): string =>
158
- `${APPLICATION_ID_PREFIX}${applicationIdSegment(name)}${APPLICATION_ID_SUFFIX}`;
155
+ const suggestApplicationId = (directoryName: string, name: string): string =>
156
+ `${APPLICATION_ID_PREFIX}${applicationIdSegment(directoryName, name)}${APPLICATION_ID_SUFFIX}`;
159
157
 
160
- const stripTrailingSlashes = (value: string): string => {
161
- let end = value.length;
158
+ const HOME_PREFIX = /^~(?=$|\/)/;
162
159
 
163
- while (end > 0 && value[end - 1] === "/") {
164
- end--;
165
- }
166
-
167
- return value.slice(0, end);
168
- };
160
+ const expandHome = (target: string): string => target.replace(HOME_PREFIX, () => homedir());
169
161
 
170
- const formatTargetDir = (target: string): string =>
171
- stripTrailingSlashes(target.trim().replaceAll(/[<>:"\\|?*]/g, ""));
172
-
173
- const deriveProjectName = (target: string): string => basename(resolve(process.cwd(), target));
162
+ const directoryNameOf = (target: string): string => basename(resolve(process.cwd(), target));
174
163
 
175
164
  const isDirEmpty = (dir: string): boolean => {
176
165
  const entries = readdirSync(dir);
@@ -201,9 +190,9 @@ const getDevDependencies = ({
201
190
  return devDeps;
202
191
  };
203
192
 
204
- const isCancellation = (value: unknown): value is symbol => p.isCancel(value);
193
+ const isCancellation = (value: unknown): value is typeof p.CANCEL_SYMBOL => p.isCancel(value);
205
194
 
206
- const guardCancellation = <T>(value: T | symbol): T => {
195
+ const guardCancellation = <T>(value: T | typeof p.CANCEL_SYMBOL): T => {
207
196
  if (isCancellation(value)) {
208
197
  p.cancel("Operation canceled");
209
198
  throw new OperationCanceledError();
@@ -212,17 +201,14 @@ const guardCancellation = <T>(value: T | symbol): T => {
212
201
  return value;
213
202
  };
214
203
 
215
- const validateProjectName = (value: string | undefined): string | undefined => {
216
- if (!value) {
217
- return "Project name is required";
218
- }
204
+ const validatePackageNameFormat = (value: string): string | undefined =>
205
+ isValidPackageName(value) ? undefined : PACKAGE_NAME_FORMAT_ERROR;
219
206
 
220
- if (!isValidProjectName(value)) {
221
- return "Project name must be lowercase letters, numbers, and hyphens only";
222
- }
207
+ const validatePackageNameInput = (value: string | undefined): string | undefined =>
208
+ value ? validatePackageNameFormat(value) : "Package name is required";
223
209
 
224
- return undefined;
225
- };
210
+ const validatePackageNameAnswer = (value: string | undefined): string | undefined =>
211
+ value ? validatePackageNameFormat(value) : undefined;
226
212
 
227
213
  const validateApplicationIdFormat = (value: string): string | undefined =>
228
214
  isValidApplicationId(value) ? undefined : APPLICATION_ID_FORMAT_ERROR;
@@ -261,30 +247,32 @@ const requestedPackageManager = (value: string | undefined): PackageManager | un
261
247
  return value;
262
248
  };
263
249
 
264
- const validateTargetDir = (target: string): string | undefined => {
265
- if (!target) {
266
- return "Project directory is required";
267
- }
268
-
269
- return validateProjectName(deriveProjectName(target));
270
- };
250
+ const validateTargetDir = (target: string): string | undefined =>
251
+ target ? undefined : "Project directory is required";
271
252
 
272
253
  const validateTargetAnswer = (value: string | undefined): string | undefined =>
273
- validateTargetDir(formatTargetDir(value ?? ""));
254
+ validateTargetDir(expandHome(value ?? ""));
274
255
 
275
256
  const promptTarget = async (): Promise<string> =>
276
- formatTargetDir(
277
- guardCancellation(
278
- await p.text({
279
- message: "Project directory",
280
- placeholder: "my-app",
281
- validate: validateTargetAnswer,
282
- }),
283
- ),
257
+ guardCancellation(
258
+ await p.text({
259
+ message: "Project directory",
260
+ placeholder: "my-app",
261
+ validate: validateTargetAnswer,
262
+ }),
284
263
  );
285
264
 
286
- const promptApplicationId = async (name: string): Promise<string> => {
287
- const defaultApplicationId = suggestApplicationId(name);
265
+ const promptPackageName = async (derived: string): Promise<string> =>
266
+ guardCancellation(
267
+ await p.text({
268
+ message: "Package name",
269
+ ...(derived === "" ? {} : { placeholder: derived, defaultValue: derived }),
270
+ validate: derived === "" ? validatePackageNameInput : validatePackageNameAnswer,
271
+ }),
272
+ );
273
+
274
+ const promptApplicationId = async (directoryName: string, name: string): Promise<string> => {
275
+ const defaultApplicationId = suggestApplicationId(directoryName, name);
288
276
 
289
277
  return guardCancellation(
290
278
  await p.text({
@@ -296,8 +284,8 @@ const promptApplicationId = async (name: string): Promise<string> => {
296
284
  );
297
285
  };
298
286
 
299
- const promptDisplayName = async (name: string): Promise<string> => {
300
- const defaultDisplayName = displayNameFromProjectName(name);
287
+ const promptDisplayName = async (directoryName: string): Promise<string> => {
288
+ const defaultDisplayName = displayNameFromDirectory(directoryName);
301
289
 
302
290
  return guardCancellation(
303
291
  await p.text({
@@ -348,11 +336,7 @@ const isOptionEnabled = async (
348
336
  value: boolean | undefined,
349
337
  isInteractive: boolean | undefined,
350
338
  message: string,
351
- ): Promise<boolean> =>
352
- value ??
353
- (isInteractive
354
- ? guardCancellation(await p.confirm({ message, initialValue: true }))
355
- : true);
339
+ ): Promise<boolean> => value ?? (!isInteractive || guardCancellation(await p.confirm({ message, initialValue: true })));
356
340
 
357
341
  const formatFileList = (heading: string, files: string[]): string => {
358
342
  const indentedFiles = files.map((file) => ` ${file}`).join("\n");
@@ -418,7 +402,11 @@ const acceptNonEmptyDirectory = async (
418
402
  };
419
403
 
420
404
  const assertTargetIsDirectory = (root: string, target: string): void => {
421
- const stats = statSync(root, { throwIfNoEntry: false });
405
+ const stats = lstatSync(root, { throwIfNoEntry: false });
406
+
407
+ if (stats?.isSymbolicLink()) {
408
+ fail(`Cannot scaffold through a symbolic link: ${root}`);
409
+ }
422
410
 
423
411
  if (stats !== undefined && !stats.isDirectory()) {
424
412
  fail(`Target "${target}" is not a directory`);
@@ -432,7 +420,6 @@ const validateTargetAvailability = async (
432
420
  changes: ScaffoldChanges,
433
421
  ): Promise<void> => {
434
422
  const stats = statSync(root, { throwIfNoEntry: false });
435
- assertTargetIsDirectory(root, target);
436
423
 
437
424
  if (stats === undefined || isDirEmpty(root)) {
438
425
  return;
@@ -443,27 +430,50 @@ const validateTargetAvailability = async (
443
430
 
444
431
  const resolveTarget = async (options: CreateOptions): Promise<string> => {
445
432
  if (options.name === undefined && options.isInteractive) {
446
- return promptTarget();
433
+ return expandHome(await promptTarget());
447
434
  }
448
435
 
449
- const target = formatTargetDir(options.name ?? "");
436
+ const target = expandHome(options.name ?? "");
450
437
  const error = validateTargetDir(target);
451
438
 
452
439
  return error === undefined ? target : fail(error);
453
440
  };
454
441
 
455
- const resolveApplicationId = async (options: CreateOptions, name: string): Promise<string> => {
456
- const applicationId = options.applicationId ??
457
- (options.isInteractive ? await promptApplicationId(name) : suggestApplicationId(name));
442
+ const resolvePackageName = async (options: CreateOptions, directoryName: string): Promise<string> => {
443
+ const derived = packageNameFromDirectory(directoryName);
444
+
445
+ if (derived === directoryName) {
446
+ return derived;
447
+ }
448
+
449
+ if (options.isInteractive) {
450
+ return promptPackageName(derived);
451
+ }
452
+
453
+ return derived === ""
454
+ ? fail(
455
+ `Directory name "${directoryName}" has no Latin letters or numbers to derive a package name from. ` +
456
+ "Rename it, or run interactively to enter a package name",
457
+ )
458
+ : derived;
459
+ };
460
+
461
+ const resolveApplicationId = async (options: CreateOptions, directoryName: string, name: string): Promise<string> => {
462
+ const applicationId =
463
+ options.applicationId ??
464
+ (options.isInteractive
465
+ ? await promptApplicationId(directoryName, name)
466
+ : suggestApplicationId(directoryName, name));
458
467
 
459
468
  const error = validateApplicationIdInput(applicationId);
460
469
 
461
470
  return error === undefined ? applicationId : fail(error);
462
471
  };
463
472
 
464
- const resolveDisplayName = async (options: CreateOptions, name: string): Promise<string> => {
465
- const value = options.displayName ??
466
- (options.isInteractive ? await promptDisplayName(name) : displayNameFromProjectName(name));
473
+ const resolveDisplayName = async (options: CreateOptions, directoryName: string): Promise<string> => {
474
+ const value =
475
+ options.displayName ??
476
+ (options.isInteractive ? await promptDisplayName(directoryName) : displayNameFromDirectory(directoryName));
467
477
  const error = validateDisplayName(value);
468
478
 
469
479
  return error === undefined ? value.trim() : fail(error);
@@ -487,11 +497,11 @@ const resolvePackageManager = async (
487
497
  const resolveOptions = async (options: CreateOptions): Promise<ResolvedOptions> => {
488
498
  const requested = requestedPackageManager(options.packageManager);
489
499
  const target = await resolveTarget(options);
490
- const name = deriveProjectName(target);
491
- const displayName = await resolveDisplayName(options, name);
492
- const applicationId = await resolveApplicationId(options, name);
500
+ const directoryName = directoryNameOf(target);
501
+ const name = await resolvePackageName(options, directoryName);
502
+ const displayName = await resolveDisplayName(options, directoryName);
503
+ const applicationId = await resolveApplicationId(options, directoryName, name);
493
504
  const root = resolve(process.cwd(), target);
494
- const isCurrentDirectory = root === process.cwd();
495
505
  const shouldInitialize = shouldInitializeGit(root);
496
506
  const packageManager = await resolvePackageManager(requested, options);
497
507
  const isTypescript = await isOptionEnabled(options.isTypescript, options.isInteractive, "Use TypeScript?");
@@ -505,11 +515,11 @@ const resolveOptions = async (options: CreateOptions): Promise<ResolvedOptions>
505
515
  return {
506
516
  target,
507
517
  root,
508
- isCurrentDirectory,
509
518
  name,
510
519
  displayName,
511
520
  applicationId,
512
521
  packageManager,
522
+ workspace: enclosingWorkspace(root, packageManager),
513
523
  isTypescript,
514
524
  shouldIncludeTesting,
515
525
  shouldInitializeGit: shouldInitialize,
@@ -537,6 +547,17 @@ const destinationPath = (template: string, resolved: ResolvedOptions): string =>
537
547
  : scriptPath;
538
548
  };
539
549
 
550
+ const scriptCommands = ({
551
+ packageManager,
552
+ isTypescript,
553
+ shouldIncludeTesting,
554
+ }: Pick<ResolvedOptions, "packageManager" | "isTypescript" | "shouldIncludeTesting">): string[] => [
555
+ ...["dev", "build", "codegen", ...(isTypescript ? ["typecheck"] : [])].map(
556
+ (script) => `${RUN_COMMAND[packageManager]} ${script}`,
557
+ ),
558
+ ...(shouldIncludeTesting ? [TEST_COMMAND[packageManager]] : []),
559
+ ];
560
+
540
561
  const templateContext = (resolved: ResolvedOptions): TemplateContext => ({
541
562
  name: resolved.name,
542
563
  applicationId: resolved.applicationId,
@@ -546,42 +567,10 @@ const templateContext = (resolved: ResolvedOptions): TemplateContext => ({
546
567
  importExtension: resolved.isTypescript ? ".js" : ".jsx",
547
568
  developerName: gitConfigValue("user.name") ?? resolved.displayName,
548
569
  developerEmail: gitConfigValue("user.email"),
570
+ packageManager: resolved.packageManager,
571
+ scriptCommands: scriptCommands(resolved),
549
572
  });
550
573
 
551
- const replaceTemplateDestination = (destination: string): void => {
552
- const entry = lstatSync(destination, { throwIfNoEntry: false });
553
-
554
- if (entry === undefined) {
555
- return;
556
- }
557
-
558
- if (!entry.isFile() && !entry.isSymbolicLink()) {
559
- fail(`Cannot replace scaffold file because its destination is not a file: ${destination}`);
560
- }
561
-
562
- rmSync(destination, { force: true });
563
- };
564
-
565
- const projectRelativeDestination = (root: string, destination: string): string => {
566
- const relativePath = relative(root, destination);
567
- const isOutsideProject = relativePath.length === 0 || relativePath.startsWith(`..${sep}`) ||
568
- isAbsolute(relativePath);
569
-
570
- if (isOutsideProject) {
571
- fail(`Scaffold destination is outside the project: ${destination}`);
572
- }
573
-
574
- return relativePath;
575
- };
576
-
577
- const assertRootIsNotSymbolicLink = (root: string): void => {
578
- const rootEntry = lstatSync(root, { throwIfNoEntry: false });
579
-
580
- if (rootEntry?.isSymbolicLink()) {
581
- fail(`Cannot scaffold through a symbolic link: ${root}`);
582
- }
583
- };
584
-
585
574
  const assertSafeAncestor = (ancestor: string): void => {
586
575
  const entry = lstatSync(ancestor, { throwIfNoEntry: false });
587
576
 
@@ -605,20 +594,21 @@ const assertSafeAncestors = (root: string, relativePath: string): void => {
605
594
  }
606
595
  };
607
596
 
608
- const assertReplaceableDestination = (destination: string): void => {
597
+ const hasReplaceableDestination = (destination: string): boolean => {
609
598
  const entry = lstatSync(destination, { throwIfNoEntry: false });
610
599
  const isReplaceable = entry === undefined || entry.isFile() || entry.isSymbolicLink();
611
600
 
612
601
  if (!isReplaceable) {
613
602
  fail(`Cannot replace scaffold file because its destination is not a file: ${destination}`);
614
603
  }
604
+
605
+ return entry !== undefined;
615
606
  };
616
607
 
617
- const assertSafeDestination = (root: string, destination: string): void => {
618
- const relativePath = projectRelativeDestination(root, destination);
619
- assertRootIsNotSymbolicLink(root);
620
- assertSafeAncestors(root, relativePath);
621
- assertReplaceableDestination(destination);
608
+ const hasExistingDestination = (root: string, destination: string): boolean => {
609
+ assertSafeAncestors(root, relative(root, destination));
610
+
611
+ return hasReplaceableDestination(destination);
622
612
  };
623
613
 
624
614
  const plannedScaffoldFiles = async (root: string, resolved: ResolvedOptions): Promise<ScaffoldFile[]> => {
@@ -637,66 +627,33 @@ const plannedScaffoldFiles = async (root: string, resolved: ResolvedOptions): Pr
637
627
  return files;
638
628
  };
639
629
 
640
- const auxiliaryDestinations = (root: string, resolved: ResolvedOptions): string[] =>
641
- resolved.packageManager === "pnpm" ? [join(root, "pnpm-workspace.yaml")] : [];
642
-
643
- const envModulePath = (root: string): string => join(root, "node_modules", ".gtkx", "env.d.ts");
644
-
645
- const shouldWriteEnvModule = (resolved: ResolvedOptions): boolean =>
646
- resolved.isTypescript && resolved.shouldInstallDependencies;
647
-
648
- const generatedDestinations = (root: string, resolved: ResolvedOptions): string[] =>
649
- shouldWriteEnvModule(resolved) ? [envModulePath(root)] : [];
650
-
651
- const isPresent = (path: string): boolean => lstatSync(path, { throwIfNoEntry: false }) !== undefined;
652
-
653
- const classifyScaffoldChange = (
654
- root: string,
655
- destination: string,
656
- ): ScaffoldChange | undefined => {
657
- const entry = lstatSync(destination, { throwIfNoEntry: false });
658
-
659
- if (entry === undefined) {
660
- return undefined;
661
- }
662
-
663
- return { destination, relativePath: projectRelativeDestination(root, destination) };
664
- };
665
-
666
- const addScaffoldChange = (plan: ScaffoldPlan, change: ScaffoldChange | undefined): void => {
667
- if (change === undefined) {
668
- return;
669
- }
670
-
671
- plan.replaceDestinations.push(change.destination);
672
- plan.changes.push(change.relativePath);
673
- };
630
+ const configDestinations = (root: string, resolved: ResolvedOptions): string[] =>
631
+ resolved.workspace === null
632
+ ? PACKAGE_MANAGER_CONFIG_FILES[resolved.packageManager].map((file) => join(root, file))
633
+ : [];
674
634
 
675
635
  const planScaffoldProject = async (root: string, resolved: ResolvedOptions): Promise<ScaffoldPlan> => {
676
636
  const files = await plannedScaffoldFiles(root, resolved);
677
- const reported = [...files.map((file) => file.destination), ...auxiliaryDestinations(root, resolved)];
678
- const generated = generatedDestinations(root, resolved);
679
637
 
680
- for (const destination of [...reported, ...generated]) {
681
- assertSafeDestination(root, destination);
638
+ for (const destination of configDestinations(root, resolved)) {
639
+ hasExistingDestination(root, destination);
682
640
  }
683
641
 
684
- const plan: ScaffoldPlan = {
642
+ const replaceDestinations = files
643
+ .map((file) => file.destination)
644
+ .filter((destination) => hasExistingDestination(root, destination));
645
+
646
+ return {
685
647
  files,
686
- replaceDestinations: generated.filter((destination) => isPresent(destination)),
687
- changes: [],
648
+ replaceDestinations,
649
+ changes: replaceDestinations.map((destination) => relative(root, destination)),
650
+ packageManagerPin: packageManagerPin(root, resolved.packageManager, resolved.workspace !== null),
688
651
  };
689
-
690
- for (const destination of reported) {
691
- addScaffoldChange(plan, classifyScaffoldChange(root, destination));
692
- }
693
-
694
- return plan;
695
652
  };
696
653
 
697
- const scaffoldProject = (root: string, resolved: ResolvedOptions, plan: ScaffoldPlan): void => {
654
+ const scaffoldProject = (root: string, plan: ScaffoldPlan): void => {
698
655
  for (const destination of plan.replaceDestinations) {
699
- replaceTemplateDestination(destination);
656
+ rmSync(destination);
700
657
  }
701
658
 
702
659
  for (const file of plan.files) {
@@ -704,9 +661,11 @@ const scaffoldProject = (root: string, resolved: ResolvedOptions, plan: Scaffold
704
661
  writeFileSync(file.destination, file.contents);
705
662
  }
706
663
 
707
- if (resolved.shouldIncludeTesting) {
664
+ const pin = plan.packageManagerPin;
665
+
666
+ if (pin !== null) {
708
667
  updateManifest(root, (manifest) => {
709
- (manifest.scripts as Record<string, string>).test = "vitest run";
668
+ manifest.packageManager = pin;
710
669
  });
711
670
  }
712
671
  };
@@ -729,103 +688,121 @@ const withoutInheritedScriptPolicy = async (run: () => Promise<void>): Promise<v
729
688
  }
730
689
  };
731
690
 
732
- const installDependencies = async (options: InstallDependenciesOptions): Promise<void> => {
733
- const { cwd, packageManager, dependencies, isDev } = options;
691
+ const dependencyVersions = (names: string[]): Record<string, string> =>
692
+ Object.fromEntries(
693
+ names.map((dependency) => {
694
+ if (dependency.startsWith("@gtkx/")) {
695
+ return [dependency, `^${selfVersion}`];
696
+ }
734
697
 
735
- await withoutInheritedScriptPolicy(async () => {
736
- await addDependency(dependencies, { cwd, packageManager, dev: isDev, silent: true });
737
- });
738
- };
698
+ const range = DEPENDENCY_RANGES[dependency];
739
699
 
740
- const pin = (names: string[]): string[] =>
741
- names.map((dependency) => {
742
- if (dependency.startsWith("@gtkx/")) {
743
- return `${dependency}@^${selfVersion}`;
744
- }
700
+ if (range === undefined) {
701
+ throw new Error(`No supported version range for ${dependency}`);
702
+ }
745
703
 
746
- return dependency === "typescript" ? `${dependency}@${TYPESCRIPT_VERSION}` : dependency;
747
- });
704
+ return [dependency, range];
705
+ }),
706
+ );
748
707
 
749
- const dependencyVersions = (names: string[]): Record<string, string> => Object.fromEntries(
750
- names.map((dependency) => {
751
- if (dependency.startsWith("@gtkx/")) {
752
- return [dependency, `^${selfVersion}`];
753
- }
708
+ const dependencyArguments = (names: string[]): string[] =>
709
+ Object.entries(dependencyVersions(names)).map(([name, version]) => `${name}@${version}`);
754
710
 
755
- return [dependency, dependency === "typescript" ? TYPESCRIPT_VERSION : "latest"];
756
- }),
757
- );
711
+ const declaredDependencies = (value: unknown): Record<string, unknown> =>
712
+ typeof value === "object" && value !== null ? { ...value } : {};
758
713
 
759
714
  const writeDependencies = (root: string, devDependencies: string[]): void => {
760
715
  updateManifest(root, (manifest) => {
761
- manifest.dependencies = dependencyVersions(DEPENDENCIES);
762
- manifest.devDependencies = dependencyVersions(devDependencies);
716
+ manifest.dependencies = {
717
+ ...dependencyVersions(DEPENDENCIES),
718
+ ...declaredDependencies(manifest.dependencies),
719
+ };
720
+ manifest.devDependencies = {
721
+ ...dependencyVersions(devDependencies),
722
+ ...declaredDependencies(manifest.devDependencies),
723
+ };
763
724
  });
764
725
  };
765
726
 
766
- const formatRecovery = ({ resolved, devDependencies }: InstallFailureOptions): string => {
767
- const add = ADD_COMMAND[resolved.packageManager];
768
-
769
- const steps = [
770
- ...(resolved.isCurrentDirectory ? [] : [`cd ${resolved.target}`]),
771
- `${add} ${pin(DEPENDENCIES).join(" ")}`,
772
- `${add} -D ${pin(devDependencies).join(" ")}`,
773
- ];
727
+ const formatRecovery = (resolved: ResolvedOptions): string =>
728
+ `To finish setup, run ${INSTALL_COMMAND[resolved.packageManager]} in ${resolved.root}.`;
774
729
 
775
- const indented = steps.map((step) => ` ${step}`).join("\n");
730
+ const startProgress = (message: string): Progress => {
731
+ if (process.stdout.isTTY) {
732
+ const spinner = p.spinner();
733
+ spinner.start(message);
776
734
 
777
- return `${RECOVERY_HEADING}\n${indented}`;
778
- };
779
-
780
- const explainInstallFailure = (options: InstallFailureOptions): void => {
781
- const hint = getInstallHint(errorMessage(options.error));
782
-
783
- if (hint !== undefined) {
784
- p.log.warn(hint);
735
+ return spinner;
785
736
  }
786
737
 
787
- p.log.info(formatRecovery(options));
738
+ p.log.step(message);
739
+
740
+ return { stop: (done) => p.log.step(done), error: (failed) => p.log.error(failed) };
788
741
  };
789
742
 
790
743
  const runWithSpinner = async (step: SpinnerStep): Promise<void> => {
791
- const spinner = p.spinner();
792
- spinner.start(step.pending);
744
+ const progress = startProgress(step.pending);
793
745
 
794
746
  try {
795
747
  await step.run();
796
- spinner.stop(step.done);
748
+ progress.stop(step.done);
797
749
  } catch (error) {
798
- spinner.error(step.failed);
750
+ progress.error(step.failed);
799
751
  p.log.error(errorMessage(error));
800
- step.explain?.(error);
752
+ step.explain?.();
801
753
  throw new ScaffoldAbortedError(step.failed);
802
754
  }
803
755
  };
804
756
 
805
- const installAllDependencies = async (options: InstallAllOptions): Promise<void> => {
806
- const { resolved, devDependencies } = options;
757
+ const printWorkspaceAllowances = ({ root, packageManager, workspace }: ResolvedOptions): void => {
758
+ const installed = workspace === null ? null : enclosingWorkspace(root, packageManager);
759
+
760
+ if (installed === null || installed.missingSettings.length === 0) {
761
+ return;
762
+ }
763
+
764
+ p.log.warn(
765
+ `The ${installed.packageManager} workspace lacks settings this app needs. ` +
766
+ `Set these entries, then run ${INSTALL_COMMAND[installed.packageManager]}:\n\n` +
767
+ installed.missingSettings
768
+ .map(
769
+ ({ file, section, entries }) =>
770
+ `${section === null ? file : `${file} (under ${section})`}:\n${entries}`,
771
+ )
772
+ .join("\n\n"),
773
+ );
774
+ };
775
+
776
+ const hasMissingAllowances = (resolved: ResolvedOptions): boolean =>
777
+ resolved.workspace?.packageManager === "pnpm" && resolved.workspace.missingSettings.length > 0;
778
+
779
+ const installAllDependencies = async (resolved: ResolvedOptions, devDependencies: string[]): Promise<void> => {
807
780
  const { root, packageManager } = resolved;
781
+ const env = hasMissingAllowances(resolved) ? LENIENT_PNPM_BUILDS_ENV : {};
808
782
 
809
783
  await runWithSpinner({
810
784
  pending: "Installing dependencies...",
811
785
  done: "Dependencies installed",
812
786
  failed: "Failed to install dependencies",
813
787
  run: async () => {
814
- await installDependencies({ cwd: root, packageManager, dependencies: pin(DEPENDENCIES), isDev: false });
815
- await installDependencies({ cwd: root, packageManager, dependencies: pin(devDependencies), isDev: true });
788
+ try {
789
+ await withoutInheritedScriptPolicy(async () => {
790
+ const options = { cwd: root, packageManager, env, silent: true };
791
+ await addDependency(dependencyArguments(DEPENDENCIES), options);
792
+ await addDependency(dependencyArguments(devDependencies), { ...options, dev: true });
793
+ });
794
+ } catch (error) {
795
+ writeDependencies(root, devDependencies);
796
+ throw error;
797
+ }
816
798
  },
817
- explain: (error) => {
818
- explainInstallFailure({ error, resolved, devDependencies });
799
+ explain: () => {
800
+ printWorkspaceAllowances(resolved);
801
+ p.log.info(formatRecovery(resolved));
819
802
  },
820
803
  });
821
804
  };
822
805
 
823
- const writeInitialEnvModule = (root: string): void => {
824
- const path = envModulePath(root);
825
- mkdirSync(dirname(path), { recursive: true });
826
- writeFileSync(path, `${GTKX_ENV_MODULE_HEADER}\n`);
827
- };
828
-
829
806
  const isInsideGitRepository = (root: string): boolean => {
830
807
  const git = tryResolveExecutable("git");
831
808
 
@@ -847,44 +824,74 @@ const initializeGitRepo = async (root: string, shouldInitialize: boolean): Promi
847
824
  return;
848
825
  }
849
826
 
850
- const spinner = p.spinner();
851
- spinner.start("Initializing git repository...");
827
+ const progress = startProgress("Initializing git repository...");
852
828
 
853
829
  try {
854
830
  const opts = { nodeOptions: { cwd: root }, throwOnError: true } as const;
855
831
  await x("git", ["init"], opts);
856
832
  await x("git", ["add", "-A"], opts);
857
833
  await x("git", ["commit", "-m", "Initial commit"], opts);
858
- spinner.stop("Git repository initialized");
834
+ progress.stop("Git repository initialized");
859
835
  } catch {
860
- spinner.error("Failed to initialize git repository");
836
+ progress.error("Failed to initialize git repository");
837
+ }
838
+ };
839
+
840
+ const missingHeadlessToolsNote = (): string => {
841
+ const missing = Object.values(HEADLESS_DISPLAY_TOOLS).filter(
842
+ (tool) => tryResolveExecutable(tool.command) === undefined,
843
+ );
844
+
845
+ return missing.length === 0
846
+ ? ""
847
+ : ["", "", "To run tests, install these tools:", ...missingToolLines(missing)].join("\n");
848
+ };
849
+
850
+ const addRootMcpServer = ({ workspace, name, root }: ResolvedOptions): void => {
851
+ if (workspace === null) {
852
+ return;
853
+ }
854
+
855
+ const result = addWorkspaceMcpServer(workspace, name);
856
+
857
+ if (result.kind === "added") {
858
+ p.log.info(
859
+ `Added the MCP server "${result.key}" to ${result.path}, so an AI client opened at the workspace ` +
860
+ "root reaches this app.",
861
+ );
862
+ } else if (result.kind === "shared") {
863
+ p.log.info(
864
+ `The MCP server "${result.key}" in ${result.path} drives every running GTKX app, including this one, ` +
865
+ `so no server was added for it. To look up this app's bindings, pass projectRoot "${root}" to its ` +
866
+ "reference tools.",
867
+ );
868
+ } else if (result.kind === "unreadable") {
869
+ p.log.warn(
870
+ `Could not add this app's MCP server to ${result.path}: ${result.reason}. For an AI client opened ` +
871
+ `at the workspace root, add this entry under "mcpServers":\n\n` +
872
+ JSON.stringify({ [result.key]: result.server }, null, 4),
873
+ );
861
874
  }
862
875
  };
863
876
 
864
877
  const printNextSteps = (resolved: ResolvedOptions): void => {
865
878
  const devCmd = DEV_COMMAND[resolved.packageManager];
866
- const cdStep = resolved.isCurrentDirectory ? "" : `cd ${resolved.target}\n`;
867
879
  const installStep = resolved.shouldInstallDependencies ? "" : `${INSTALL_COMMAND[resolved.packageManager]}\n`;
868
- const testingNote = resolved.shouldIncludeTesting ? HEADLESS_COMPOSITOR_NOTE : "";
869
- p.note(`${cdStep}${installStep}${devCmd}${testingNote}`, "Next steps");
880
+ const testingNote = resolved.shouldIncludeTesting ? missingHeadlessToolsNote() : "";
881
+ p.note(`${installStep}${devCmd}${testingNote}`, `Run in ${resolved.root}`);
870
882
  };
871
883
 
872
- const createProjectStructure = async (
873
- root: string,
874
- resolved: ResolvedOptions,
875
- plan: ScaffoldPlan,
876
- ): Promise<void> => {
884
+ const createProjectStructure = async (root: string, resolved: ResolvedOptions, plan: ScaffoldPlan): Promise<void> => {
877
885
  await runWithSpinner({
878
886
  pending: "Creating project structure...",
879
887
  done: "Project structure created",
880
888
  failed: "Failed to create the project structure",
881
889
  run: () => {
882
890
  mkdirSync(root, { recursive: true });
883
- scaffoldProject(root, resolved, plan);
884
- writeBuildAllowance(root, resolved.packageManager);
891
+ scaffoldProject(root, plan);
885
892
 
886
- if (shouldWriteEnvModule(resolved)) {
887
- writeInitialEnvModule(root);
893
+ if (resolved.workspace === null) {
894
+ writePackageManagerSettings(root, resolved.packageManager);
888
895
  }
889
896
  },
890
897
  });
@@ -899,15 +906,16 @@ const scaffold = async (options: CreateOptions = {}): Promise<void> => {
899
906
  const plan = await planScaffoldProject(root, resolved);
900
907
  await validateTargetAvailability(root, resolved.target, options, plan.changes);
901
908
  await createProjectStructure(root, resolved, plan);
909
+ writeDependencies(root, devDeps);
902
910
  reportCompletedChanges(plan.changes);
911
+ addRootMcpServer(resolved);
903
912
 
904
913
  if (resolved.shouldInstallDependencies) {
905
- await installAllDependencies({ resolved, devDependencies: devDeps });
906
- } else {
907
- writeDependencies(root, devDeps);
914
+ await installAllDependencies(resolved, devDeps);
908
915
  }
909
916
 
910
917
  await initializeGitRepo(root, resolved.shouldInitializeGit);
918
+ printWorkspaceAllowances(resolved);
911
919
  printNextSteps(resolved);
912
920
  };
913
921