@venizia/vulcan 0.4.8 → 0.4.9-1

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 (179) hide show
  1. package/base/extensions/vulcan-guards.ts +48 -41
  2. package/base/hooks/antigravity-guards.ts +4 -3
  3. package/base/hooks/codex-guards.ts +17 -6
  4. package/base/hooks/guard-git.ts +8 -8
  5. package/base/hooks/guard-manifest.ts +5 -5
  6. package/base/hooks/guard-outside.ts +8 -8
  7. package/base/hooks/guard-package.ts +6 -6
  8. package/base/hooks/guard-remote-hosts.ts +14 -9
  9. package/base/hooks/guard-scripting.ts +6 -6
  10. package/base/hooks/guard-writes.ts +20 -11
  11. package/base/hooks/post-tool.ts +4 -3
  12. package/base/hooks/prompt-submit.ts +4 -3
  13. package/base/hooks/session-start.ts +5 -3
  14. package/base/hooks/stop.ts +4 -3
  15. package/base/hooks/subagent-start.ts +2 -2
  16. package/base/make/vulcan.mk +1 -4
  17. package/base/skills/build-a-feature/SKILL.md +1 -1
  18. package/base/skills/docs-update/SKILL.md +11 -5
  19. package/base/skills/docs-update/evals/evals.json +1 -1
  20. package/base/skills/docs-writing/SKILL.md +1 -1
  21. package/base/skills/plan-a-change/references/spec-card.md +1 -1
  22. package/base/skills/ship/SKILL.md +1 -1
  23. package/base/skills/visualize-work/SKILL.md +29 -6
  24. package/base/skills/visualize-work/references/spec.md +16 -5
  25. package/package.json +5 -6
  26. package/src/agents/atlas-block.ts +43 -43
  27. package/src/agents/codex-hooks.ts +55 -52
  28. package/src/agents/common/types.ts +1 -1
  29. package/src/agents/detect.ts +19 -16
  30. package/src/agents/exclude.ts +97 -98
  31. package/src/agents/hooks-json.ts +41 -43
  32. package/src/agents/local.ts +46 -43
  33. package/src/agents/prompt.ts +45 -42
  34. package/src/agents/render.ts +203 -201
  35. package/src/agents/resolve.ts +133 -134
  36. package/src/agents/table.ts +12 -8
  37. package/src/cli.ts +3 -1
  38. package/src/commands/add.command.ts +2 -2
  39. package/src/commands/agents.command.ts +11 -17
  40. package/src/commands/clean.command.ts +6 -6
  41. package/src/commands/doctor.command.ts +6 -4
  42. package/src/commands/help.command.ts +11 -9
  43. package/src/commands/init.command.ts +14 -8
  44. package/src/commands/preset.command.ts +2 -2
  45. package/src/commands/profile.command.ts +43 -50
  46. package/src/commands/sync.command.ts +109 -111
  47. package/src/commands/upgrade.command.ts +85 -78
  48. package/src/commands/visualize.command.ts +20 -5
  49. package/src/commands/x.command.ts +55 -50
  50. package/src/common/format.ts +23 -21
  51. package/src/common/index.ts +2 -0
  52. package/src/common/json.ts +8 -5
  53. package/src/common/layout-folder.ts +96 -111
  54. package/src/common/paths.ts +14 -12
  55. package/src/common/record.ts +7 -0
  56. package/src/common/text.ts +7 -0
  57. package/src/config/common/constants.ts +13 -1
  58. package/src/config/common/types.ts +8 -1
  59. package/src/config/loader.ts +53 -48
  60. package/src/config/packages.ts +17 -11
  61. package/src/config/schema.ts +54 -7
  62. package/src/create/add-app.ts +604 -493
  63. package/src/create/add-lib.ts +249 -242
  64. package/src/create/bunfig.ts +26 -23
  65. package/src/create/checks.ts +36 -34
  66. package/src/create/common/constants.ts +1 -0
  67. package/src/create/common/failure.ts +10 -0
  68. package/src/create/common/index.ts +2 -0
  69. package/src/create/common/preset-path.ts +11 -0
  70. package/src/create/common/types.ts +7 -2
  71. package/src/create/diff.ts +21 -23
  72. package/src/create/dockerignore.ts +26 -24
  73. package/src/create/files.ts +7 -5
  74. package/src/create/init-monorepo.ts +78 -80
  75. package/src/create/lib-preset.ts +62 -61
  76. package/src/create/manifest-json.ts +10 -4
  77. package/src/create/names.ts +217 -210
  78. package/src/create/next.ts +27 -24
  79. package/src/create/plan.ts +15 -12
  80. package/src/create/preset-diff.ts +415 -240
  81. package/src/create/preset-menu.ts +40 -34
  82. package/src/create/preset.ts +207 -194
  83. package/src/create/process.ts +80 -71
  84. package/src/create/scratch.ts +49 -48
  85. package/src/create/workspace.ts +423 -398
  86. package/src/doctor/checks.ts +1069 -998
  87. package/src/doctor/makefile.ts +17 -13
  88. package/src/doctor/runner.ts +88 -116
  89. package/src/doctor/skills.ts +97 -95
  90. package/src/doctor/tags.ts +44 -41
  91. package/src/hooks/codex-patch.ts +27 -24
  92. package/src/hooks/command-view.ts +44 -39
  93. package/src/hooks/common/constants.ts +0 -3
  94. package/src/hooks/common/types.ts +15 -1
  95. package/src/hooks/decision.ts +38 -42
  96. package/src/hooks/guard-git.ts +52 -50
  97. package/src/hooks/guard-manifest.ts +58 -55
  98. package/src/hooks/guard-outside.ts +109 -88
  99. package/src/hooks/guard-package.ts +86 -77
  100. package/src/hooks/guard-scripting.ts +20 -15
  101. package/src/hooks/guard-writes.ts +169 -111
  102. package/src/hooks/owner-reply.ts +128 -128
  103. package/src/hooks/post-tool.ts +94 -93
  104. package/src/hooks/project-guards.ts +93 -55
  105. package/src/hooks/project-tmp.ts +27 -24
  106. package/src/hooks/remote-hosts.ts +157 -149
  107. package/src/hooks/session-digest.ts +99 -95
  108. package/src/hooks/shell.ts +519 -500
  109. package/src/hooks/subagent-card.ts +11 -7
  110. package/src/hooks/trusted-scripts.ts +158 -80
  111. package/src/init/common/types.ts +1 -1
  112. package/src/init/scaffold.ts +137 -134
  113. package/src/local/clean.ts +39 -37
  114. package/src/local/format.ts +21 -17
  115. package/src/local/scan.ts +146 -140
  116. package/src/manifest/render.ts +127 -112
  117. package/src/owner/card.ts +51 -46
  118. package/src/owner/profile.ts +100 -96
  119. package/src/owner/reply-switch.ts +9 -6
  120. package/src/owner/shape.ts +72 -70
  121. package/src/owner/survey.ts +175 -164
  122. package/src/owner/view.ts +62 -59
  123. package/src/owner/violations.ts +119 -123
  124. package/src/router.ts +4 -1
  125. package/src/rules/base.ts +15 -11
  126. package/src/rules/common/types.ts +1 -1
  127. package/src/rules/parser.ts +39 -32
  128. package/src/rules/slots.ts +8 -6
  129. package/src/signals/claims.ts +30 -28
  130. package/src/signals/classify.ts +36 -33
  131. package/src/signals/loop.ts +39 -37
  132. package/src/signals/state.ts +80 -85
  133. package/src/skills/frontmatter.ts +28 -28
  134. package/src/sync/agent-files.ts +217 -199
  135. package/src/sync/agent-removal.ts +62 -68
  136. package/src/sync/atlas-block.ts +45 -43
  137. package/src/sync/base-rules.ts +32 -30
  138. package/src/sync/claude-launch.ts +74 -37
  139. package/src/sync/common/constants.ts +4 -0
  140. package/src/sync/common/index.ts +1 -0
  141. package/src/sync/common/symlink.ts +9 -0
  142. package/src/sync/common/types.ts +2 -2
  143. package/src/sync/exclude.ts +77 -69
  144. package/src/sync/local-choice.ts +50 -47
  145. package/src/sync/planner.ts +64 -68
  146. package/src/sync/prune.ts +52 -48
  147. package/src/sync/settings.ts +167 -168
  148. package/src/ui/capability.ts +12 -7
  149. package/src/ui/keyboard.ts +35 -33
  150. package/src/ui/prompt.ts +81 -77
  151. package/src/visualize/assets.ts +379 -195
  152. package/src/visualize/charts.ts +188 -176
  153. package/src/visualize/compare-css.ts +31 -0
  154. package/src/visualize/compare-render.ts +196 -0
  155. package/src/visualize/compare-schema.ts +81 -0
  156. package/src/visualize/compare-validate.ts +126 -0
  157. package/src/visualize/constants.ts +29 -3
  158. package/src/visualize/diagrams.ts +189 -174
  159. package/src/visualize/gate.ts +136 -0
  160. package/src/visualize/grid-span.ts +34 -0
  161. package/src/visualize/icons.ts +9 -4
  162. package/src/visualize/index.ts +2 -0
  163. package/src/visualize/kinds-css.ts +54 -0
  164. package/src/visualize/kinds-render.ts +698 -0
  165. package/src/visualize/kinds-schema.ts +148 -0
  166. package/src/visualize/kinds-validate.ts +186 -0
  167. package/src/visualize/labels-vi.ts +109 -0
  168. package/src/visualize/labels.ts +53 -0
  169. package/src/visualize/layout.ts +112 -92
  170. package/src/visualize/page.ts +140 -114
  171. package/src/visualize/render.ts +158 -114
  172. package/src/visualize/schema.ts +21 -1
  173. package/src/visualize/sections.ts +401 -309
  174. package/src/visualize/sources.ts +270 -0
  175. package/src/visualize/theme.ts +474 -0
  176. package/src/visualize/validate.ts +15 -5
  177. package/src/wiki/anchors.ts +39 -37
  178. package/src/wiki/command.ts +4 -4
  179. package/src/wiki/source-links.ts +49 -49
