@venizia/vulcan 0.4.9-0 → 0.4.9-2

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 (141) hide show
  1. package/base/extensions/vulcan-guards.ts +48 -41
  2. package/base/hooks/antigravity-guards.ts +2 -2
  3. package/base/hooks/codex-guards.ts +15 -5
  4. package/base/hooks/guard-git.ts +8 -8
  5. package/base/hooks/guard-manifest.ts +4 -5
  6. package/base/hooks/guard-outside.ts +8 -8
  7. package/base/hooks/guard-package.ts +5 -6
  8. package/base/hooks/guard-remote-hosts.ts +6 -7
  9. package/base/hooks/guard-scripting.ts +5 -6
  10. package/base/hooks/guard-writes.ts +8 -9
  11. package/base/hooks/post-tool.ts +2 -2
  12. package/base/hooks/prompt-submit.ts +2 -2
  13. package/base/hooks/session-start.ts +3 -3
  14. package/base/hooks/stop.ts +2 -2
  15. package/base/hooks/subagent-start.ts +2 -2
  16. package/base/skills/docs-update/SKILL.md +4 -2
  17. package/base/skills/visualize-work/SKILL.md +9 -0
  18. package/package.json +3 -3
  19. package/src/agents/atlas-block.ts +43 -43
  20. package/src/agents/codex-hooks.ts +45 -43
  21. package/src/agents/detect.ts +19 -16
  22. package/src/agents/exclude.ts +96 -97
  23. package/src/agents/hooks-json.ts +38 -36
  24. package/src/agents/local.ts +46 -43
  25. package/src/agents/prompt.ts +45 -42
  26. package/src/agents/render.ts +201 -195
  27. package/src/agents/resolve.ts +133 -134
  28. package/src/agents/table.ts +12 -8
  29. package/src/commands/add.command.ts +2 -2
  30. package/src/commands/agents.command.ts +11 -17
  31. package/src/commands/clean.command.ts +6 -6
  32. package/src/commands/doctor.command.ts +4 -4
  33. package/src/commands/init.command.ts +12 -8
  34. package/src/commands/preset.command.ts +2 -2
  35. package/src/commands/profile.command.ts +42 -49
  36. package/src/commands/sync.command.ts +109 -111
  37. package/src/commands/upgrade.command.ts +80 -75
  38. package/src/commands/visualize.command.ts +7 -13
  39. package/src/commands/x.command.ts +55 -50
  40. package/src/common/format.ts +23 -21
  41. package/src/common/json.ts +8 -5
  42. package/src/common/layout-folder.ts +94 -91
  43. package/src/common/paths.ts +14 -12
  44. package/src/config/loader.ts +52 -49
  45. package/src/config/packages.ts +14 -11
  46. package/src/config/schema.ts +3 -3
  47. package/src/create/add-app.ts +519 -509
  48. package/src/create/add-lib.ts +237 -240
  49. package/src/create/bunfig.ts +26 -23
  50. package/src/create/checks.ts +36 -34
  51. package/src/create/diff.ts +21 -23
  52. package/src/create/dockerignore.ts +26 -24
  53. package/src/create/files.ts +7 -5
  54. package/src/create/init-monorepo.ts +75 -80
  55. package/src/create/lib-preset.ts +59 -63
  56. package/src/create/manifest-json.ts +10 -4
  57. package/src/create/names.ts +217 -210
  58. package/src/create/next.ts +26 -23
  59. package/src/create/plan.ts +15 -12
  60. package/src/create/preset-diff.ts +301 -303
  61. package/src/create/preset-menu.ts +38 -32
  62. package/src/create/preset.ts +202 -197
  63. package/src/create/process.ts +79 -72
  64. package/src/create/scratch.ts +48 -49
  65. package/src/create/workspace.ts +404 -396
  66. package/src/doctor/checks.ts +1027 -1014
  67. package/src/doctor/makefile.ts +17 -13
  68. package/src/doctor/runner.ts +88 -118
  69. package/src/doctor/skills.ts +97 -95
  70. package/src/doctor/tags.ts +42 -37
  71. package/src/hooks/codex-patch.ts +25 -22
  72. package/src/hooks/command-view.ts +44 -39
  73. package/src/hooks/decision.ts +37 -37
  74. package/src/hooks/guard-git.ts +51 -49
  75. package/src/hooks/guard-manifest.ts +58 -55
  76. package/src/hooks/guard-outside.ts +93 -91
  77. package/src/hooks/guard-package.ts +82 -79
  78. package/src/hooks/guard-scripting.ts +19 -14
  79. package/src/hooks/guard-writes.ts +154 -149
  80. package/src/hooks/owner-reply.ts +127 -127
  81. package/src/hooks/post-tool.ts +94 -93
  82. package/src/hooks/project-guards.ts +65 -62
  83. package/src/hooks/project-tmp.ts +27 -24
  84. package/src/hooks/remote-hosts.ts +153 -130
  85. package/src/hooks/session-digest.ts +98 -101
  86. package/src/hooks/shell.ts +509 -499
  87. package/src/hooks/subagent-card.ts +11 -7
  88. package/src/hooks/trusted-scripts.ts +106 -104
  89. package/src/init/scaffold.ts +135 -132
  90. package/src/local/clean.ts +38 -36
  91. package/src/local/format.ts +21 -17
  92. package/src/local/scan.ts +144 -138
  93. package/src/manifest/render.ts +110 -104
  94. package/src/owner/card.ts +51 -46
  95. package/src/owner/profile.ts +99 -93
  96. package/src/owner/reply-switch.ts +9 -6
  97. package/src/owner/shape.ts +71 -69
  98. package/src/owner/survey.ts +173 -171
  99. package/src/owner/view.ts +62 -59
  100. package/src/owner/violations.ts +119 -123
  101. package/src/rules/base.ts +15 -11
  102. package/src/rules/parser.ts +39 -32
  103. package/src/rules/slots.ts +8 -6
  104. package/src/signals/claims.ts +30 -28
  105. package/src/signals/classify.ts +38 -33
  106. package/src/signals/loop.ts +39 -37
  107. package/src/signals/state.ts +79 -81
  108. package/src/skills/frontmatter.ts +28 -28
  109. package/src/sync/agent-files.ts +217 -199
  110. package/src/sync/agent-removal.ts +56 -59
  111. package/src/sync/atlas-block.ts +45 -43
  112. package/src/sync/base-rules.ts +32 -30
  113. package/src/sync/claude-launch.ts +36 -34
  114. package/src/sync/exclude.ts +77 -69
  115. package/src/sync/local-choice.ts +50 -47
  116. package/src/sync/planner.ts +59 -61
  117. package/src/sync/prune.ts +52 -48
  118. package/src/sync/settings.ts +166 -167
  119. package/src/ui/capability.ts +12 -7
  120. package/src/ui/keyboard.ts +38 -38
  121. package/src/ui/prompt.ts +79 -77
  122. package/src/visualize/assets.ts +33 -24
  123. package/src/visualize/charts.ts +179 -176
  124. package/src/visualize/compare-css.ts +3 -2
  125. package/src/visualize/compare-render.ts +9 -7
  126. package/src/visualize/diagrams.ts +189 -174
  127. package/src/visualize/grid-span.ts +34 -0
  128. package/src/visualize/icons.ts +7 -5
  129. package/src/visualize/kinds-render.ts +50 -45
  130. package/src/visualize/kinds-validate.ts +12 -10
  131. package/src/visualize/labels.ts +21 -17
  132. package/src/visualize/layout.ts +112 -97
  133. package/src/visualize/page.ts +92 -104
  134. package/src/visualize/render.ts +143 -140
  135. package/src/visualize/sections.ts +395 -384
  136. package/src/visualize/sources.ts +2 -2
  137. package/src/visualize/theme.ts +12 -10
  138. package/src/visualize/validate.ts +13 -9
  139. package/src/wiki/anchors.ts +38 -36
  140. package/src/wiki/command.ts +4 -4
  141. package/src/wiki/source-links.ts +46 -44
