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
@@ -1,47 +1,49 @@
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 { PACKAGE_MANAGER_CONFIG_FILES, enclosingWorkspace, packageManagerPin, writePackageManagerSettings, } from "./build-allowance.js";
11
12
  import { OperationCanceledError, ScaffoldAbortedError } from "./errors.js";
12
- import { getInstallHint } from "./install-hints.js";
13
13
  import { updateManifest } from "./manifest.js";
14
14
  import { isKnownPackageManager, PACKAGE_MANAGER_VALUES, PACKAGE_MANAGERS, } from "./package-managers.js";
15
- import { isValidProjectName } from "./project-name.js";
15
+ import { isValidPackageName, packageNameFromDirectory, withoutAccents } from "./project-name.js";
16
16
  import { listTemplates, renderFile } from "./templates.js";
17
+ import { addWorkspaceMcpServer } from "./workspace-mcp.js";
17
18
  const selfVersion = packageManifest.version;
18
19
  const ICON_TEMPLATE_NAME = "icon.svg";
19
20
  const TYPESCRIPT_VERSION = "^6.0.3";
20
- const GTKX_ENV_MODULE_HEADER = `/**
21
- * Generated by \`gtkx codegen\`, \`gtkx dev\`, and \`gtkx build\`; do not edit.
22
- */`;
21
+ const DEPENDENCY_RANGES = {
22
+ ...JSON.parse(readFileSync(new URL("../dependency-ranges.json", import.meta.url), "utf8")),
23
+ typescript: TYPESCRIPT_VERSION,
24
+ };
23
25
  const DEPENDENCIES = ["@gtkx/cairo", "@gtkx/css", "@gtkx/runtime", "@gtkx/react", "react"];
24
- const DEV_DEPENDENCIES = ["@gtkx/cli", "@gtkx/config", "@gtkx/mcp", "vite"];
25
- const TYPESCRIPT_DEV_DEPENDENCIES = ["@types/node", "@types/react", "typescript"];
26
- const TESTING_DEV_DEPENDENCIES = ["@gtkx/testing", "vitest"];
26
+ const DEV_DEPENDENCIES = ["@gtkx/cli", "@gtkx/config", "@gtkx/mcp", "@gtkx/testing", "@types/react", "vite"];
27
+ const TYPESCRIPT_DEV_DEPENDENCIES = ["@types/node", "typescript"];
28
+ const TESTING_DEV_DEPENDENCIES = ["vitest"];
27
29
  const DEV_COMMAND = Object.fromEntries(PACKAGE_MANAGERS.map((manager) => [manager.value, manager.devCommand]));
28
- const ADD_COMMAND = Object.fromEntries(PACKAGE_MANAGERS.map((manager) => [manager.value, manager.addCommand]));
29
30
  const INSTALL_COMMAND = Object.fromEntries(PACKAGE_MANAGERS.map((manager) => [manager.value, manager.installCommand]));
31
+ const RUN_COMMAND = Object.fromEntries(PACKAGE_MANAGERS.map((manager) => [manager.value, manager.runCommand]));
32
+ const TEST_COMMAND = Object.fromEntries(PACKAGE_MANAGERS.map((manager) => [manager.value, manager.testCommand]));
30
33
  const INHERITED_SCRIPT_POLICY_VARS = ["npm_config_allow_scripts", "npm_config_allow-scripts"];
34
+ const LENIENT_PNPM_BUILDS_ENV = { pnpm_config_strict_dep_builds: "false" };
31
35
  const TESTING_TEMPLATES = new Set(["vitest.config.ts", "tests/app.test.tsx"]);
32
36
  const TYPESCRIPT_TEMPLATES = new Set(["tsconfig.json", "src/gtkx-env.d.ts"]);
33
- const HEADLESS_COMPOSITOR_NOTE = `
34
-
35
- To run tests, you need a headless Wayland compositor installed:
36
- Fedora: sudo dnf install sway
37
- Ubuntu: sudo apt install sway`;
38
- const RECOVERY_HEADING = "Finish the setup by adding the dependencies again, which is safe to repeat:";
39
37
  const APPLICATION_ID_FORMAT_ERROR = "Application ID must be reverse domain notation (e.g., com.example.myapp)";
38
+ const PACKAGE_NAME_FORMAT_ERROR = "Package name must be a valid npm package name: lowercase, no spaces (e.g., my-app)";
40
39
  const APPLICATION_ID_PREFIX = "com.";