@@ -2,29 +2,28 @@ import { existsSync, readFileSync, statSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
3
  import type { TConstValue } from '../common/index.ts';
4
4
  import { ExitCodes } from '../common/index.ts';
5
- import { layoutFoldersOf } from '../common/layout-folder.ts';
5
+ import { LayoutFolder } from '../common/layout-folder.ts';
6
6
  import type { ILayout } from '../common/layout-folder.ts';
7
- import { loadConfig, PackageKinds, resolvePackages } from '../config/index.ts';
8
- import { locate, resolveApiUrl } from './add-app.ts';
7
+ import { ConfigLoader, LibraryKinds, PackageKinds, ProjectPackages } from '../config/index.ts';
8
+ import type { IProjectPackage, TLibraryKind } from '../config/index.ts';
9
+ import { AppScaffold } from './add-app.ts';
9
10
  import { AppSides, CreateConstants, CreateFlags, PresetDiffStatuses } from './common/index.ts';
10
11
  import type { ILocatedPreset, IRecordedPreset, IPresetSpec, TAppSide } from './common/index.ts';
11
- import { diffLines } from './diff.ts';
12
+ import { LineDiff } from './diff.ts';
12
13
  import type { ILineDiff } from './diff.ts';
13
- import { readFlag } from './names.ts';
14
- import {
15
- decodeText,
16
- locatePreset,
17
- parsePresetSpec,
18
- readJson,
19
- renderPresetFiles,
20
- } from './preset.ts';
14
+ import { LibPreset } from './lib-preset.ts';
15
+ import { ProjectNames } from './names.ts';
16
+ import { Preset } from './preset.ts';
21
17
  import type { IRenderedPresetFile } from './preset.ts';
22
- import { withScratch } from './scratch.ts';
23
- import { readPort } from './workspace.ts';
18
+ import { PresetScratch } from './scratch.ts';
19
+ import { PortRegistry } from './workspace.ts';
24
20
 
25
21
  const SUBCOMMAND = 'diff';
26
- const USAGE = `usage: vulcan preset ${SUBCOMMAND} <app> [--preset <name|file:path>] [--api <backend app> | --no-api] [--full] [--check]`;
22
+ const USAGE = `usage: vulcan preset ${SUBCOMMAND} <package> [--preset <name|file:path>] [--api <backend app> | --no-api] [--full] [--check]`;
27
23
  const API_URL_TOKEN = '{{apiUrl}}';
24
+ /** What the compared folder is called in the output. */
25
+ const APP_SUBJECT = 'app';
26
+ const PACKAGE_SUBJECT = 'package';
28
27
  /** Flags that take the next word as their value. */
29
28
  const VALUE_FLAGS = [CreateFlags.PRESET, CreateFlags.API];
30
29
 
@@ -39,121 +38,35 @@ const sideOf = (opts: { layout: ILayout; path: string }): TAppSide | undefined =
39
38
  const isIn = (side: { folders: string[] }): boolean =>
40
39
  side.folders.some((folder) => opts.path.startsWith(`${folder}/`));
41
40
 
42
- if (isIn({ folders: layoutFoldersOf({ value: opts.layout.backend }) })) {
41
+ if (isIn({ folders: LayoutFolder.layoutFoldersOf({ value: opts.layout.backend }) })) {
43
42
  return AppSides.BACKEND;
44
43
  }
45
44
 
46
- return isIn({ folders: layoutFoldersOf({ value: opts.layout.frontend }) })
45
+ return isIn({ folders: LayoutFolder.layoutFoldersOf({ value: opts.layout.frontend }) })
47
46
  ? AppSides.FRONTEND
48
47
  : undefined;
49
48
  };
50
49
 
51
50
  /** The npm package a preset spec stands for: the name in it, or the name inside the folder of a `file:` spec. */
52
51
  const packageNameOf = (opts: { spec: string; root: string }): string | undefined => {
53
- const parsed = parsePresetSpec({ value: opts.spec, cwd: opts.root });
52
+ const parsed = Preset.parseSpec({ value: opts.spec, cwd: opts.root });
54
53
 
55
54
  if (parsed.packageName !== undefined) {
56
55
  return parsed.packageName;
57
56
  }
58
57
 
59
- const name = readJson({
58
+ const name = Preset.readJson({
60
59
  file: join(parsed.range.slice(CreateConstants.PRESET_FILE_PREFIX.length), 'package.json'),
61
60
  })?.['name'];
62
61
 
63
62
  return typeof name === 'string' ? name : undefined;
64
63
  };
65
64
 
66
- /**
67
- * The recorded preset an app came from: `add` writes the preset's package into the app's dependencies,
68
- * and the config records the presets of the project, so the one of the app's side whose package the app
69
- * depends on is it. Records of one package under two specs (`api`, then `api@2`) are one preset.
70
- * Nothing else is guessed: no match, or two packages, asks for `--preset`.
71
- */
72
- export const detectPreset = (opts: {
73
- root: string;
74
- recorded: IRecordedPreset[];
75
- dependencies: string[];
76
- side: TAppSide;
77
- }): { ok: true; spec: string } | { ok: false; error: string } => {
78
- const matching = new Map<string, string>();
79
-
80
- for (const preset of opts.recorded) {
81
- const name = packageNameOf({ spec: preset.spec, root: opts.root });
82
-
83
- if (preset.side === opts.side && name !== undefined && opts.dependencies.includes(name)) {
84
- // The last record of a package wins: it is the newest spec `add` wrote.
85
- matching.set(name, preset.spec);
86
- }
87
- }
88
-
89
- const [only] = [...matching.values()];
90
-
91
- if (matching.size === 1 && only !== undefined) {
92
- return { ok: true, spec: only };
93
- }
94
-
95
- const known =
96
- opts.recorded.length === 0
97
- ? 'the config records no preset'
98
- : `recorded: ${opts.recorded.map((preset) => preset.spec).join(', ')}`;
99
-
100
- return {
101
- ok: false,
102
- error: `${matching.size === 0 ? "no recorded preset of the app's side is a dependency of the app" : 'more than one recorded preset fits the app'} (${known}) - say which with ${CreateFlags.PRESET} <name|file:path>`,
103
- };
104
- };
105
-
106
- export interface IPresetFileReport {
107
- path: string;
108
- status: TConstValue<typeof PresetDiffStatuses>;
109
- diff?: ILineDiff;
110
- /** Both files are not text, so there is a status and no diff. */
111
- isBinary?: boolean;
112
- /** The app has a folder where the preset has a file. */
113
- isFolder?: boolean;
114
- }
115
-
116
- /** Each file the preset makes, set against the file the app has at the same path. Reads only. */
117
- export const comparePresetFiles = (opts: {
118
- rendered: IRenderedPresetFile[];
119
- appDirectory: string;
120
- }): IPresetFileReport[] =>
121
- [...opts.rendered]
122
- .sort((first, second) => first.path.localeCompare(second.path))
123
- .map((file): IPresetFileReport => {
124
- const target = join(opts.appDirectory, file.path);
125
-
126
- if (!existsSync(target)) {
127
- return { path: file.path, status: PresetDiffStatuses.MISSING };
128
- }
129
-
130
- if (statSync(target).isDirectory()) {
131
- return { path: file.path, status: PresetDiffStatuses.DIFFERS, isFolder: true };
132
- }
133
-
134
- const current = readFileSync(target);
135
-
136
- if (current.equals(file.content)) {
137
- return { path: file.path, status: PresetDiffStatuses.SAME };
138
- }
139
-
140
- const currentText = decodeText({ content: current });
141
- const presetText = decodeText({ content: file.content });
142
-
143
- return currentText === undefined || presetText === undefined
144
- ? { path: file.path, status: PresetDiffStatuses.DIFFERS, isBinary: true }
145
- : {
146
- path: file.path,
147
- status: PresetDiffStatuses.DIFFERS,
148
- diff: diffLines({ current: currentText, preset: presetText }),
149
- };
150
- });
151
-
152
- const describeDifference = (opts: { report: IPresetFileReport }): string => {
65
+ const describeDifference = (opts: { report: IPresetFileReport; subject: string }): string => {
153
66
  const { diff, isBinary, isFolder } = opts.report;
154
67
 
155
68
  if (isFolder === true) {
156
- return '(the app has a folder here)';
69
+ return `(the ${opts.subject} has a folder here)`;
157
70
  }
158
71
 
159
72
  if (isBinary === true) {
@@ -175,6 +88,8 @@ const describeDifference = (opts: { report: IPresetFileReport }): string => {
175
88
 
176
89
  const printReport = (opts: {
177
90
  appPath: string;
91
+ /** What the folder is called in the output: `app`, or `package` for a library or a shared package. */
92
+ subject: string;
178
93
  located: ILocatedPreset;
179
94
  source: string;
180
95
  reports: IPresetFileReport[];
@@ -188,13 +103,16 @@ const printReport = (opts: {
188
103
  ];
189
104
 
190
105
  for (const report of reports) {
191
- const note = report.status === PresetDiffStatuses.DIFFERS ? describeDifference({ report }) : '';
106
+ const note =
107
+ report.status === PresetDiffStatuses.DIFFERS
108
+ ? describeDifference({ report, subject: opts.subject })
109
+ : '';
192
110
 
193
111
  lines.push(` ${report.status.padEnd(8)} ${report.path}${note === '' ? '' : ` ${note}`}`);
194
112
 
195
113
  if (opts.isFull && report.diff?.hunks !== undefined && report.diff.hunks.length > 0) {
196
114
  lines.push(
197
- ` --- ${opts.appPath}/${report.path} (the app)`,
115
+ ` --- ${opts.appPath}/${report.path} (the ${opts.subject})`,
198
116
  ` +++ ${report.path} (the preset)`,
199
117
  ...report.diff.hunks.flatMap((hunk) => hunk.split('\n').map((line) => ` ${line}`)),
200
118
  );
@@ -202,7 +120,7 @@ const printReport = (opts: {
202
120
  }
203
121
 
204
122
  lines.push(
205
- `${reports.length} file${reports.length === 1 ? '' : 's'}: ${countOf(PresetDiffStatuses.SAME)} same, ${countOf(PresetDiffStatuses.DIFFERS)} differ, ${countOf(PresetDiffStatuses.MISSING)} missing in the app`,
123
+ `${reports.length} file${reports.length === 1 ? '' : 's'}: ${countOf(PresetDiffStatuses.SAME)} same, ${countOf(PresetDiffStatuses.DIFFERS)} differ, ${countOf(PresetDiffStatuses.MISSING)} missing in the ${opts.subject}`,
206
124
  );
207
125
  process.stdout.write(`${lines.join('\n')}\n`);
208
126
  };
@@ -218,7 +136,7 @@ const readValue = (opts: {
218
136
  return { ok: true, value: undefined };
219
137
  }
220
138
 
221
- const value = readFlag({ args: opts.args, flag: opts.flag });
139
+ const value = ProjectNames.readFlag({ args: opts.args, flag: opts.flag });
222
140
 
223
141
  if (count > 1) {
224
142
  return { ok: false, error: `${opts.flag} is given more than once` };
@@ -231,176 +149,433 @@ const readValue = (opts: {
231
149
 
232
150
  /** The installed copy of an npm preset: in the app's own `node_modules` (bun's isolated linker) or the monorepo root's. */
233
151
  const locateInstalled = (opts: { spec: IPresetSpec; appDirectory: string; root: string }) => {
234
- const inApp = locatePreset({ spec: opts.spec, root: opts.appDirectory });
152
+ const inApp = Preset.locate({ spec: opts.spec, root: opts.appDirectory });
235
153
 
236
- return inApp.ok ? inApp : locatePreset({ spec: opts.spec, root: opts.root });
154
+ return inApp.ok ? inApp : Preset.locate({ spec: opts.spec, root: opts.root });
237
155
  };
238
156
 
239
- export const runPresetDiff = async (opts: { cwd: string; args: string[] }): Promise<number> => {
240
- const { cwd, args } = opts;
241
- const positionals = args.filter(
242
- (arg, index) => !arg.startsWith('-') && !VALUE_FLAGS.includes(args[index - 1] ?? ''),
243
- );
244
- const [subcommand, appName] = positionals;
245
-
246
- if (subcommand !== SUBCOMMAND || appName === undefined) {
247
- return fail({ message: USAGE });
248
- }
157
+ /** Finds the preset (the `--preset` value, else the detected spec) where it lives and hands it to `compare`. */
158
+ const locateAndCompare = async (opts: {
159
+ cwd: string;
160
+ flagValue: string | undefined;
161
+ detectedSpec: string | undefined;
162
+ /** The folder of the package being compared: an installed preset is looked for in its own `node_modules` first. */
163
+ packageDirectory: string;
164
+ compare: (found: { located: ILocatedPreset; source: string }) => Promise<number>;
165
+ }): Promise<number> => {
166
+ const { cwd, compare } = opts;
167
+ const value = opts.flagValue ?? opts.detectedSpec ?? '';
168
+ const spec = Preset.parseSpec({ value, cwd });
169
+ // `name@range` is fetched; a bare name, a detected spec or a `file:` folder is read where it already is.
170
+ const isFetched = opts.flagValue !== undefined && opts.flagValue.lastIndexOf('@') > 0;
249
171
 
250
- const presetFlag = readValue({ args, flag: CreateFlags.PRESET });
251
- const apiFlag = readValue({ args, flag: CreateFlags.API });
172
+ if (isFetched) {
173
+ return PresetScratch.withScratch({
174
+ root: cwd,
175
+ run: async (scratch) => {
176
+ const located = await AppScaffold.locate({ cwd, scratch, spec });
252
177
 
253
- if (!presetFlag.ok || !apiFlag.ok) {
254
- return fail({ message: !presetFlag.ok ? presetFlag.error : apiFlag.ok ? '' : apiFlag.error });
178
+ return located.ok
179
+ ? compare({
180
+ located: located.located,
181
+ source: `fetched ${spec.packageName}@${spec.range}`,
182
+ })
183
+ : fail({ message: located.error });
184
+ },
185
+ });
255
186
  }
256
187
 
257
- const loaded = await loadConfig({ root: cwd });
188
+ const located =
189
+ spec.packageName === undefined
190
+ ? Preset.locate({ spec, root: cwd })
191
+ : locateInstalled({ spec, appDirectory: opts.packageDirectory, root: cwd });
258
192
 
259
- if (!loaded.ok) {
193
+ if (!located.ok) {
260
194
  return fail({
261
- message:
262
- loaded.file === undefined
263
- ? 'run it at the root of a monorepo vulcan init created (no .configs/vulcan.config.*)'
264
- : loaded.error,
195
+ message: `${located.error}${spec.packageName === undefined ? '' : ` - run bun install, or give ${CreateFlags.PRESET} ${spec.packageName}@<range> to fetch it`}`,
265
196
  });
266
197
  }
267
198
 
268
- const { config } = loaded;
269
- const packages = resolvePackages({ config });
270
- const app = packages.find((entry) => entry.dir === appName || entry.path === appName);
199
+ return compare({
200
+ located: located.located,
201
+ source:
202
+ spec.packageName === undefined
203
+ ? `file:${spec.range.slice(CreateConstants.PRESET_FILE_PREFIX.length)}`
204
+ : 'installed in node_modules',
205
+ });
206
+ };
271
207
 
272
- if (config.layout === undefined || app === undefined) {
273
- const known = packages
274
- .filter((entry) => entry.kind !== PackageKinds.LIB)
275
- .map((entry) => entry.dir);
208
+ const PRESET_HINT = `say which with ${CreateFlags.PRESET} <name|file:path>`;
276
209
 
277
- return fail({
278
- message: `no app '${appName}' in the config packages${known.length === 0 ? '' : ` (apps: ${known.join(', ')})`}`,
279
- });
280
- }
210
+ const MANIFEST_FILE = 'package.json';
281
211
 
282
- const side = sideOf({ layout: config.layout, path: app.path });
212
+ /**
213
+ * The recorded preset a library or shared package is set against: the one recorded preset (a package counted
214
+ * once, as `PresetDiff.detect` does) whose record ships the package's kind. A package made by the shared kind
215
+ * never takes a lib kind and the reverse, so nothing falls back to the other kind.
216
+ */
217
+ const detectLibraryPreset = (opts: {
218
+ root: string;
219
+ recorded: IRecordedPreset[];
220
+ kind: TLibraryKind;
221
+ }): { ok: true; spec: string } | { ok: false; error: string } => {
222
+ const matching = new Map<string, string>();
223
+
224
+ for (const preset of opts.recorded) {
225
+ const ships = (opts.kind === LibraryKinds.SHARED ? preset.shared : preset.lib) !== undefined;
283
226
 
284
- if (side === undefined) {
285
- return fail({ message: `${app.path} is not in a backend or frontend folder of the layout` });
227
+ if (ships) {
228
+ // The last record of a package wins: it is the newest spec `add` wrote.
229
+ matching.set(
230
+ packageNameOf({ spec: preset.spec, root: opts.root }) ?? preset.spec,
231
+ preset.spec,
232
+ );
233
+ }
286
234
  }
287
235
 
288
- const appDirectory = join(cwd, app.path);
289
- const appManifest = readJson({ file: join(appDirectory, 'package.json') });
236
+ const [only] = [...matching.values()];
290
237
 
291
- if (appManifest === undefined) {
292
- return fail({ message: `${app.path}/package.json is missing or not JSON` });
238
+ if (matching.size === 1 && only !== undefined) {
239
+ return { ok: true, spec: only };
293
240
  }
294
241
 
295
- const dependencies = appManifest['dependencies'];
296
- const detected =
297
- presetFlag.value === undefined
298
- ? detectPreset({
299
- root: cwd,
300
- recorded: config.presets ?? [],
301
- dependencies: Object.keys(
302
- typeof dependencies === 'object' && dependencies !== null ? dependencies : {},
303
- ),
304
- side,
305
- })
306
- : undefined;
242
+ const known =
243
+ opts.recorded.length === 0
244
+ ? 'the config records no preset'
245
+ : `recorded: ${opts.recorded.map((preset) => preset.spec).join(', ')}`;
246
+
247
+ return {
248
+ ok: false,
249
+ error: `${matching.size === 0 ? `no recorded preset ships the ${opts.kind} kind` : `more than one recorded preset ships the ${opts.kind} kind`} (${known}) - ${PRESET_HINT}`,
250
+ };
251
+ };
252
+
253
+ /** The refusal for a name that is no package of the config: it lists the apps and the libraries there are. */
254
+ const reportNotFound = (opts: { packages: IProjectPackage[]; packageName: string }): number => {
255
+ const namesOf = (query: { isLibrary: boolean }): string[] =>
256
+ opts.packages
257
+ .filter((entry) => (entry.kind === PackageKinds.LIB) === query.isLibrary)
258
+ .map((entry) => entry.dir);
259
+ const apps = namesOf({ isLibrary: false });
260
+ const libraries = namesOf({ isLibrary: true });
261
+ const known = [
262
+ ...(apps.length === 0 ? [] : [`apps: ${apps.join(', ')}`]),
263
+ ...(libraries.length === 0 ? [] : [`libraries: ${libraries.join(', ')}`]),
264
+ ];
265
+
266
+ return fail({
267
+ message: `no app '${opts.packageName}' in the config packages${known.length === 0 ? '' : ` (${known.join('; ')})`}`,
268
+ });
269
+ };
270
+
271
+ export class PresetDiff {
272
+ /**
273
+ * `preset diff` of a package whose config entry has `kind: 'lib'`: the files of the preset kind that made it
274
+ * (`presetKind`, absent means `lib`), rendered with that kind's tokens, set against the package's folder.
275
+ */
276
+ private static async diffLibrary(opts: {
277
+ cwd: string;
278
+ args: string[];
279
+ library: IProjectPackage;
280
+ kind: TLibraryKind;
281
+ recorded: IRecordedPreset[];
282
+ configName: string | undefined;
283
+ presetValue: string | undefined;
284
+ }): Promise<number> {
285
+ const { cwd, args, library, kind } = opts;
286
+ const noun = kind === LibraryKinds.SHARED ? 'shared package' : 'library';
287
+
288
+ for (const flag of [CreateFlags.API, CreateFlags.NO_API]) {
289
+ if (args.includes(flag)) {
290
+ return fail({
291
+ message: `${library.dir} is a ${noun}: it has no proxy target, so ${flag} does not apply`,
292
+ });
293
+ }
294
+ }
295
+
296
+ const detected =
297
+ opts.presetValue === undefined
298
+ ? detectLibraryPreset({ root: cwd, recorded: opts.recorded, kind })
299
+ : undefined;
300
+
301
+ if (detected !== undefined && !detected.ok) {
302
+ return fail({ message: detected.error });
303
+ }
307
304
 
308
- if (detected !== undefined && !detected.ok) {
309
- return fail({ message: detected.error });
305
+ const rootManifest = Preset.readJson({ file: join(cwd, MANIFEST_FILE) });
306
+ const rootName = rootManifest?.['name'];
307
+ const project = opts.configName ?? (typeof rootName === 'string' ? rootName : library.dir);
308
+ const directory = join(cwd, library.path);
309
+
310
+ return locateAndCompare({
311
+ cwd,
312
+ flagValue: opts.presetValue,
313
+ detectedSpec: detected?.ok === true ? detected.spec : undefined,
314
+ packageDirectory: directory,
315
+ compare: async ({ located, source }) => {
316
+ const read = LibPreset.read({ located, kind });
317
+
318
+ if (!read.ok) {
319
+ return fail({ message: `${read.error} (${library.dir} is a ${noun})` });
320
+ }
321
+
322
+ // A package.json among the files is skipped: add replaces it with a generated one.
323
+ const rendered = Preset.renderFiles({
324
+ located,
325
+ files: read.lib.files,
326
+ tokens: { project, [kind]: library.dir, package: library.name },
327
+ }).filter((file) => file.path !== MANIFEST_FILE);
328
+ const reports = PresetDiff.compareFiles({ rendered, appDirectory: directory });
329
+
330
+ printReport({
331
+ appPath: library.path,
332
+ subject: PACKAGE_SUBJECT,
333
+ located,
334
+ source,
335
+ reports,
336
+ isFull: args.includes(CreateFlags.FULL),
337
+ });
338
+
339
+ return args.includes(CreateFlags.CHECK) &&
340
+ reports.some((report) => report.status !== PresetDiffStatuses.SAME)
341
+ ? ExitCodes.FAILURE
342
+ : ExitCodes.OK;
343
+ },
344
+ });
310
345
  }
311
346
 
312
- const rootManifest = readJson({ file: join(cwd, 'package.json') });
313
- const project =
314
- config.name ?? (typeof rootManifest?.['name'] === 'string' ? rootManifest['name'] : app.dir);
315
- const envFile = join(appDirectory, '.env.example');
316
- const ownPort = existsSync(envFile)
317
- ? readPort({ envExample: readFileSync(envFile, 'utf8') })
318
- : undefined;
347
+ /**
348
+ * The recorded preset an app came from: `add` writes the preset's package into the app's dependencies,
349
+ * and the config records the presets of the project, so the one of the app's side whose package the app
350
+ * depends on is it. Records of one package under two specs (`api`, then `api@2`) are one preset.
351
+ * Nothing else is guessed: no match, or two packages, asks for `--preset`.
352
+ */
353
+ static detect(opts: {
354
+ root: string;
355
+ recorded: IRecordedPreset[];
356
+ dependencies: string[];
357
+ side: TAppSide;
358
+ }): { ok: true; spec: string } | { ok: false; error: string } {
359
+ const matching = new Map<string, string>();
360
+
361
+ for (const preset of opts.recorded) {
362
+ const name = packageNameOf({ spec: preset.spec, root: opts.root });
363
+
364
+ if (preset.side === opts.side && name !== undefined && opts.dependencies.includes(name)) {
365
+ // The last record of a package wins: it is the newest spec `add` wrote.
366
+ matching.set(name, preset.spec);
367
+ }
368
+ }
369
+
370
+ const [only] = [...matching.values()];
319
371
 
320
- const compare = async (found: { located: ILocatedPreset; source: string }): Promise<number> => {
321
- const { located } = found;
322
- const tokens: Record<string, string> = {
323
- project,
324
- app: app.dir,
325
- appPath: app.path,
326
- devPort: String(ownPort ?? located.preset.devPort),
372
+ if (matching.size === 1 && only !== undefined) {
373
+ return { ok: true, spec: only };
374
+ }
375
+
376
+ const known =
377
+ opts.recorded.length === 0
378
+ ? 'the config records no preset'
379
+ : `recorded: ${opts.recorded.map((preset) => preset.spec).join(', ')}`;
380
+
381
+ return {
382
+ ok: false,
383
+ error: `${matching.size === 0 ? "no recorded preset of the app's side is a dependency of the app" : 'more than one recorded preset fits the app'} (${known}) - say which with ${CreateFlags.PRESET} <name|file:path>`,
327
384
  };
328
- let rendered = renderPresetFiles({ located, tokens });
329
- const usesApiUrl = rendered.some((file) =>
330
- (decodeText({ content: file.content }) ?? '').includes(API_URL_TOKEN),
385
+ }
386
+
387
+ /** Each file the preset makes, set against the file the app has at the same path. Reads only. */
388
+ static compareFiles(opts: {
389
+ rendered: IRenderedPresetFile[];
390
+ appDirectory: string;
391
+ }): IPresetFileReport[] {
392
+ return [...opts.rendered]
393
+ .sort((first, second) => first.path.localeCompare(second.path))
394
+ .map((file): IPresetFileReport => {
395
+ const target = join(opts.appDirectory, file.path);
396
+
397
+ if (!existsSync(target)) {
398
+ return { path: file.path, status: PresetDiffStatuses.MISSING };
399
+ }
400
+
401
+ if (statSync(target).isDirectory()) {
402
+ return { path: file.path, status: PresetDiffStatuses.DIFFERS, isFolder: true };
403
+ }
404
+
405
+ const current = readFileSync(target);
406
+
407
+ if (current.equals(file.content)) {
408
+ return { path: file.path, status: PresetDiffStatuses.SAME };
409
+ }
410
+
411
+ const currentText = Preset.decodeText({ content: current });
412
+ const presetText = Preset.decodeText({ content: file.content });
413
+
414
+ return currentText === undefined || presetText === undefined
415
+ ? { path: file.path, status: PresetDiffStatuses.DIFFERS, isBinary: true }
416
+ : {
417
+ path: file.path,
418
+ status: PresetDiffStatuses.DIFFERS,
419
+ diff: LineDiff.diff({ current: currentText, preset: presetText }),
420
+ };
421
+ });
422
+ }
423
+
424
+ static async run(opts: { cwd: string; args: string[] }): Promise<number> {
425
+ const { cwd, args } = opts;
426
+ const positionals = args.filter(
427
+ (arg, index) => !arg.startsWith('-') && !VALUE_FLAGS.includes(args[index - 1] ?? ''),
331
428
  );
429
+ const [subcommand, packageName] = positionals;
430
+
431
+ if (subcommand !== SUBCOMMAND || packageName === undefined) {
432
+ return fail({ message: USAGE });
433
+ }
434
+
435
+ const presetFlag = readValue({ args, flag: CreateFlags.PRESET });
436
+ const apiFlag = readValue({ args, flag: CreateFlags.API });
437
+
438
+ if (!presetFlag.ok || !apiFlag.ok) {
439
+ return fail({ message: !presetFlag.ok ? presetFlag.error : apiFlag.ok ? '' : apiFlag.error });
440
+ }
441
+
442
+ const loaded = await ConfigLoader.load({ root: cwd });
332
443
 
333
- if (usesApiUrl) {
334
- const api = await resolveApiUrl({
335
- root: cwd,
444
+ if (!loaded.ok) {
445
+ return fail({
446
+ message:
447
+ loaded.file === undefined
448
+ ? 'run it at the root of a monorepo vulcan init created (no .configs/vulcan.config.*)'
449
+ : loaded.error,
450
+ });
451
+ }
452
+
453
+ const { config } = loaded;
454
+ const packages = ProjectPackages.resolve({ config });
455
+ const app = packages.find((entry) => entry.dir === packageName || entry.path === packageName);
456
+
457
+ if (app === undefined) {
458
+ return reportNotFound({ packages, packageName });
459
+ }
460
+
461
+ if (app.kind === PackageKinds.LIB) {
462
+ return PresetDiff.diffLibrary({
463
+ cwd,
336
464
  args,
337
- interactive: false,
338
- backendFolders: layoutFoldersOf({ value: config.layout?.backend }),
339
- packages,
465
+ library: app,
466
+ kind: app.presetKind ?? LibraryKinds.LIB,
467
+ recorded: config.presets ?? [],
468
+ configName: config.name,
469
+ presetValue: presetFlag.value,
340
470
  });
471
+ }
341
472
 
342
- if (!api.ok) {
343
- return fail({
344
- message: `${api.error} (the files of this preset use the proxy target, as they did when add made the app)`,
345
- });
346
- }
473
+ if (config.layout === undefined) {
474
+ return reportNotFound({ packages, packageName });
475
+ }
476
+
477
+ const side = sideOf({ layout: config.layout, path: app.path });
347
478
 
348
- rendered = renderPresetFiles({ located, tokens: { ...tokens, apiUrl: api.apiUrl } });
479
+ if (side === undefined) {
480
+ return fail({ message: `${app.path} is not in a backend or frontend folder of the layout` });
349
481
  }
350
482
 
351
- const reports = comparePresetFiles({ rendered, appDirectory });
483
+ const appDirectory = join(cwd, app.path);
484
+ const appManifest = Preset.readJson({ file: join(appDirectory, 'package.json') });
352
485
 
353
- printReport({
354
- appPath: app.path,
355
- located,
356
- source: found.source,
357
- reports,
358
- isFull: args.includes(CreateFlags.FULL),
359
- });
486
+ if (appManifest === undefined) {
487
+ return fail({ message: `${app.path}/package.json is missing or not JSON` });
488
+ }
360
489
 
361
- return args.includes(CreateFlags.CHECK) &&
362
- reports.some((report) => report.status !== PresetDiffStatuses.SAME)
363
- ? ExitCodes.FAILURE
364
- : ExitCodes.OK;
365
- };
490
+ const dependencies = appManifest['dependencies'];
491
+ const detected =
492
+ presetFlag.value === undefined
493
+ ? PresetDiff.detect({
494
+ root: cwd,
495
+ recorded: config.presets ?? [],
496
+ dependencies: Object.keys(
497
+ typeof dependencies === 'object' && dependencies !== null ? dependencies : {},
498
+ ),
499
+ side,
500
+ })
501
+ : undefined;
502
+
503
+ if (detected !== undefined && !detected.ok) {
504
+ return fail({ message: detected.error });
505
+ }
366
506
 
367
- const value = presetFlag.value ?? (detected?.ok === true ? detected.spec : '');
368
- const spec = parsePresetSpec({ value, cwd });
369
- // `name@range` is fetched; a bare name, a detected spec or a `file:` folder is read where it already is.
370
- const isFetched = presetFlag.value !== undefined && presetFlag.value.lastIndexOf('@') > 0;
507
+ const rootManifest = Preset.readJson({ file: join(cwd, 'package.json') });
508
+ const project =
509
+ config.name ?? (typeof rootManifest?.['name'] === 'string' ? rootManifest['name'] : app.dir);
510
+ const envFile = join(appDirectory, '.env.example');
511
+ const ownPort = existsSync(envFile)
512
+ ? PortRegistry.read({ envExample: readFileSync(envFile, 'utf8') })
513
+ : undefined;
371
514
 
372
- if (isFetched) {
373
- return withScratch({
374
- root: cwd,
375
- run: async (scratch) => {
376
- const located = await locate({ cwd, scratch, spec });
515
+ const compare = async (found: { located: ILocatedPreset; source: string }): Promise<number> => {
516
+ const { located } = found;
517
+ const tokens: Record<string, string> = {
518
+ project,
519
+ app: app.dir,
520
+ appPath: app.path,
521
+ devPort: String(ownPort ?? located.preset.devPort),
522
+ };
523
+ let rendered = Preset.renderFiles({ located, tokens });
524
+ const usesApiUrl = rendered.some((file) =>
525
+ (Preset.decodeText({ content: file.content }) ?? '').includes(API_URL_TOKEN),
526
+ );
377
527
 
378
- return located.ok
379
- ? compare({
380
- located: located.located,
381
- source: `fetched ${spec.packageName}@${spec.range}`,
382
- })
383
- : fail({ message: located.error });
384
- },
385
- });
386
- }
528
+ if (usesApiUrl) {
529
+ const api = await AppScaffold.resolveApiUrl({
530
+ root: cwd,
531
+ args,
532
+ interactive: false,
533
+ backendFolders: LayoutFolder.layoutFoldersOf({ value: config.layout?.backend }),
534
+ packages,
535
+ });
387
536
 
388
- const located =
389
- spec.packageName === undefined
390
- ? locatePreset({ spec, root: cwd })
391
- : locateInstalled({ spec, appDirectory, root: cwd });
537
+ if (!api.ok) {
538
+ return fail({
539
+ message: `${api.error} (the files of this preset use the proxy target, as they did when add made the app)`,
540
+ });
541
+ }
392
542
 
393
- if (!located.ok) {
394
- return fail({
395
- message: `${located.error}${spec.packageName === undefined ? '' : ` - run bun install, or give ${CreateFlags.PRESET} ${spec.packageName}@<range> to fetch it`}`,
543
+ rendered = Preset.renderFiles({ located, tokens: { ...tokens, apiUrl: api.apiUrl } });
544
+ }
545
+
546
+ const reports = PresetDiff.compareFiles({ rendered, appDirectory });
547
+
548
+ printReport({
549
+ appPath: app.path,
550
+ subject: APP_SUBJECT,
551
+ located,
552
+ source: found.source,
553
+ reports,
554
+ isFull: args.includes(CreateFlags.FULL),
555
+ });
556
+
557
+ return args.includes(CreateFlags.CHECK) &&
558
+ reports.some((report) => report.status !== PresetDiffStatuses.SAME)
559
+ ? ExitCodes.FAILURE
560
+ : ExitCodes.OK;
561
+ };
562
+
563
+ return locateAndCompare({
564
+ cwd,
565
+ flagValue: presetFlag.value,
566
+ detectedSpec: detected?.ok === true ? detected.spec : undefined,
567
+ packageDirectory: appDirectory,
568
+ compare,
396
569
  });
397
570
  }
571
+ }
398
572
 
399
- return compare({
400
- located: located.located,
401
- source:
402
- spec.packageName === undefined
403
- ? `file:${spec.range.slice(CreateConstants.PRESET_FILE_PREFIX.length)}`
404
- : 'installed in node_modules',
405
- });
406
- };
573
+ interface IPresetFileReport {
574
+ path: string;
575
+ status: TConstValue<typeof PresetDiffStatuses>;
576
+ diff?: ILineDiff;
577
+ /** Both files are not text, so there is a status and no diff. */
578
+ isBinary?: boolean;
579
+ /** The app has a folder where the preset has a file. */
580
+ isFolder?: boolean;
581
+ }