@@ -1,59 +1,34 @@
1
1
  import { existsSync, readFileSync } from 'node:fs';
2
2
  import { join, relative } from 'node:path';
3
3
  import { ExitCodes } from '../common/index.ts';
4
- import {
5
- describeFolders,
6
- LayoutKeys,
7
- layoutFoldersOf,
8
- layoutOverlapProblems,
9
- listedFoldersNote,
10
- withLayoutFolder,
11
- } from '../common/layout-folder.ts';
4
+ import { LayoutFolder, LayoutKeys } from '../common/layout-folder.ts';
12
5
  import type { ILayout } from '../common/layout-folder.ts';
13
6
  import { OFFICIAL_PRESETS, OfficialPresets } from '@venizia/vulcan-atlas';
14
7
  import type { IOfficialPreset } from '@venizia/vulcan-atlas';
15
- import { LibraryKinds, loadConfig, PackageKinds, resolvePackages } from '../config/index.ts';
8
+ import { ConfigLoader, LibraryKinds, PackageKinds, ProjectPackages } from '../config/index.ts';
16
9
  import type { IProjectPackage, TLibraryKind, TResolvedConfig } from '../config/index.ts';
17
- import { readWorkspaceGlobs } from '../init/index.ts';
18
- import { addLibrary } from './add-lib.ts';
19
- import { runAppChecks } from './checks.ts';
10
+ import { ProjectScaffold } from '../init/index.ts';
11
+ import { LibraryScaffold } from './add-lib.ts';
12
+ import { AppChecks } from './checks.ts';
20
13
  import { AddFailure, AppSides, AppsBlockProblems, CreateFlags } from './common/index.ts';
21
14
  import type { IAppsBlock, ILocatedPreset, IPresetSpec, TAppSide } from './common/index.ts';
22
- import { writeFile } from './files.ts';
23
- import { recordedPresetOf } from './lib-preset.ts';
24
- import { renderManifestJson } from './manifest-json.ts';
25
- import { menusAvailable, promptSelect } from '../ui/index.ts';
26
- import { askPresetSpec } from './preset-menu.ts';
27
- import { ABORTED, confirmWrite, planLines } from './plan.ts';
28
- import {
29
- askInTerminal,
30
- askScope,
31
- askWithPrompt,
32
- nameProblem,
33
- readFlag,
34
- readScope,
35
- resolveNames,
36
- SIDE_FIELDS,
37
- } from './names.ts';
38
- import { readExistingApps, renderNext } from './next.ts';
39
- import { copyPresetFiles, locatePreset, parsePresetSpec } from './preset.ts';
40
- import { isInstallSkipped, runBun } from './process.ts';
41
- import { installNpmPreset, withScratch } from './scratch.ts';
15
+ import { ProjectFile } from './files.ts';
16
+ import { LibPreset } from './lib-preset.ts';
17
+ import { ManifestJson } from './manifest-json.ts';
18
+ import { TerminalCapability, TerminalPrompt } from '../ui/index.ts';
19
+ import { PresetMenu } from './preset-menu.ts';
20
+ import { ABORTED, WritePlan } from './plan.ts';
21
+ import { askInTerminal, ProjectNames, SIDE_FIELDS } from './names.ts';
22
+ import { NextStep } from './next.ts';
23
+ import { Preset } from './preset.ts';
24
+ import { SubProcess } from './process.ts';
25
+ import { PresetScratch } from './scratch.ts';
42
26
  import {
43
- addAppBullet,
44
- checkPeers,
45
- filePresetWarning,
46
- parseAppsBlock,
47
- pickPort,
48
- planRootManifest,
49
- presetSpecOf,
50
- readCatalog,
51
- readPort,
52
- recordPreset,
53
- renderAppConcept,
54
- renderAppManifest,
55
- renderKnowledgeIndex,
56
- replaceAppsBlock,
27
+ AppsBlock,
28
+ PortRegistry,
29
+ PresetRecord,
30
+ WorkspaceDocs,
31
+ WorkspaceManifest,
57
32
  } from './workspace.ts';
58
33
 
59
34
  type TRootManifest = Record<string, unknown>;