41
40
  const APPLICATION_ID_SUFFIX = ".app";
42
- const APPLICATION_ID_SEGMENT_LIMIT = APPLICATION_ID_MAX_LENGTH - APPLICATION_ID_PREFIX.length -
43
- APPLICATION_ID_SUFFIX.length;
44
- const displayNameFromProjectName = (name) => name.split("-").map((part) => upperFirst(part)).join(" ");
41
+ const APPLICATION_ID_SEGMENT_LIMIT = APPLICATION_ID_MAX_LENGTH - APPLICATION_ID_PREFIX.length - APPLICATION_ID_SUFFIX.length;
42
+ const displayNameFromDirectory = (directoryName) => directoryName
43
+ .split(/[\s._-]+/)
44
+ .filter((part) => part.length > 0)
45
+ .map((part) => upperFirst(part))
46
+ .join(" ");
45
47
  const gitConfigValue = (key) => {
46
48
  const git = tryResolveExecutable("git");
47
49
  if (git === undefined) {
@@ -54,21 +56,16 @@ const gitConfigValue = (key) => {
54
56
  return null;
55
57
  }
56
58
  };
57
- const applicationIdSegment = (name) => {
58
- const compact = name.replaceAll("-", "");
59
+ const compactIdentifier = (name) => withoutAccents(name).replaceAll(/[^A-Za-z0-9_]/g, "");
60
+ const applicationIdSegment = (directoryName, name) => {
61
+ const compact = compactIdentifier(directoryName) || compactIdentifier(name);
59
62
  const segment = /^[A-Za-z_]/.test(compact) ? compact : `_${compact}`;
60
63
  return segment.slice(0, APPLICATION_ID_SEGMENT_LIMIT);
61
64
  };
62
- const suggestApplicationId = (name) => `${APPLICATION_ID_PREFIX}${applicationIdSegment(name)}${APPLICATION_ID_SUFFIX}`;
63
- const stripTrailingSlashes = (value) => {
64
- let end = value.length;
65
- while (end > 0 && value[end - 1] === "/") {
66
- end--;
67
- }
68
- return value.slice(0, end);
69
- };
70
- const formatTargetDir = (target) => stripTrailingSlashes(target.trim().replaceAll(/[<>:"\\|?*]/g, ""));
71
- const deriveProjectName = (target) => basename(resolve(process.cwd(), target));
65
+ const suggestApplicationId = (directoryName, name) => `${APPLICATION_ID_PREFIX}${applicationIdSegment(directoryName, name)}${APPLICATION_ID_SUFFIX}`;
66
+ const HOME_PREFIX = /^~(?=$|\/)/;
67
+ const expandHome = (target) => target.replace(HOME_PREFIX, () => homedir());
68
+ const directoryNameOf = (target) => basename(resolve(process.cwd(), target));
72
69
  const isDirEmpty = (dir) => {
73
70
  const entries = readdirSync(dir);
74
71
  return entries.length === 0 || (entries.length === 1 && entries[0] === ".git");
@@ -95,15 +92,9 @@ const guardCancellation = (value) => {
95
92
  }
96
93
  return value;
97
94
  };
98
- const validateProjectName = (value) => {
99
- if (!value) {
100
- return "Project name is required";
101
- }
102
- if (!isValidProjectName(value)) {
103
- return "Project name must be lowercase letters, numbers, and hyphens only";
104
- }
105
- return undefined;
106
- };
95
+ const validatePackageNameFormat = (value) => isValidPackageName(value) ? undefined : PACKAGE_NAME_FORMAT_ERROR;
96
+ const validatePackageNameInput = (value) => value ? validatePackageNameFormat(value) : "Package name is required";
97
+ const validatePackageNameAnswer = (value) => value ? validatePackageNameFormat(value) : undefined;
107
98
  const validateApplicationIdFormat = (value) => isValidApplicationId(value) ? undefined : APPLICATION_ID_FORMAT_ERROR;
108
99
  const validateApplicationIdInput = (value) => value ? validateApplicationIdFormat(value) : "Application ID is required";
109
100
  const validateApplicationIdAnswer = (value) => value ? validateApplicationIdFormat(value) : undefined;
@@ -127,20 +118,20 @@ const requestedPackageManager = (value) => {
127
118
  }
128
119
  return value;
129
120
  };
130
- const validateTargetDir = (target) => {
131
- if (!target) {
132
- return "Project directory is required";
133
- }
134
- return validateProjectName(deriveProjectName(target));
135
- };
136
- const validateTargetAnswer = (value) => validateTargetDir(formatTargetDir(value ?? ""));
137
- const promptTarget = async () => formatTargetDir(guardCancellation(await p.text({
121
+ const validateTargetDir = (target) => target ? undefined : "Project directory is required";
122
+ const validateTargetAnswer = (value) => validateTargetDir(expandHome(value ?? ""));
123
+ const promptTarget = async () => guardCancellation(await p.text({
138
124
  message: "Project directory",
139
125
  placeholder: "my-app",
140
126
  validate: validateTargetAnswer,
141
- })));
142
- const promptApplicationId = async (name) => {
143
- const defaultApplicationId = suggestApplicationId(name);
127
+ }));
128
+ const promptPackageName = async (derived) => guardCancellation(await p.text({
129
+ message: "Package name",
130
+ ...(derived === "" ? {} : { placeholder: derived, defaultValue: derived }),
131
+ validate: derived === "" ? validatePackageNameInput : validatePackageNameAnswer,
132
+ }));
133
+ const promptApplicationId = async (directoryName, name) => {
134
+ const defaultApplicationId = suggestApplicationId(directoryName, name);
144
135
  return guardCancellation(await p.text({
145
136
  message: "Application ID",
146
137
  placeholder: defaultApplicationId,
@@ -148,8 +139,8 @@ const promptApplicationId = async (name) => {
148
139
  validate: validateApplicationIdAnswer,
149
140
  }));
150
141
  };
151
- const promptDisplayName = async (name) => {
152
- const defaultDisplayName = displayNameFromProjectName(name);
142
+ const promptDisplayName = async (directoryName) => {
143
+ const defaultDisplayName = displayNameFromDirectory(directoryName);
153
144
  return guardCancellation(await p.text({
154
145
  message: "Display name",
155
146
  placeholder: defaultDisplayName,
@@ -185,10 +176,7 @@ const promptPackageManager = async () => {
185
176
  initialValue: initial,
186
177
  }));
187
178
  };
188
- const isOptionEnabled = async (value, isInteractive, message) => value ??
189
- (isInteractive
190
- ? guardCancellation(await p.confirm({ message, initialValue: true }))
191
- : true);
179
+ const isOptionEnabled = async (value, isInteractive, message) => value ?? (!isInteractive || guardCancellation(await p.confirm({ message, initialValue: true })));
192
180
  const formatFileList = (heading, files) => {
193
181
  const indentedFiles = files.map((file) => ` ${file}`).join("\n");
194
182
  return `${heading}:\n${indentedFiles}`;
@@ -231,14 +219,16 @@ const acceptNonEmptyDirectory = async (target, options, changes) => {
231
219
  refuseNonEmptyDirectory(target, changes);
232
220
  };
233
221
  const assertTargetIsDirectory = (root, target) => {
234
- const stats = statSync(root, { throwIfNoEntry: false });
222
+ const stats = lstatSync(root, { throwIfNoEntry: false });
223
+ if (stats?.isSymbolicLink()) {
224
+ fail(`Cannot scaffold through a symbolic link: ${root}`);
225
+ }
235
226
  if (stats !== undefined && !stats.isDirectory()) {
236
227
  fail(`Target "${target}" is not a directory`);
237
228
  }
238
229
  };
239
230
  const validateTargetAvailability = async (root, target, options, changes) => {
240
231
  const stats = statSync(root, { throwIfNoEntry: false });
241
- assertTargetIsDirectory(root, target);
242
232
  if (stats === undefined || isDirEmpty(root)) {
243
233
  return;
244
234
  }
@@ -246,21 +236,36 @@ const validateTargetAvailability = async (root, target, options, changes) => {
246
236
  };
247
237
  const resolveTarget = async (options) => {
248
238
  if (options.name === undefined && options.isInteractive) {
249
- return promptTarget();
239
+ return expandHome(await promptTarget());
250
240
  }
251
- const target = formatTargetDir(options.name ?? "");
241
+ const target = expandHome(options.name ?? "");
252
242
  const error = validateTargetDir(target);
253
243
  return error === undefined ? target : fail(error);
254
244
  };
255
- const resolveApplicationId = async (options, name) => {
245
+ const resolvePackageName = async (options, directoryName) => {
246
+ const derived = packageNameFromDirectory(directoryName);
247
+ if (derived === directoryName) {
248
+ return derived;
249
+ }
250
+ if (options.isInteractive) {
251
+ return promptPackageName(derived);
252
+ }
253
+ return derived === ""
254
+ ? fail(`Directory name "${directoryName}" has no Latin letters or numbers to derive a package name from. ` +
255
+ "Rename it, or run interactively to enter a package name")
256
+ : derived;
257
+ };
258
+ const resolveApplicationId = async (options, directoryName, name) => {
256
259
  const applicationId = options.applicationId ??
257
- (options.isInteractive ? await promptApplicationId(name) : suggestApplicationId(name));
260
+ (options.isInteractive
261
+ ? await promptApplicationId(directoryName, name)
262
+ : suggestApplicationId(directoryName, name));
258
263
  const error = validateApplicationIdInput(applicationId);
259
264
  return error === undefined ? applicationId : fail(error);
260
265
  };
261
- const resolveDisplayName = async (options, name) => {
266
+ const resolveDisplayName = async (options, directoryName) => {
262
267
  const value = options.displayName ??
263
- (options.isInteractive ? await promptDisplayName(name) : displayNameFromProjectName(name));
268
+ (options.isInteractive ? await promptDisplayName(directoryName) : displayNameFromDirectory(directoryName));
264
269
  const error = validateDisplayName(value);
265
270
  return error === undefined ? value.trim() : fail(error);
266
271
  };
@@ -276,11 +281,11 @@ const resolvePackageManager = async (requested, options) => {
276
281
  const resolveOptions = async (options) => {
277
282
  const requested = requestedPackageManager(options.packageManager);
278
283
  const target = await resolveTarget(options);
279
- const name = deriveProjectName(target);
280
- const displayName = await resolveDisplayName(options, name);
281
- const applicationId = await resolveApplicationId(options, name);
284
+ const directoryName = directoryNameOf(target);
285
+ const name = await resolvePackageName(options, directoryName);
286
+ const displayName = await resolveDisplayName(options, directoryName);
287
+ const applicationId = await resolveApplicationId(options, directoryName, name);
282
288
  const root = resolve(process.cwd(), target);
283
- const isCurrentDirectory = root === process.cwd();
284
289
  const shouldInitialize = shouldInitializeGit(root);
285
290
  const packageManager = await resolvePackageManager(requested, options);
286
291
  const isTypescript = await isOptionEnabled(options.isTypescript, options.isInteractive, "Use TypeScript?");
@@ -288,11 +293,11 @@ const resolveOptions = async (options) => {
288
293
  return {
289
294
  target,
290
295
  root,
291
- isCurrentDirectory,
292
296
  name,
293
297
  displayName,
294
298
  applicationId,
295
299
  packageManager,
300
+ workspace: enclosingWorkspace(root, packageManager),
296
301
  isTypescript,
297
302
  shouldIncludeTesting,
298
303
  shouldInitializeGit: shouldInitialize,
@@ -314,6 +319,10 @@ const destinationPath = (template, resolved) => {
314
319
  ? `${scriptPath.slice(0, -ICON_TEMPLATE_NAME.length)}${resolved.applicationId}.svg`
315
320
  : scriptPath;
316
321
  };
322
+ const scriptCommands = ({ packageManager, isTypescript, shouldIncludeTesting, }) => [
323
+ ...["dev", "build", "codegen", ...(isTypescript ? ["typecheck"] : [])].map((script) => `${RUN_COMMAND[packageManager]} ${script}`),
324
+ ...(shouldIncludeTesting ? [TEST_COMMAND[packageManager]] : []),
325
+ ];
317
326
  const templateContext = (resolved) => ({
318
327
  name: resolved.name,
319
328
  applicationId: resolved.applicationId,
@@ -323,32 +332,9 @@ const templateContext = (resolved) => ({
323
332
  importExtension: resolved.isTypescript ? ".js" : ".jsx",
324
333
  developerName: gitConfigValue("user.name") ?? resolved.displayName,
325
334
  developerEmail: gitConfigValue("user.email"),
335
+ packageManager: resolved.packageManager,
336
+ scriptCommands: scriptCommands(resolved),
326
337
  });
327
- const replaceTemplateDestination = (destination) => {
328
- const entry = lstatSync(destination, { throwIfNoEntry: false });
329
- if (entry === undefined) {
330
- return;
331
- }
332
- if (!entry.isFile() && !entry.isSymbolicLink()) {
333
- fail(`Cannot replace scaffold file because its destination is not a file: ${destination}`);
334
- }
335
- rmSync(destination, { force: true });
336
- };
337
- const projectRelativeDestination = (root, destination) => {
338
- const relativePath = relative(root, destination);
339
- const isOutsideProject = relativePath.length === 0 || relativePath.startsWith(`..${sep}`) ||
340
- isAbsolute(relativePath);
341
- if (isOutsideProject) {
342
- fail(`Scaffold destination is outside the project: ${destination}`);
343
- }
344
- return relativePath;
345
- };
346
- const assertRootIsNotSymbolicLink = (root) => {
347
- const rootEntry = lstatSync(root, { throwIfNoEntry: false });
348
- if (rootEntry?.isSymbolicLink()) {
349
- fail(`Cannot scaffold through a symbolic link: ${root}`);
350
- }
351
- };
352
338
  const assertSafeAncestor = (ancestor) => {
353
339
  const entry = lstatSync(ancestor, { throwIfNoEntry: false });
354
340
  if (entry?.isSymbolicLink()) {
@@ -367,18 +353,17 @@ const assertSafeAncestors = (root, relativePath) => {
367
353
  assertSafeAncestor(ancestor);
368
354
  }
369
355
  };
370
- const assertReplaceableDestination = (destination) => {
356
+ const hasReplaceableDestination = (destination) => {
371
357
  const entry = lstatSync(destination, { throwIfNoEntry: false });
372
358
  const isReplaceable = entry === undefined || entry.isFile() || entry.isSymbolicLink();
373
359
  if (!isReplaceable) {
374
360
  fail(`Cannot replace scaffold file because its destination is not a file: ${destination}`);
375
361
  }
362
+ return entry !== undefined;
376
363
  };
377
- const assertSafeDestination = (root, destination) => {
378
- const relativePath = projectRelativeDestination(root, destination);
379
- assertRootIsNotSymbolicLink(root);
380
- assertSafeAncestors(root, relativePath);
381
- assertReplaceableDestination(destination);
364
+ const hasExistingDestination = (root, destination) => {
365
+ assertSafeAncestors(root, relative(root, destination));
366
+ return hasReplaceableDestination(destination);
382
367
  };
383
368
  const plannedScaffoldFiles = async (root, resolved) => {
384
369
  const context = templateContext(resolved);
@@ -393,53 +378,36 @@ const plannedScaffoldFiles = async (root, resolved) => {
393
378
  }
394
379
  return files;
395
380
  };
396
- const auxiliaryDestinations = (root, resolved) => resolved.packageManager === "pnpm" ? [join(root, "pnpm-workspace.yaml")] : [];
397
- const envModulePath = (root) => join(root, "node_modules", ".gtkx", "env.d.ts");
398
- const shouldWriteEnvModule = (resolved) => resolved.isTypescript && resolved.shouldInstallDependencies;
399
- const generatedDestinations = (root, resolved) => shouldWriteEnvModule(resolved) ? [envModulePath(root)] : [];
400
- const isPresent = (path) => lstatSync(path, { throwIfNoEntry: false }) !== undefined;
401
- const classifyScaffoldChange = (root, destination) => {
402
- const entry = lstatSync(destination, { throwIfNoEntry: false });
403
- if (entry === undefined) {
404
- return undefined;
405
- }
406
- return { destination, relativePath: projectRelativeDestination(root, destination) };
407
- };
408
- const addScaffoldChange = (plan, change) => {
409
- if (change === undefined) {
410
- return;
411
- }
412
- plan.replaceDestinations.push(change.destination);
413
- plan.changes.push(change.relativePath);
414
- };
381
+ const configDestinations = (root, resolved) => resolved.workspace === null
382
+ ? PACKAGE_MANAGER_CONFIG_FILES[resolved.packageManager].map((file) => join(root, file))
383
+ : [];
415
384
  const planScaffoldProject = async (root, resolved) => {
416
385
  const files = await plannedScaffoldFiles(root, resolved);
417
- const reported = [...files.map((file) => file.destination), ...auxiliaryDestinations(root, resolved)];
418
- const generated = generatedDestinations(root, resolved);
419
- for (const destination of [...reported, ...generated]) {
420
- assertSafeDestination(root, destination);
386
+ for (const destination of configDestinations(root, resolved)) {
387
+ hasExistingDestination(root, destination);
421
388
  }
422
- const plan = {
389
+ const replaceDestinations = files
390
+ .map((file) => file.destination)
391
+ .filter((destination) => hasExistingDestination(root, destination));
392
+ return {
423
393
  files,
424
- replaceDestinations: generated.filter((destination) => isPresent(destination)),
425
- changes: [],
394
+ replaceDestinations,
395
+ changes: replaceDestinations.map((destination) => relative(root, destination)),
396
+ packageManagerPin: packageManagerPin(root, resolved.packageManager, resolved.workspace !== null),
426
397
  };
427
- for (const destination of reported) {
428
- addScaffoldChange(plan, classifyScaffoldChange(root, destination));
429
- }
430
- return plan;
431
398
  };
432
- const scaffoldProject = (root, resolved, plan) => {
399
+ const scaffoldProject = (root, plan) => {
433
400
  for (const destination of plan.replaceDestinations) {
434
- replaceTemplateDestination(destination);
401
+ rmSync(destination);
435
402
  }
436
403
  for (const file of plan.files) {
437
404
  mkdirSync(dirname(file.destination), { recursive: true });
438
405
  writeFileSync(file.destination, file.contents);
439
406
  }
440
- if (resolved.shouldIncludeTesting) {
407
+ const pin = plan.packageManagerPin;
408
+ if (pin !== null) {
441
409
  updateManifest(root, (manifest) => {
442
- manifest.scripts.test = "vitest run";
410
+ manifest.packageManager = pin;
443
411
  });
444
412
  }
445
413
  };
@@ -459,82 +427,91 @@ const withoutInheritedScriptPolicy = async (run) => {
459
427
  }
460
428
  }
461
429
  };
462
- const installDependencies = async (options) => {
463
- const { cwd, packageManager, dependencies, isDev } = options;
464
- await withoutInheritedScriptPolicy(async () => {
465
- await addDependency(dependencies, { cwd, packageManager, dev: isDev, silent: true });
466
- });
467
- };
468
- const pin = (names) => names.map((dependency) => {
469
- if (dependency.startsWith("@gtkx/")) {
470
- return `${dependency}@^${selfVersion}`;
471
- }
472
- return dependency === "typescript" ? `${dependency}@${TYPESCRIPT_VERSION}` : dependency;
473
- });
474
430
  const dependencyVersions = (names) => Object.fromEntries(names.map((dependency) => {
475
431
  if (dependency.startsWith("@gtkx/")) {
476
432
  return [dependency, `^${selfVersion}`];
477
433
  }
478
- return [dependency, dependency === "typescript" ? TYPESCRIPT_VERSION : "latest"];
434
+ const range = DEPENDENCY_RANGES[dependency];
435
+ if (range === undefined) {
436
+ throw new Error(`No supported version range for ${dependency}`);
437
+ }
438
+ return [dependency, range];
479
439
  }));
440
+ const dependencyArguments = (names) => Object.entries(dependencyVersions(names)).map(([name, version]) => `${name}@${version}`);
441
+ const declaredDependencies = (value) => typeof value === "object" && value !== null ? { ...value } : {};
480
442
  const writeDependencies = (root, devDependencies) => {
481
443
  updateManifest(root, (manifest) => {
482
- manifest.dependencies = dependencyVersions(DEPENDENCIES);
483
- manifest.devDependencies = dependencyVersions(devDependencies);
444
+ manifest.dependencies = {
445
+ ...dependencyVersions(DEPENDENCIES),
446
+ ...declaredDependencies(manifest.dependencies),
447
+ };
448
+ manifest.devDependencies = {
449
+ ...dependencyVersions(devDependencies),
450
+ ...declaredDependencies(manifest.devDependencies),
451
+ };
484
452
  });
485
453
  };
486
- const formatRecovery = ({ resolved, devDependencies }) => {
487
- const add = ADD_COMMAND[resolved.packageManager];
488
- const steps = [
489
- ...(resolved.isCurrentDirectory ? [] : [`cd ${resolved.target}`]),
490
- `${add} ${pin(DEPENDENCIES).join(" ")}`,
491
- `${add} -D ${pin(devDependencies).join(" ")}`,
492
- ];
493
- const indented = steps.map((step) => ` ${step}`).join("\n");
494
- return `${RECOVERY_HEADING}\n${indented}`;
495
- };
496
- const explainInstallFailure = (options) => {
497
- const hint = getInstallHint(errorMessage(options.error));
498
- if (hint !== undefined) {
499
- p.log.warn(hint);
454
+ const formatRecovery = (resolved) => `To finish setup, run ${INSTALL_COMMAND[resolved.packageManager]} in ${resolved.root}.`;
455
+ const startProgress = (message) => {
456
+ if (process.stdout.isTTY) {
457
+ const spinner = p.spinner();
458
+ spinner.start(message);
459
+ return spinner;
500
460
  }
501
- p.log.info(formatRecovery(options));
461
+ p.log.step(message);
462
+ return { stop: (done) => p.log.step(done), error: (failed) => p.log.error(failed) };
502
463
  };
503
464
  const runWithSpinner = async (step) => {
504
- const spinner = p.spinner();
505
- spinner.start(step.pending);
465
+ const progress = startProgress(step.pending);
506
466
  try {
507
467
  await step.run();
508
- spinner.stop(step.done);
468
+ progress.stop(step.done);
509
469
  }
510
470
  catch (error) {
511
- spinner.error(step.failed);
471
+ progress.error(step.failed);
512
472
  p.log.error(errorMessage(error));
513
- step.explain?.(error);
473
+ step.explain?.();
514
474
  throw new ScaffoldAbortedError(step.failed);
515
475
  }
516
476
  };
517
- const installAllDependencies = async (options) => {
518
- const { resolved, devDependencies } = options;
477
+ const printWorkspaceAllowances = ({ root, packageManager, workspace }) => {
478
+ const installed = workspace === null ? null : enclosingWorkspace(root, packageManager);
479
+ if (installed === null || installed.missingSettings.length === 0) {
480
+ return;
481
+ }
482
+ p.log.warn(`The ${installed.packageManager} workspace lacks settings this app needs. ` +
483
+ `Set these entries, then run ${INSTALL_COMMAND[installed.packageManager]}:\n\n` +
484
+ installed.missingSettings
485
+ .map(({ file, section, entries }) => `${section === null ? file : `${file} (under ${section})`}:\n${entries}`)
486
+ .join("\n\n"));
487
+ };
488
+ const hasMissingAllowances = (resolved) => resolved.workspace?.packageManager === "pnpm" && resolved.workspace.missingSettings.length > 0;
489
+ const installAllDependencies = async (resolved, devDependencies) => {
519
490
  const { root, packageManager } = resolved;
491
+ const env = hasMissingAllowances(resolved) ? LENIENT_PNPM_BUILDS_ENV : {};
520
492
  await runWithSpinner({
521
493
  pending: "Installing dependencies...",
522
494
  done: "Dependencies installed",
523
495
  failed: "Failed to install dependencies",
524
496
  run: async () => {
525
- await installDependencies({ cwd: root, packageManager, dependencies: pin(DEPENDENCIES), isDev: false });
526
- await installDependencies({ cwd: root, packageManager, dependencies: pin(devDependencies), isDev: true });
497
+ try {
498
+ await withoutInheritedScriptPolicy(async () => {
499
+ const options = { cwd: root, packageManager, env, silent: true };
500
+ await addDependency(dependencyArguments(DEPENDENCIES), options);
501
+ await addDependency(dependencyArguments(devDependencies), { ...options, dev: true });
502
+ });
503
+ }
504
+ catch (error) {
505
+ writeDependencies(root, devDependencies);
506
+ throw error;
507
+ }
527
508
  },
528
- explain: (error) => {
529
- explainInstallFailure({ error, resolved, devDependencies });
509
+ explain: () => {
510
+ printWorkspaceAllowances(resolved);
511
+ p.log.info(formatRecovery(resolved));
530
512
  },
531
513
  });
532
514
  };
533
- const writeInitialEnvModule = (root) => {
534
- const path = envModulePath(root);
535
- mkdirSync(dirname(path), { recursive: true });
536
- writeFileSync(path, `${GTKX_ENV_MODULE_HEADER}\n`);
537
- };
538
515
  const isInsideGitRepository = (root) => {
539
516
  const git = tryResolveExecutable("git");
540
517
  if (git === undefined) {
@@ -552,25 +529,49 @@ const initializeGitRepo = async (root, shouldInitialize) => {
552
529
  if (!shouldInitialize || isInsideGitRepository(root)) {
553
530
  return;
554
531
  }
555
- const spinner = p.spinner();
556
- spinner.start("Initializing git repository...");
532
+ const progress = startProgress("Initializing git repository...");
557
533
  try {
558
534
  const opts = { nodeOptions: { cwd: root }, throwOnError: true };
559
535
  await x("git", ["init"], opts);
560
536
  await x("git", ["add", "-A"], opts);
561
537
  await x("git", ["commit", "-m", "Initial commit"], opts);
562
- spinner.stop("Git repository initialized");
538
+ progress.stop("Git repository initialized");
563
539
  }
564
540
  catch {
565
- spinner.error("Failed to initialize git repository");
541
+ progress.error("Failed to initialize git repository");
542
+ }
543
+ };
544
+ const missingHeadlessToolsNote = () => {
545
+ const missing = Object.values(HEADLESS_DISPLAY_TOOLS).filter((tool) => tryResolveExecutable(tool.command) === undefined);
546
+ return missing.length === 0
547
+ ? ""
548
+ : ["", "", "To run tests, install these tools:", ...missingToolLines(missing)].join("\n");
549
+ };
550
+ const addRootMcpServer = ({ workspace, name, root }) => {
551
+ if (workspace === null) {
552
+ return;
553
+ }
554
+ const result = addWorkspaceMcpServer(workspace, name);
555
+ if (result.kind === "added") {
556
+ p.log.info(`Added the MCP server "${result.key}" to ${result.path}, so an AI client opened at the workspace ` +
557
+ "root reaches this app.");
558
+ }
559
+ else if (result.kind === "shared") {
560
+ p.log.info(`The MCP server "${result.key}" in ${result.path} drives every running GTKX app, including this one, ` +
561
+ `so no server was added for it. To look up this app's bindings, pass projectRoot "${root}" to its ` +
562
+ "reference tools.");
563
+ }
564
+ else if (result.kind === "unreadable") {
565
+ p.log.warn(`Could not add this app's MCP server to ${result.path}: ${result.reason}. For an AI client opened ` +
566
+ `at the workspace root, add this entry under "mcpServers":\n\n` +
567
+ JSON.stringify({ [result.key]: result.server }, null, 4));
566
568
  }
567
569
  };
568
570
  const printNextSteps = (resolved) => {
569
571
  const devCmd = DEV_COMMAND[resolved.packageManager];
570
- const cdStep = resolved.isCurrentDirectory ? "" : `cd ${resolved.target}\n`;
571
572
  const installStep = resolved.shouldInstallDependencies ? "" : `${INSTALL_COMMAND[resolved.packageManager]}\n`;
572
- const testingNote = resolved.shouldIncludeTesting ? HEADLESS_COMPOSITOR_NOTE : "";
573
- p.note(`${cdStep}${installStep}${devCmd}${testingNote}`, "Next steps");
573
+ const testingNote = resolved.shouldIncludeTesting ? missingHeadlessToolsNote() : "";
574
+ p.note(`${installStep}${devCmd}${testingNote}`, `Run in ${resolved.root}`);
574
575
  };
575
576
  const createProjectStructure = async (root, resolved, plan) => {
576
577
  await runWithSpinner({
@@ -579,10 +580,9 @@ const createProjectStructure = async (root, resolved, plan) => {
579
580
  failed: "Failed to create the project structure",
580
581
  run: () => {
581
582
  mkdirSync(root, { recursive: true });
582
- scaffoldProject(root, resolved, plan);
583
- writeBuildAllowance(root, resolved.packageManager);
584
- if (shouldWriteEnvModule(resolved)) {
585
- writeInitialEnvModule(root);
583
+ scaffoldProject(root, plan);
584
+ if (resolved.workspace === null) {
585
+ writePackageManagerSettings(root, resolved.packageManager);
586
586
  }
587
587
  },
588
588
  });
@@ -596,14 +596,14 @@ const scaffold = async (options = {}) => {
596
596
  const plan = await planScaffoldProject(root, resolved);
597
597
  await validateTargetAvailability(root, resolved.target, options, plan.changes);
598
598
  await createProjectStructure(root, resolved, plan);
599
+ writeDependencies(root, devDeps);
599
600
  reportCompletedChanges(plan.changes);
601
+ addRootMcpServer(resolved);
600
602
  if (resolved.shouldInstallDependencies) {
601
- await installAllDependencies({ resolved, devDependencies: devDeps });
602
- }
603
- else {
604
- writeDependencies(root, devDeps);
603
+ await installAllDependencies(resolved, devDeps);
605
604
  }
606
605
  await initializeGitRepo(root, resolved.shouldInitializeGit);
606
+ printWorkspaceAllowances(resolved);
607
607
  printNextSteps(resolved);
608
608
  };
609
609
  export { scaffold };