@@ -87,7 +62,7 @@ const sideNamedBy = (opts: { args: string[] }): TAppSide | undefined => {
87
62
  const missingFlag = (opts: { args: string[]; layout: ILayout }): string | undefined => {
88
63
  const side = sideNamedBy({ args: opts.args });
89
64
 
90
- if (readFlag({ args: opts.args, flag: CreateFlags.APP }) === undefined) {
65
+ if (ProjectNames.readFlag({ args: opts.args, flag: CreateFlags.APP }) === undefined) {
91
66
  const kind = side === undefined ? '' : `${side} `;
92
67
 
93
68
  return `missing ${CreateFlags.APP} (Name of this ${kind}app) - names are never chosen for you`;
@@ -99,11 +74,14 @@ const missingFlag = (opts: { args: string[]; layout: ILayout }): string | undefi
99
74
 
100
75
  const folder = SIDE_FIELDS[side];
101
76
 
102
- const listed = layoutFoldersOf({ value: opts.layout[side] });
77
+ const listed = LayoutFolder.layoutFoldersOf({ value: opts.layout[side] });
103
78
 
104
79
  // One listed folder is the answer; none, or several, is for the flag to say.
105
- if (readFlag({ args: opts.args, flag: folder.flag }) === undefined && listed.length !== 1) {
106
- return `missing ${folder.flag} (${folder.question}${listed.length > 1 ? `; ${listedFoldersNote({ folders: listed })}` : ''}) - names are never chosen for you`;
80
+ if (
81
+ ProjectNames.readFlag({ args: opts.args, flag: folder.flag }) === undefined &&
82
+ listed.length !== 1
83
+ ) {
84
+ return `missing ${folder.flag} (${folder.question}${listed.length > 1 ? `; ${LayoutFolder.listedNote({ folders: listed })}` : ''}) - names are never chosen for you`;
107
85
  }
108
86
 
109
87
  const hasApi = opts.args.includes(CreateFlags.API) || opts.args.includes(CreateFlags.NO_API);
@@ -187,8 +165,8 @@ const noSharedKindMessage = (opts: {
187
165
 
188
166
  /** The terminal asks which kind, listing only what the preset offers; end of input stops the command. */
189
167
  const askKind = async (opts: { offered: TAddKind[] }): Promise<TAddKind | undefined> => {
190
- if (menusAvailable()) {
191
- const picked = await promptSelect({
168
+ if (TerminalCapability.menusAvailable()) {
169
+ const picked = await TerminalPrompt.promptSelect({
192
170
  message: 'What do you want to create?',
193
171
  choices: opts.offered.map((kind) => ({
194
172
  value: kind,
@@ -201,7 +179,7 @@ const askKind = async (opts: { offered: TAddKind[] }): Promise<TAddKind | undefi
201
179
  }
202
180
 
203
181
  for (;;) {
204
- const answer = askWithPrompt({
182
+ const answer = ProjectNames.askWithPrompt({
205
183
  question: `What do you want to create? (${opts.offered.join(', ')})`,
206
184
  });
207
185
 
@@ -249,548 +227,580 @@ const literal = (opts: {
249
227
  ),
250
228
  ];
251
229
 
252
- /** A frontend's proxy target: the chosen backend app's port, or nothing when it has no backend. */
253
- export const resolveApiUrl = async (opts: {
254
- root: string;
255
- args: string[];
256
- interactive: boolean;
257
- backendFolders: string[];
258
- packages: IProjectPackage[];
259
- }): Promise<{ ok: true; apiUrl: string } | { ok: false; error: string }> => {
260
- if (opts.args.includes(CreateFlags.NO_API)) {
261
- return { ok: true, apiUrl: '' };
262
- }
263
-
264
- let chosen = readFlag({ args: opts.args, flag: CreateFlags.API });
265
-
266
- if (chosen === undefined) {
267
- if (!opts.interactive) {
268
- return { ok: false, error: MISSING_API };
269
- }
230
+ const usedPorts = (opts: { root: string; packages: IProjectPackage[] }): number[] =>
231
+ NextStep.readExistingApps({
232
+ root: opts.root,
233
+ paths: opts.packages.map((entry) => entry.path),
234
+ }).map((app) => app.port);
270
235
 
271
- if (menusAvailable()) {
272
- const backends = opts.packages.filter((entry) =>
273
- opts.backendFolders.some((folder) => entry.path.startsWith(`${folder}/`)),
274
- );
236
+ /** A terminal picks one of the presets the project recorded or an official one, or types another; null when cancelled. */
237
+ const askPreset = async (opts: { cwd: string }): Promise<string | null> => {
238
+ const loaded = await ConfigLoader.load({ root: opts.cwd });
275
239
 
276
- // Nothing to pick from: a frontend of a project without a backend has nothing to proxy to.
277
- if (backends.length === 0) {
278
- return { ok: true, apiUrl: '' };
279
- }
240
+ return PresetMenu.askSpec({ recorded: loaded.ok ? (loaded.config.presets ?? []) : [] });
241
+ };
280
242
 
281
- const picked = await promptSelect({
282
- message: 'Backend app to proxy /api to',
283
- choices: [
284
- ...backends.map((entry) => ({ value: entry.dir, label: entry.dir, hint: entry.path })),
285
- { value: NO_BACKEND, label: 'none', hint: 'no proxy' },
286
- ],
243
+ export class AppScaffold {
244
+ private static async runAdd(opts: {
245
+ cwd: string;
246
+ args: string[];
247
+ scratch: string;
248
+ official?: IOfficialPreset[];
249
+ }): Promise<number> {
250
+ const { cwd } = opts;
251
+ const flagged = ProjectNames.readFlag({ args: opts.args, flag: CreateFlags.PRESET });
252
+
253
+ if (flagged === undefined && !TerminalCapability.menusAvailable()) {
254
+ return AddFailure.fail({
255
+ message: '--preset needs a value (a package name, or file:<path>)',
287
256
  });
257
+ }
288
258
 
289
- if (picked === null) {
290
- return { ok: false, error: 'aborted' };
291
- }
259
+ const askingPreset = flagged === undefined ? askPreset({ cwd }) : undefined;
260
+ const typedPreset = await askingPreset;
261
+ const presetValue = flagged ?? typedPreset?.trim();
292
262
 
293
- chosen = picked === NO_BACKEND ? '' : picked;
294
- } else {
295
- chosen =
296
- askWithPrompt({ question: 'Backend app to proxy /api to (empty for none)' })?.trim() ?? '';
263
+ if (presetValue === undefined || presetValue === '') {
264
+ return AddFailure.fail({
265
+ message: '--preset needs a value (a package name, or file:<path>)',
266
+ });
297
267
  }
298
268
 
299
- if (chosen === '') {
300
- return { ok: true, apiUrl: '' };
269
+ const loaded = await ConfigLoader.load({ root: cwd });
270
+
271
+ if (!loaded.ok) {
272
+ return AddFailure.fail({ message: loaded.file === undefined ? ROOT_HINT : loaded.error });
301
273
  }
302
- }
303
274
 
304
- const backend = opts.packages.find(
305
- (entry) =>
306
- entry.dir === chosen &&
307
- opts.backendFolders.some((folder) => entry.path.startsWith(`${folder}/`)),
308
- );
275
+ const config: TResolvedConfig = loaded.config;
276
+ const configPath = relative(cwd, loaded.file);
277
+ const manifestPath = join(cwd, 'package.json');
278
+ const manifest = readRootManifest({ path: manifestPath });
309
279
 
310
- if (backend === undefined) {
311
- return {
312
- ok: false,
313
- error: `${CreateFlags.API} '${chosen}' is not a backend app of this monorepo`,
314
- };
315
- }
316
-
317
- const envFile = join(opts.root, backend.path, '.env.example');
318
- const port = existsSync(envFile)
319
- ? readPort({ envExample: readFileSync(envFile, 'utf8') })
320
- : undefined;
280
+ if (config.layout === undefined || manifest === undefined) {
281
+ return AddFailure.fail({ message: ROOT_HINT });
282
+ }
321
283
 
322
- if (port === undefined) {
323
- return {
324
- ok: false,
325
- error: `no *PORT=<number> line in ${backend.path}/.env.example to proxy to`,
326
- };
327
- }
284
+ const interactive = process.stdin.isTTY === true;
285
+ const flaggedKinds = ADD_KIND_ORDER.filter((candidate) =>
286
+ opts.args.includes(ADD_KINDS[candidate].flag),
287
+ );
328
288
 
329
- return { ok: true, apiUrl: `http://localhost:${port}` };
330
- };
289
+ if (flaggedKinds.length > 1) {
290
+ return AddFailure.fail({
291
+ message: `${CreateFlags.APP}, ${CreateFlags.LIB} and ${CreateFlags.SHARED} cannot be used together`,
292
+ });
293
+ }
331
294
 
332
- const usedPorts = (opts: { root: string; packages: IProjectPackage[] }): number[] =>
333
- readExistingApps({ root: opts.root, paths: opts.packages.map((entry) => entry.path) }).map(
334
- (app) => app.port,
335
- );
295
+ const [flaggedKind] = flaggedKinds;
296
+ const flagsLibrary = flaggedKind !== undefined && flaggedKind !== PackageKinds.APP;
297
+ const flaggedScope = ProjectNames.readScope({ args: opts.args });
336
298
 
337
- export const locate = async (opts: {
338
- cwd: string;
339
- scratch: string;
340
- spec: IPresetSpec;
341
- }): Promise<{ ok: true; located: ILocatedPreset } | { ok: false; error: string }> => {
342
- if (opts.spec.packageName === undefined) {
343
- return locatePreset({ spec: opts.spec, root: opts.cwd });
344
- }
299
+ if (!flaggedScope.ok) {
300
+ return AddFailure.fail({ message: flaggedScope.error });
301
+ }
345
302
 
346
- if (isInstallSkipped()) {
347
- return { ok: false, error: 'an npm preset needs an install - use file: in tests' };
348
- }
303
+ if (
304
+ flagsLibrary &&
305
+ ProjectNames.readFlag({ args: opts.args, flag: ADD_KINDS[flaggedKind].flag }) === undefined
306
+ ) {
307
+ return AddFailure.fail({ message: `${ADD_KINDS[flaggedKind].flag} needs a name` });
308
+ }
349
309
 
350
- const installed = await installNpmPreset({ scratch: opts.scratch, spec: opts.spec });
310
+ // Never a default kind: without a terminal to ask, nothing is fetched or written until the flag says which.
311
+ if (!interactive && flaggedKind === undefined) {
312
+ return AddFailure.fail({
313
+ message: `${SAY_WHAT}\n ${kindCommands({ presetValue }).join('\n ')}`,
314
+ });
315
+ }
351
316
 
352
- return installed === ExitCodes.OK
353
- ? locatePreset({ spec: opts.spec, root: opts.scratch })
354
- : { ok: false, error: `could not install ${opts.spec.packageName}@${opts.spec.range}` };
355
- };
317
+ const early =
318
+ interactive || flagsLibrary
319
+ ? undefined
320
+ : missingFlag({ args: opts.args, layout: config.layout });
356
321
 
357
- /** A terminal picks one of the presets the project recorded or an official one, or types another; null when cancelled. */
358
- const askPreset = async (opts: { cwd: string }): Promise<string | null> => {
359
- const loaded = await loadConfig({ root: opts.cwd });
322
+ if (early !== undefined) {
323
+ return AddFailure.fail({ message: early });
324
+ }
360
325
 
361
- return askPresetSpec({ recorded: loaded.ok ? (loaded.config.presets ?? []) : [] });
362
- };
326
+ const spec = Preset.parseSpec({ value: presetValue, cwd });
327
+ const located = await AppScaffold.locate({ cwd, scratch: opts.scratch, spec });
363
328
 
364
- const runAdd = async (opts: {
365
- cwd: string;
366
- args: string[];
367
- scratch: string;
368
- official?: IOfficialPreset[];
369
- }): Promise<number> => {
370
- const { cwd } = opts;
371
- const flagged = readFlag({ args: opts.args, flag: CreateFlags.PRESET });
329
+ if (!located.ok) {
330
+ return AddFailure.fail({ message: located.error });
331
+ }
372
332
 
373
- if (flagged === undefined && !menusAvailable()) {
374
- return AddFailure.fail({ message: '--preset needs a value (a package name, or file:<path>)' });
375
- }
333
+ const { preset, packageName, packageVersion } = located.located;
334
+ const recordedSpec = PresetRecord.presetSpecOf({ value: presetValue, root: cwd, cwd });
335
+ let kind: TAddKind = flaggedKind ?? PackageKinds.APP;
336
+
337
+ if (flaggedKind === LibraryKinds.SHARED && located.located.sharedFile === undefined) {
338
+ return AddFailure.fail({
339
+ message: noSharedKindMessage({
340
+ located: located.located,
341
+ recorded: config.presets,
342
+ name:
343
+ ProjectNames.readFlag({ args: opts.args, flag: ADD_KINDS[flaggedKind].flag }) ??
344
+ '<name>',
345
+ official: opts.official,
346
+ }),
347
+ });
348
+ }
376
349
 
377
- const askingPreset = flagged === undefined ? askPreset({ cwd }) : undefined;
378
- const typedPreset = await askingPreset;
379
- const presetValue = flagged ?? typedPreset?.trim();
350
+ if (flaggedKind === undefined) {
351
+ const offered = kindsOffered({ located: located.located });
352
+ const askingKind = offered.length === 1 ? PackageKinds.APP : askKind({ offered });
353
+ const chosen = await askingKind;
380
354
 
381
- if (presetValue === undefined || presetValue === '') {
382
- return AddFailure.fail({ message: '--preset needs a value (a package name, or file:<path>)' });
383
- }
355
+ if (chosen === undefined) {
356
+ return AddFailure.fail({ message: SAY_WHAT });
357
+ }
384
358
 
385
- const loaded = await loadConfig({ root: cwd });
359
+ kind = chosen;
360
+ }
386
361
 
387
- if (!loaded.ok) {
388
- return AddFailure.fail({ message: loaded.file === undefined ? ROOT_HINT : loaded.error });
389
- }
362
+ if (kind !== PackageKinds.APP) {
363
+ const flaggedName = ProjectNames.readFlag({ args: opts.args, flag: ADD_KINDS[kind].flag });
364
+ const askingName =
365
+ flaggedName === undefined
366
+ ? askInTerminal({
367
+ question: 'Name of this library',
368
+ validate: (value) =>
369
+ value.trim() === '' ? undefined : ProjectNames.nameProblem({ name: value.trim() }),
370
+ })
371
+ : undefined;
372
+ const typedName = await askingName;
373
+ const name = flaggedName ?? typedName?.trim();
374
+
375
+ if (name === undefined || name === '') {
376
+ return AddFailure.fail({ message: `${ADD_KINDS[kind].flag} needs a name` });
377
+ }
390
378
 
391
- const config: TResolvedConfig = loaded.config;
392
- const configPath = relative(cwd, loaded.file);
393
- const manifestPath = join(cwd, 'package.json');
394
- const manifest = readRootManifest({ path: manifestPath });
379
+ return LibraryScaffold.add({
380
+ cwd,
381
+ args: opts.args,
382
+ interactive,
383
+ presetValue,
384
+ spec,
385
+ located: located.located,
386
+ config,
387
+ configFile: loaded.file,
388
+ configPath,
389
+ manifest,
390
+ packages: ProjectPackages.resolve({ config }),
391
+ libName: name,
392
+ kind,
393
+ recorded: ({ block }) =>
394
+ PresetRecord.record({
395
+ block,
396
+ preset: LibPreset.recordedOf({ spec: recordedSpec, located: located.located }),
397
+ }),
398
+ });
399
+ }
395
400
 
396
- if (config.layout === undefined || manifest === undefined) {
397
- return AddFailure.fail({ message: ROOT_HINT });
398
- }
401
+ // Before any question: a catalog the preset cannot live in is no reason to ask for names.
402
+ const peerProblem = WorkspaceManifest.checkPeers({
403
+ catalog: WorkspaceManifest.readCatalog({ manifest }),
404
+ peers: preset.peers,
405
+ presetVersions: preset,
406
+ });
399
407
 
400
- const interactive = process.stdin.isTTY === true;
401
- const flaggedKinds = ADD_KIND_ORDER.filter((candidate) =>
402
- opts.args.includes(ADD_KINDS[candidate].flag),
403
- );
408
+ if (peerProblem !== undefined) {
409
+ return AddFailure.fail({ message: peerProblem });
410
+ }
404
411
 
405
- if (flaggedKinds.length > 1) {
406
- return AddFailure.fail({
407
- message: `${CreateFlags.APP}, ${CreateFlags.LIB} and ${CreateFlags.SHARED} cannot be used together`,
412
+ const side = preset.side;
413
+ const listed = LayoutFolder.layoutFoldersOf({ value: config.layout[side] });
414
+ const [only] = listed;
415
+ const names = await ProjectNames.resolve({
416
+ fields: [
417
+ // One listed folder is the answer and a menu does not ask; several are picked from; a new one is a flag.
418
+ {
419
+ ...SIDE_FIELDS[side],
420
+ previous: listed.length === 1 ? only : undefined,
421
+ choices: listed.length > 1 ? listed : undefined,
422
+ fixed: TerminalCapability.menusAvailable() && listed.length === 1,
423
+ },
424
+ { key: 'app', flag: CreateFlags.APP, question: `Name of this ${side} app` },
425
+ ],
426
+ args: opts.args,
427
+ interactive,
428
+ ask: askInTerminal,
408
429
  });
409
- }
410
430
 
411
- const [flaggedKind] = flaggedKinds;
412
- const flagsLibrary = flaggedKind !== undefined && flaggedKind !== PackageKinds.APP;
413
- const flaggedScope = readScope({ args: opts.args });
431
+ if (!names.ok) {
432
+ return AddFailure.fail({ message: names.error });
433
+ }
434
+
435
+ const { folder, app } = names.names;
414
436
 
415
- if (!flaggedScope.ok) {
416
- return AddFailure.fail({ message: flaggedScope.error });
417
- }
437
+ const otherSide = Object.entries(config.layout).find(
438
+ ([key, value]) => key !== side && LayoutFolder.layoutFoldersOf({ value }).includes(folder),
439
+ );
418
440
 
419
- if (
420
- flagsLibrary &&
421
- readFlag({ args: opts.args, flag: ADD_KINDS[flaggedKind].flag }) === undefined
422
- ) {
423
- return AddFailure.fail({ message: `${ADD_KINDS[flaggedKind].flag} needs a name` });
424
- }
441
+ // One folder holds one kind of code: a folder another key already owns would mix them.
442
+ if (otherSide !== undefined) {
443
+ return AddFailure.fail({
444
+ message:
445
+ otherSide[0] === LayoutKeys.OTHER
446
+ ? `the ${side} folder '${folder}' is listed under layout.other in ${configPath}: folders the layout leaves alone are not app targets`
447
+ : `the ${side} folder '${folder}' is the ${otherSide[0]} folder in ${configPath}; each kind of code needs its own folder`,
448
+ });
449
+ }
425
450
 
426
- // Never a default kind: without a terminal to ask, nothing is fetched or written until the flag says which.
427
- if (!interactive && flaggedKind === undefined) {
428
- return AddFailure.fail({
429
- message: `${SAY_WHAT}\n ${kindCommands({ presetValue }).join('\n ')}`,
451
+ const grown = LayoutFolder.withLayoutFolder({ value: config.layout[side], folder });
452
+ const overlaps = LayoutFolder.layoutOverlapProblems({
453
+ layout: { ...config.layout, [side]: grown },
430
454
  });
431
- }
432
455
 
433
- const early =
434
- interactive || flagsLibrary
435
- ? undefined
436
- : missingFlag({ args: opts.args, layout: config.layout });
456
+ // A folder inside another (or around one) would give a package path two owners.
457
+ if (overlaps.length > 0) {
458
+ return AddFailure.fail({
459
+ message: `the ${side} folder '${folder}' does not fit the layout of ${configPath}: ${overlaps.join('; ')}`,
460
+ });
461
+ }
437
462
 
438
- if (early !== undefined) {
439
- return AddFailure.fail({ message: early });
440
- }
463
+ const isNewFolder = !listed.includes(folder);
441
464
 
442
- const spec = parsePresetSpec({ value: presetValue, cwd });
443
- const located = await locate({ cwd, scratch: opts.scratch, spec });
465
+ // Optional, asked only where menus are drawn; a plain terminal and a script give --scope.
466
+ const askingScope =
467
+ flaggedScope.scope ??
468
+ (TerminalCapability.menusAvailable() ? ProjectNames.askScope() : undefined);
469
+ const scope = await askingScope;
444
470
 
445
- if (!located.ok) {
446
- return AddFailure.fail({ message: located.error });
447
- }
471
+ if (scope === null) {
472
+ return AddFailure.fail({ message: ABORTED });
473
+ }
448
474
 
449
- const { preset, packageName, packageVersion } = located.located;
450
- const recordedSpec = presetSpecOf({ value: presetValue, root: cwd, cwd });
451
- let kind: TAddKind = flaggedKind ?? PackageKinds.APP;
475
+ const packageOfApp = scope === undefined ? app : `${scope}/${app}`;
476
+ const packages = ProjectPackages.resolve({ config });
452
477
 
453
- if (flaggedKind === LibraryKinds.SHARED && located.located.sharedFile === undefined) {
454
- return AddFailure.fail({
455
- message: noSharedKindMessage({
456
- located: located.located,
457
- recorded: config.presets,
458
- name: readFlag({ args: opts.args, flag: ADD_KINDS[flaggedKind].flag }) ?? '<name>',
459
- official: opts.official,
460
- }),
478
+ if (
479
+ existsSync(join(cwd, folder, app)) ||
480
+ packages.some((entry) => entry.dir === app || entry.name === packageOfApp)
481
+ ) {
482
+ return AddFailure.fail({ message: `${folder}/${app} already exists` });
483
+ }
484
+
485
+ const devPort = PortRegistry.pick({
486
+ preferred: preset.devPort,
487
+ used: usedPorts({ root: cwd, packages }),
461
488
  });
462
- }
489
+ let apiUrl = '';
490
+
491
+ if (side === AppSides.FRONTEND) {
492
+ const api = await AppScaffold.resolveApiUrl({
493
+ root: cwd,
494
+ args: opts.args,
495
+ interactive,
496
+ backendFolders: LayoutFolder.layoutFoldersOf({ value: config.layout.backend }),
497
+ packages,
498
+ });
463
499
 
464
- if (flaggedKind === undefined) {
465
- const offered = kindsOffered({ located: located.located });
466
- const askingKind = offered.length === 1 ? PackageKinds.APP : askKind({ offered });
467
- const chosen = await askingKind;
500
+ if (!api.ok) {
501
+ return AddFailure.fail({ message: api.error });
502
+ }
468
503
 
469
- if (chosen === undefined) {
470
- return AddFailure.fail({ message: SAY_WHAT });
504
+ apiUrl = api.apiUrl;
471
505
  }
472
506
 
473
- kind = chosen;
474
- }
475
-
476
- if (kind !== PackageKinds.APP) {
477
- const flaggedName = readFlag({ args: opts.args, flag: ADD_KINDS[kind].flag });
478
- const askingName =
479
- flaggedName === undefined
480
- ? askInTerminal({
481
- question: 'Name of this library',
482
- validate: (value) =>
483
- value.trim() === '' ? undefined : nameProblem({ name: value.trim() }),
484
- })
485
- : undefined;
486
- const typedName = await askingName;
487
- const name = flaggedName ?? typedName?.trim();
488
-
489
- if (name === undefined || name === '') {
490
- return AddFailure.fail({ message: `${ADD_KINDS[kind].flag} needs a name` });
507
+ const source = readFileSync(loaded.file, 'utf8');
508
+ const entry = { dir: app, name: packageOfApp, path: `${folder}/${app}` };
509
+ const knownSources = new Set(config.atlas.sources.map((known) => known.name));
510
+ const newSources = preset.atlas.filter((candidate) => !knownSources.has(candidate.name));
511
+ const parsed = AppsBlock.parse({ source });
512
+
513
+ // The user's config is theirs: with the block gone or no longer JSON it is never rewritten, only described.
514
+ if (!parsed.ok) {
515
+ return AddFailure.fail({
516
+ message: [
517
+ parsed.reason === AppsBlockProblems.MISSING
518
+ ? `the vulcan:apps block is gone from ${configPath} - add by hand:`
519
+ : `the vulcan:apps block in ${configPath} is not the JSON vulcan wrote - add by hand:`,
520
+ ...literal({ side, folders: grown, app: entry, sources: newSources }),
521
+ ].join('\n'),
522
+ });
491
523
  }
492
524
 
493
- return addLibrary({
494
- cwd,
495
- args: opts.args,
496
- interactive,
497
- presetValue,
498
- spec,
499
- located: located.located,
500
- config,
501
- configFile: loaded.file,
502
- configPath,
503
- manifest,
504
- packages: resolvePackages({ config }),
505
- libName: name,
506
- kind,
507
- recorded: ({ block }) =>
508
- recordPreset({
509
- block,
510
- preset: recordedPresetOf({ spec: recordedSpec, located: located.located }),
511
- }),
525
+ // Extend what the markers hold: the resolved config also carries what the user added outside them.
526
+ const extended: IAppsBlock = {
527
+ layout: {
528
+ ...parsed.block.layout,
529
+ [side]: LayoutFolder.withLayoutFolder({ value: parsed.block.layout[side], folder }),
530
+ },
531
+ packages: [...parsed.block.packages, entry],
532
+ ...(parsed.block.presets === undefined ? {} : { presets: parsed.block.presets }),
533
+ sources: [
534
+ ...parsed.block.sources,
535
+ ...newSources.filter(
536
+ (candidate) => !parsed.block.sources.some((existing) => existing.name === candidate.name),
537
+ ),
538
+ ],
539
+ };
540
+ const block = PresetRecord.record({
541
+ block: extended,
542
+ preset: LibPreset.recordedOf({ spec: recordedSpec, located: located.located }),
512
543
  });
513
- }
514
-
515
- // Before any question: a catalog the preset cannot live in is no reason to ask for names.
516
- const peerProblem = checkPeers({
517
- catalog: readCatalog({ manifest }),
518
- peers: preset.peers,
519
- presetVersions: preset,
520
- });
544
+ const replaced = AppsBlock.replace({ source, block });
545
+ // A config written before presets were recorded does not read them yet: the line that does goes in.
546
+ const nextConfig =
547
+ replaced === undefined || replaced.includes('apps.presets')
548
+ ? replaced
549
+ : replaced.replace(
550
+ ' packages: apps.packages,\n',
551
+ ' packages: apps.packages,\n presets: apps.presets,\n',
552
+ );
553
+
554
+ if (nextConfig === undefined) {
555
+ return AddFailure.fail({ message: ROOT_HINT });
556
+ }
521
557
 
522
- if (peerProblem !== undefined) {
523
- return AddFailure.fail({ message: peerProblem });
524
- }
558
+ const project = config.name ?? (typeof manifest.name === 'string' ? manifest.name : app);
525
559
 
526
- const side = preset.side;
527
- const listed = layoutFoldersOf({ value: config.layout[side] });
528
- const [only] = listed;
529
- const names = await resolveNames({
530
- fields: [
531
- // One listed folder is the answer and a menu does not ask; several are picked from; a new one is a flag.
532
- {
533
- ...SIDE_FIELDS[side],
534
- previous: listed.length === 1 ? only : undefined,
535
- choices: listed.length > 1 ? listed : undefined,
536
- fixed: menusAvailable() && listed.length === 1,
537
- },
538
- { key: 'app', flag: CreateFlags.APP, question: `Name of this ${side} app` },
539
- ],
540
- args: opts.args,
541
- interactive,
542
- ask: askInTerminal,
543
- });
544
-
545
- if (!names.ok) {
546
- return AddFailure.fail({ message: names.error });
547
- }
560
+ const warning = WorkspaceDocs.filePresetWarning({ spec, packageName });
548
561
 
549
- const { folder, app } = names.names;
562
+ if (warning !== undefined) {
563
+ process.stderr.write(`${warning}\n`);
564
+ }
550
565
 
551
- const otherSide = Object.entries(config.layout).find(
552
- ([key, value]) => key !== side && layoutFoldersOf({ value }).includes(folder),
553
- );
566
+ const rows: [string, string][] = [['app', `${folder}/${app}`]];
554
567
 
555
- // One folder holds one kind of code: a folder another key already owns would mix them.
556
- if (otherSide !== undefined) {
557
- return AddFailure.fail({
558
- message:
559
- otherSide[0] === LayoutKeys.OTHER
560
- ? `the ${side} folder '${folder}' is listed under layout.other in ${configPath}: folders the layout leaves alone are not app targets`
561
- : `the ${side} folder '${folder}' is the ${otherSide[0]} folder in ${configPath}; each kind of code needs its own folder`,
562
- });
563
- }
568
+ if (isNewFolder) {
569
+ rows.push([
570
+ 'layout',
571
+ `adds '${folder}' to layout.${side} (now ${LayoutFolder.describe({ folders: LayoutFolder.layoutFoldersOf({ value: grown }) })})`,
572
+ ]);
573
+ }
564
574
 
565
- const grown = withLayoutFolder({ value: config.layout[side], folder });
566
- const overlaps = layoutOverlapProblems({ layout: { ...config.layout, [side]: grown } });
575
+ if (scope !== undefined) {
576
+ rows.push(['package', packageOfApp]);
577
+ }
567
578
 
568
- // A folder inside another (or around one) would give a package path two owners.
569
- if (overlaps.length > 0) {
570
- return AddFailure.fail({
571
- message: `the ${side} folder '${folder}' does not fit the layout of ${configPath}: ${overlaps.join('; ')}`,
572
- });
573
- }
579
+ rows.push(
580
+ ['side', side],
581
+ ['preset', `${packageName} ${packageVersion}`],
582
+ ['port', String(devPort)],
583
+ );
574
584
 
575
- const isNewFolder = !listed.includes(folder);
585
+ if (side === AppSides.FRONTEND) {
586
+ rows.push(['proxy', apiUrl === '' ? '(none)' : apiUrl]);
587
+ }
576
588
 
577
- // Optional, asked only where menus are drawn; a plain terminal and a script give --scope.
578
- const askingScope = flaggedScope.scope ?? (menusAvailable() ? askScope() : undefined);
579
- const scope = await askingScope;
589
+ const confirmed = await WritePlan.confirm({
590
+ title: `Add ${app}`,
591
+ lines: WritePlan.planLines({ rows }),
592
+ });
580
593
 
581
- if (scope === null) {
582
- return AddFailure.fail({ message: ABORTED });
583
- }
594
+ if (!confirmed) {
595
+ return AddFailure.fail({ message: ABORTED });
596
+ }
584
597
 
585
- const packageOfApp = scope === undefined ? app : `${scope}/${app}`;
586
- const packages = resolvePackages({ config });
598
+ Preset.copyFiles({
599
+ located: located.located,
600
+ target: join(cwd, folder, app),
601
+ tokens: { project, app, appPath: `${folder}/${app}`, devPort: String(devPort), apiUrl },
602
+ });
603
+ ProjectFile.write({
604
+ root: cwd,
605
+ path: `${folder}/${app}/package.json`,
606
+ content: WorkspaceManifest.renderApp({
607
+ app,
608
+ name: packageOfApp,
609
+ preset,
610
+ presetPackage: { name: packageName, version: packageVersion },
611
+ }),
612
+ });
587
613
 
588
- if (
589
- existsSync(join(cwd, folder, app)) ||
590
- packages.some((entry) => entry.dir === app || entry.name === packageOfApp)
591
- ) {
592
- return AddFailure.fail({ message: `${folder}/${app} already exists` });
593
- }
614
+ const nextManifest = WorkspaceManifest.planRoot({
615
+ manifest,
616
+ globs: ProjectScaffold.readWorkspaceGlobs({ root: cwd }),
617
+ folder,
618
+ additions: {
619
+ ...preset.dependencies,
620
+ ...preset.devDependencies,
621
+ [packageName]: spec.packageName === undefined ? spec.range : packageVersion,
622
+ },
623
+ });
594
624
 
595
- const devPort = pickPort({ preferred: preset.devPort, used: usedPorts({ root: cwd, packages }) });
596
- let apiUrl = '';
625
+ ProjectFile.write({
626
+ root: cwd,
627
+ path: 'package.json',
628
+ content: ManifestJson.render({ value: nextManifest }),
629
+ });
630
+ ProjectFile.write({ root: cwd, path: configPath, content: nextConfig });
631
+ ProjectFile.write({
632
+ root: cwd,
633
+ path: `${KNOWLEDGE_DIRECTORY}/packages/${app}.md`,
634
+ content: WorkspaceDocs.renderAppConcept({
635
+ app: { name: app, side, folder },
636
+ summary: preset.summary,
637
+ presetPackage: packageName,
638
+ }),
639
+ });
640
+ const indexPath = join(cwd, KNOWLEDGE_DIRECTORY, 'index.md');
597
641
 
598
- if (side === AppSides.FRONTEND) {
599
- const api = await resolveApiUrl({
642
+ ProjectFile.write({
600
643
  root: cwd,
601
- args: opts.args,
602
- interactive,
603
- backendFolders: layoutFoldersOf({ value: config.layout.backend }),
604
- packages,
644
+ path: `${KNOWLEDGE_DIRECTORY}/index.md`,
645
+ content: existsSync(indexPath)
646
+ ? AppsBlock.addBullet({
647
+ source: readFileSync(indexPath, 'utf8'),
648
+ app: { name: app, summary: preset.summary },
649
+ })
650
+ : WorkspaceDocs.renderKnowledgeIndex({
651
+ project,
652
+ apps: [{ name: app, summary: preset.summary }],
653
+ }),
605
654
  });
606
655
 
607
- if (!api.ok) {
608
- return AddFailure.fail({ message: api.error });
656
+ for (const step of [
657
+ () => SubProcess.runBun({ cwd, args: ['install'], label: 'bun install' }),
658
+ // The installed CLI syncs, so the project is wired to the version it pins.
659
+ () =>
660
+ SubProcess.runBun({
661
+ cwd,
662
+ args: [join(cwd, 'node_modules', '.bin', 'vulcan'), 'sync'],
663
+ label: 'vulcan sync',
664
+ }),
665
+ () =>
666
+ AppChecks.run({ root: cwd, appDirectory: join(cwd, folder, app), checks: preset.checks }),
667
+ ]) {
668
+ const code = await step();
669
+
670
+ if (code !== ExitCodes.OK) {
671
+ return code;
672
+ }
609
673
  }
610
674
 
611
- apiUrl = api.apiUrl;
612
- }
675
+ // Every app `make dev` serves: those that were here, then the new one at the port it was given.
676
+ process.stderr.write(
677
+ NextStep.render({
678
+ done: `Done. ${folder}/${app} is added.`,
679
+ command: 'make dev',
680
+ apps: [
681
+ ...NextStep.readExistingApps({
682
+ root: cwd,
683
+ paths: packages.map((existing) => existing.path),
684
+ }),
685
+ { port: devPort, urls: preset.urls },
686
+ ],
687
+ }),
688
+ );
613
689
 
614
- const source = readFileSync(loaded.file, 'utf8');
615
- const entry = { dir: app, name: packageOfApp, path: `${folder}/${app}` };
616
- const knownSources = new Set(config.atlas.sources.map((known) => known.name));
617
- const newSources = preset.atlas.filter((candidate) => !knownSources.has(candidate.name));
618
- const parsed = parseAppsBlock({ source });
619
-
620
- // The user's config is theirs: with the block gone or no longer JSON it is never rewritten, only described.
621
- if (!parsed.ok) {
622
- return AddFailure.fail({
623
- message: [
624
- parsed.reason === AppsBlockProblems.MISSING
625
- ? `the vulcan:apps block is gone from ${configPath} - add by hand:`
626
- : `the vulcan:apps block in ${configPath} is not the JSON vulcan wrote - add by hand:`,
627
- ...literal({ side, folders: grown, app: entry, sources: newSources }),
628
- ].join('\n'),
629
- });
690
+ return ExitCodes.OK;
630
691
  }
631
692
 
632
- // Extend what the markers hold: the resolved config also carries what the user added outside them.
633
- const extended: IAppsBlock = {
634
- layout: {
635
- ...parsed.block.layout,
636
- [side]: withLayoutFolder({ value: parsed.block.layout[side], folder }),
637
- },
638
- packages: [...parsed.block.packages, entry],
639
- ...(parsed.block.presets === undefined ? {} : { presets: parsed.block.presets }),
640
- sources: [
641
- ...parsed.block.sources,
642
- ...newSources.filter(
643
- (candidate) => !parsed.block.sources.some((existing) => existing.name === candidate.name),
644
- ),
645
- ],
646
- };
647
- const block = recordPreset({
648
- block: extended,
649
- preset: recordedPresetOf({ spec: recordedSpec, located: located.located }),
650
- });
651
- const replaced = replaceAppsBlock({ source, block });
652
- // A config written before presets were recorded does not read them yet: the line that does goes in.
653
- const nextConfig =
654
- replaced === undefined || replaced.includes('apps.presets')
655
- ? replaced
656
- : replaced.replace(
657
- ' packages: apps.packages,\n',
658
- ' packages: apps.packages,\n presets: apps.presets,\n',
659
- );
660
-
661
- if (nextConfig === undefined) {
662
- return AddFailure.fail({ message: ROOT_HINT });
663
- }
693
+ /** A frontend's proxy target: the chosen backend app's port, or nothing when it has no backend. */
694
+ static async resolveApiUrl(opts: {
695
+ root: string;
696
+ args: string[];
697
+ interactive: boolean;
698
+ backendFolders: string[];
699
+ packages: IProjectPackage[];
700
+ }): Promise<{ ok: true; apiUrl: string } | { ok: false; error: string }> {
701
+ if (opts.args.includes(CreateFlags.NO_API)) {
702
+ return { ok: true, apiUrl: '' };
703
+ }
664
704
 
665
- const project = config.name ?? (typeof manifest.name === 'string' ? manifest.name : app);
705
+ let chosen = ProjectNames.readFlag({ args: opts.args, flag: CreateFlags.API });
666
706
 
667
- const warning = filePresetWarning({ spec, packageName });
707
+ if (chosen === undefined) {
708
+ if (!opts.interactive) {
709
+ return { ok: false, error: MISSING_API };
710
+ }
668
711
 
669
- if (warning !== undefined) {
670
- process.stderr.write(`${warning}\n`);
671
- }
712
+ if (TerminalCapability.menusAvailable()) {
713
+ const backends = opts.packages.filter((entry) =>
714
+ opts.backendFolders.some((folder) => entry.path.startsWith(`${folder}/`)),
715
+ );
672
716
 
673
- const rows: [string, string][] = [['app', `${folder}/${app}`]];
717
+ // Nothing to pick from: a frontend of a project without a backend has nothing to proxy to.
718
+ if (backends.length === 0) {
719
+ return { ok: true, apiUrl: '' };
720
+ }
721
+
722
+ const picked = await TerminalPrompt.promptSelect({
723
+ message: 'Backend app to proxy /api to',
724
+ choices: [
725
+ ...backends.map((entry) => ({ value: entry.dir, label: entry.dir, hint: entry.path })),
726
+ { value: NO_BACKEND, label: 'none', hint: 'no proxy' },
727
+ ],
728
+ });
729
+
730
+ if (picked === null) {
731
+ return { ok: false, error: 'aborted' };
732
+ }
733
+
734
+ chosen = picked === NO_BACKEND ? '' : picked;
735
+ } else {
736
+ chosen =
737
+ ProjectNames.askWithPrompt({
738
+ question: 'Backend app to proxy /api to (empty for none)',
739
+ })?.trim() ?? '';
740
+ }
674
741
 
675
- if (isNewFolder) {
676
- rows.push([
677
- 'layout',
678
- `adds '${folder}' to layout.${side} (now ${describeFolders({ folders: layoutFoldersOf({ value: grown }) })})`,
679
- ]);
680
- }
742
+ if (chosen === '') {
743
+ return { ok: true, apiUrl: '' };
744
+ }
745
+ }
681
746
 
682
- if (scope !== undefined) {
683
- rows.push(['package', packageOfApp]);
684
- }
747
+ const backend = opts.packages.find(
748
+ (entry) =>
749
+ entry.dir === chosen &&
750
+ opts.backendFolders.some((folder) => entry.path.startsWith(`${folder}/`)),
751
+ );
685
752
 
686
- rows.push(
687
- ['side', side],
688
- ['preset', `${packageName} ${packageVersion}`],
689
- ['port', String(devPort)],
690
- );
753
+ if (backend === undefined) {
754
+ return {
755
+ ok: false,
756
+ error: `${CreateFlags.API} '${chosen}' is not a backend app of this monorepo`,
757
+ };
758
+ }
691
759
 
692
- if (side === AppSides.FRONTEND) {
693
- rows.push(['proxy', apiUrl === '' ? '(none)' : apiUrl]);
694
- }
760
+ const envFile = join(opts.root, backend.path, '.env.example');
761
+ const port = existsSync(envFile)
762
+ ? PortRegistry.read({ envExample: readFileSync(envFile, 'utf8') })
763
+ : undefined;
695
764
 
696
- const confirmed = await confirmWrite({ title: `Add ${app}`, lines: planLines({ rows }) });
765
+ if (port === undefined) {
766
+ return {
767
+ ok: false,
768
+ error: `no *PORT=<number> line in ${backend.path}/.env.example to proxy to`,
769
+ };
770
+ }
697
771
 
698
- if (!confirmed) {
699
- return AddFailure.fail({ message: ABORTED });
772
+ return { ok: true, apiUrl: `http://localhost:${port}` };
700
773
  }
701
774
 
702
- copyPresetFiles({
703
- located: located.located,
704
- target: join(cwd, folder, app),
705
- tokens: { project, app, appPath: `${folder}/${app}`, devPort: String(devPort), apiUrl },
706
- });
707
- writeFile({
708
- root: cwd,
709
- path: `${folder}/${app}/package.json`,
710
- content: renderAppManifest({
711
- app,
712
- name: packageOfApp,
713
- preset,
714
- presetPackage: { name: packageName, version: packageVersion },
715
- }),
716
- });
717
-
718
- const nextManifest = planRootManifest({
719
- manifest,
720
- globs: readWorkspaceGlobs({ root: cwd }),
721
- folder,
722
- additions: {
723
- ...preset.dependencies,
724
- ...preset.devDependencies,
725
- [packageName]: spec.packageName === undefined ? spec.range : packageVersion,
726
- },
727
- });
728
-
729
- writeFile({
730
- root: cwd,
731
- path: 'package.json',
732
- content: renderManifestJson({ value: nextManifest }),
733
- });
734
- writeFile({ root: cwd, path: configPath, content: nextConfig });
735
- writeFile({
736
- root: cwd,
737
- path: `${KNOWLEDGE_DIRECTORY}/packages/${app}.md`,
738
- content: renderAppConcept({
739
- app: { name: app, side, folder },
740
- summary: preset.summary,
741
- presetPackage: packageName,
742
- }),
743
- });
744
- const indexPath = join(cwd, KNOWLEDGE_DIRECTORY, 'index.md');
745
-
746
- writeFile({
747
- root: cwd,
748
- path: `${KNOWLEDGE_DIRECTORY}/index.md`,
749
- content: existsSync(indexPath)
750
- ? addAppBullet({
751
- source: readFileSync(indexPath, 'utf8'),
752
- app: { name: app, summary: preset.summary },
753
- })
754
- : renderKnowledgeIndex({ project, apps: [{ name: app, summary: preset.summary }] }),
755
- });
756
-
757
- for (const step of [
758
- () => runBun({ cwd, args: ['install'], label: 'bun install' }),
759
- // The installed CLI syncs, so the project is wired to the version it pins.
760
- () =>
761
- runBun({
762
- cwd,
763
- args: [join(cwd, 'node_modules', '.bin', 'vulcan'), 'sync'],
764
- label: 'vulcan sync',
765
- }),
766
- () => runAppChecks({ root: cwd, appDirectory: join(cwd, folder, app), checks: preset.checks }),
767
- ]) {
768
- const code = await step();
775
+ static async locate(opts: {
776
+ cwd: string;
777
+ scratch: string;
778
+ spec: IPresetSpec;
779
+ }): Promise<{ ok: true; located: ILocatedPreset } | { ok: false; error: string }> {
780
+ if (opts.spec.packageName === undefined) {
781
+ return Preset.locate({ spec: opts.spec, root: opts.cwd });
782
+ }
769
783
 
770
- if (code !== ExitCodes.OK) {
771
- return code;
784
+ if (SubProcess.isInstallSkipped()) {
785
+ return { ok: false, error: 'an npm preset needs an install - use file: in tests' };
772
786
  }
773
- }
774
787
 
775
- // Every app `make dev` serves: those that were here, then the new one at the port it was given.
776
- process.stderr.write(
777
- renderNext({
778
- done: `Done. ${folder}/${app} is added.`,
779
- command: 'make dev',
780
- apps: [
781
- ...readExistingApps({ root: cwd, paths: packages.map((existing) => existing.path) }),
782
- { port: devPort, urls: preset.urls },
783
- ],
784
- }),
785
- );
788
+ const installed = await PresetScratch.installNpm({ scratch: opts.scratch, spec: opts.spec });
786
789
 
787
- return ExitCodes.OK;
788
- };
790
+ return installed === ExitCodes.OK
791
+ ? Preset.locate({ spec: opts.spec, root: opts.scratch })
792
+ : { ok: false, error: `could not install ${opts.spec.packageName}@${opts.spec.range}` };
793
+ }
789
794
 
790
- export const addApp = async (opts: {
791
- cwd: string;
792
- args: string[];
793
- /** The official presets a refusal names; the published list by default. */
794
- official?: IOfficialPreset[];
795
- }): Promise<number> =>
796
- withScratch({ root: opts.cwd, run: (scratch) => runAdd({ ...opts, scratch }) });
795
+ static async add(opts: {
796
+ cwd: string;
797
+ args: string[];
798
+ /** The official presets a refusal names; the published list by default. */
799
+ official?: IOfficialPreset[];
800
+ }): Promise<number> {
801
+ return PresetScratch.withScratch({
802
+ root: opts.cwd,
803
+ run: (scratch) => AppScaffold.runAdd({ ...opts, scratch }),
804
+ });
805
+ }
806
+ }