anhedral 0.10.1 → 0.11.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 (183) hide show
  1. package/README.md +79 -124
  2. package/assets/patches/LICENSE.braces +21 -0
  3. package/assets/patches/LICENSE.node-forge +50 -0
  4. package/assets/patches/audit-deps.mjs +167 -0
  5. package/assets/patches/braces@3.0.3.patch +127 -0
  6. package/assets/patches/node-forge@1.4.0.patch +41 -0
  7. package/dist/auth-schema.js +3 -3
  8. package/dist/bin.js +284 -163
  9. package/dist/capabilities.d.ts +4 -4
  10. package/dist/capabilities.js +6 -2
  11. package/dist/capability-contract.d.ts +47 -0
  12. package/dist/capability-contract.js +153 -0
  13. package/dist/catalog-model.d.ts +24 -0
  14. package/dist/catalog-model.js +1 -0
  15. package/dist/catalog-registration.d.ts +16 -0
  16. package/dist/catalog-registration.js +22 -0
  17. package/dist/catalog-snapshot.d.ts +5 -0
  18. package/dist/catalog-snapshot.js +97 -0
  19. package/dist/cli-arguments.d.ts +16 -0
  20. package/dist/cli-arguments.js +115 -0
  21. package/dist/cli-output.d.ts +8 -0
  22. package/dist/cli-output.js +236 -0
  23. package/dist/cloudflare.d.ts +14 -3
  24. package/dist/cloudflare.js +196 -36
  25. package/dist/command-schema.d.ts +21 -0
  26. package/dist/command-schema.js +418 -0
  27. package/dist/delivery.d.ts +12 -5
  28. package/dist/delivery.js +173 -39
  29. package/dist/dependencies.d.ts +24 -0
  30. package/dist/dependencies.js +48 -0
  31. package/dist/dependency-patches.d.ts +7 -0
  32. package/dist/dependency-patches.js +125 -0
  33. package/dist/index.d.ts +26 -1
  34. package/dist/index.js +17 -1
  35. package/dist/inspector-model.d.ts +123 -0
  36. package/dist/inspector-model.js +1 -0
  37. package/dist/integration-service-readers.d.ts +13 -0
  38. package/dist/integration-service-readers.js +173 -0
  39. package/dist/lifecycle-model.d.ts +15 -0
  40. package/dist/lifecycle-model.js +20 -0
  41. package/dist/lifecycle.d.ts +11 -0
  42. package/dist/lifecycle.js +91 -0
  43. package/dist/mobile-delivery.d.ts +100 -0
  44. package/dist/mobile-delivery.js +319 -0
  45. package/dist/neon-service-data.d.ts +8 -0
  46. package/dist/neon-service-data.js +117 -0
  47. package/dist/platforms/mobile.js +8 -5
  48. package/dist/pnpm-policy.d.ts +2 -2
  49. package/dist/pnpm-policy.js +19 -45
  50. package/dist/project-catalog.d.ts +41 -0
  51. package/dist/project-catalog.js +288 -0
  52. package/dist/project-config.d.ts +14 -0
  53. package/dist/project-config.js +89 -0
  54. package/dist/project-inspector.d.ts +4 -0
  55. package/dist/project-inspector.js +702 -0
  56. package/dist/project-lifecycle.d.ts +25 -0
  57. package/dist/project-lifecycle.js +57 -0
  58. package/dist/project-state.d.ts +22 -1
  59. package/dist/project-state.js +361 -27
  60. package/dist/provider-auth.d.ts +41 -0
  61. package/dist/provider-auth.js +209 -0
  62. package/dist/provider-readiness.js +27 -10
  63. package/dist/providers/adapters.d.ts +17 -0
  64. package/dist/providers/adapters.js +272 -0
  65. package/dist/providers/api.d.ts +29 -0
  66. package/dist/providers/api.js +253 -0
  67. package/dist/providers/config.d.ts +15 -0
  68. package/dist/providers/config.js +182 -0
  69. package/dist/providers/definitions.d.ts +318 -0
  70. package/dist/providers/definitions.js +127 -0
  71. package/dist/providers/provision.d.ts +24 -0
  72. package/dist/providers/provision.js +76 -0
  73. package/dist/providers/receipts.d.ts +20 -0
  74. package/dist/providers/receipts.js +66 -0
  75. package/dist/providers/recovery-verification.d.ts +7 -0
  76. package/dist/providers/recovery-verification.js +112 -0
  77. package/dist/providers/recovery.d.ts +30 -0
  78. package/dist/providers/recovery.js +34 -0
  79. package/dist/providers/runtime.d.ts +10 -0
  80. package/dist/providers/runtime.js +254 -0
  81. package/dist/providers/schema.d.ts +28 -0
  82. package/dist/providers/schema.js +49 -0
  83. package/dist/providers/state.d.ts +55 -0
  84. package/dist/providers/state.js +289 -0
  85. package/dist/provision.d.ts +10 -1
  86. package/dist/provision.js +91 -4
  87. package/dist/r2-service-data.d.ts +2 -0
  88. package/dist/r2-service-data.js +136 -0
  89. package/dist/readiness.js +9 -13
  90. package/dist/registry/add.d.ts +6 -0
  91. package/dist/registry/add.js +93 -22
  92. package/dist/registry/commands.d.ts +3 -2
  93. package/dist/registry/commands.js +52 -15
  94. package/dist/registry/options.d.ts +1 -1
  95. package/dist/registry/options.js +5 -4
  96. package/dist/registry/preview.d.ts +11 -0
  97. package/dist/registry/preview.js +91 -0
  98. package/dist/registry/receipt.d.ts +1 -0
  99. package/dist/registry/receipt.js +19 -4
  100. package/dist/registry/resolve.js +5 -1
  101. package/dist/registry/usage.d.ts +10 -0
  102. package/dist/registry/usage.js +18 -37
  103. package/dist/render.d.ts +2 -0
  104. package/dist/render.js +6 -0
  105. package/dist/runtime-policy.d.ts +4 -0
  106. package/dist/runtime-policy.js +21 -0
  107. package/dist/scaffold/auth.js +3 -19
  108. package/dist/scaffold/bootstrap.js +2 -2
  109. package/dist/scaffold/compose.js +9 -3
  110. package/dist/scaffold/database.js +107 -25
  111. package/dist/scaffold/documentation.js +18 -13
  112. package/dist/scaffold/lint.d.ts +4 -0
  113. package/dist/scaffold/lint.js +56 -0
  114. package/dist/scaffold/neon-realtime.d.ts +2 -0
  115. package/dist/scaffold/neon-realtime.js +97 -0
  116. package/dist/scaffold/stack-documentation.js +1 -1
  117. package/dist/scaffold/void.d.ts +4 -0
  118. package/dist/scaffold/void.js +256 -0
  119. package/dist/scaffold/web.js +7 -1
  120. package/dist/scaffold/workspace.js +127 -25
  121. package/dist/service-deletion.d.ts +29 -0
  122. package/dist/service-deletion.js +195 -0
  123. package/dist/service-descriptor.d.ts +10 -0
  124. package/dist/service-descriptor.js +78 -0
  125. package/dist/service-model.d.ts +49 -0
  126. package/dist/service-model.js +8 -0
  127. package/dist/service-operations.d.ts +29 -0
  128. package/dist/service-operations.js +78 -0
  129. package/dist/service-readers.d.ts +8 -0
  130. package/dist/service-readers.js +247 -0
  131. package/dist/services-command.d.ts +39 -0
  132. package/dist/services-command.js +100 -0
  133. package/dist/ship.d.ts +348 -0
  134. package/dist/ship.js +237 -0
  135. package/dist/stack-registry.d.ts +4 -2
  136. package/dist/stack-registry.js +48 -12
  137. package/dist/standard.d.ts +2 -1
  138. package/dist/standard.js +33 -14
  139. package/dist/transaction.d.ts +2 -0
  140. package/dist/transaction.js +10 -0
  141. package/dist/util.js +17 -2
  142. package/dist/vercel.d.ts +5 -3
  143. package/dist/vercel.js +96 -14
  144. package/dist/version.d.ts +1 -1
  145. package/dist/version.js +1 -1
  146. package/dist/vinext.d.ts +1 -0
  147. package/dist/vinext.js +13 -1
  148. package/dist/void-execution.d.ts +10 -0
  149. package/dist/void-execution.js +94 -0
  150. package/dist/void-migrations.d.ts +6 -0
  151. package/dist/void-migrations.js +110 -0
  152. package/dist/void-state.d.ts +16 -0
  153. package/dist/void-state.js +65 -0
  154. package/dist/void.d.ts +3 -0
  155. package/dist/void.js +5 -0
  156. package/docs/cli-design.md +67 -0
  157. package/docs/delivery-workflow.md +32 -17
  158. package/docs/plugin-ui.md +102 -0
  159. package/docs/provider-configuration.md +116 -0
  160. package/docs/stack-standard.md +175 -0
  161. package/docs/void-verification.md +185 -0
  162. package/package.json +29 -23
  163. package/assets/anhedral-cli-init-technical.svg +0 -322
  164. package/assets/anhedral-cli-init.svg +0 -322
  165. package/assets/anhedral-mark.svg +0 -4
  166. package/assets/anhedral.svg +0 -4
  167. package/assets/favicon.ico +0 -0
  168. package/assets/security/LICENSES.txt +0 -63
  169. package/assets/security/audit-deps.mjs +0 -300
  170. package/assets/security/braces-regression.mjs +0 -102
  171. package/assets/security/braces@3.0.3.patch +0 -285
  172. package/assets/security/decode-uri-component@0.2.2.patch +0 -149
  173. package/assets/security/decoder-regression.mjs +0 -37
  174. package/assets/security/forge-regression.mjs +0 -46
  175. package/assets/security/manifest.json +0 -53
  176. package/assets/security/node-forge@1.4.0.patch +0 -26
  177. package/dist/managed-hosting.d.ts +0 -49
  178. package/dist/managed-hosting.js +0 -373
  179. package/dist/security-backports.d.ts +0 -3
  180. package/dist/security-backports.js +0 -26
  181. package/docs/application-stack-standard.md +0 -104
  182. package/docs/managed-hosting-architecture.md +0 -87
  183. package/docs/sponsorships.md +0 -25
package/dist/readiness.js CHANGED
@@ -1,4 +1,4 @@
1
- import { readBoundedFile, MAX_PROJECT_JSON_BYTES } from './bounded-file.js';
1
+ import { readProjectSection } from './project-config.js';
2
2
  import { existsSync } from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { isDeepStrictEqual } from 'node:util';
@@ -9,22 +9,19 @@ import { STANDARD_PRODUCTS } from './stack-registry.js';
9
9
  export function inspectProject(root) {
10
10
  const checks = [];
11
11
  const record = (id, ok, detail) => checks.push({ id, ok, detail });
12
- const read = (file) => JSON.parse(readBoundedFile(path.join(root, file), MAX_PROJECT_JSON_BYTES).toString('utf8'));
13
12
  record('workspace', existsSync(path.join(root, 'pnpm-workspace.yaml')), 'pnpm workspace manifest');
14
13
  record('lockfile', existsSync(path.join(root, 'pnpm-lock.yaml')), 'Committed dependency resolution required');
15
14
  try {
16
- const plan = read('anhedral.setup.json');
15
+ const plan = readProjectSection(root, 'setup');
17
16
  const recordedVersion = plan?.cliVersion;
18
- const compatible = recordedVersion === CAPABILITY_REGISTRY.cliVersion;
19
- record('cli-compatibility', compatible, /^\d+\.\d+\.\d+$/.test(recordedVersion ?? '')
20
- ? `Use anhedral@${recordedVersion} for this project or review upgrade differences`
21
- : 'Use the recorded project CLI version or review upgrade differences');
17
+ const current = recordedVersion === CAPABILITY_REGISTRY.cliVersion;
18
+ record('cli-version', current, `Project configuration must be generated by anhedral@${CAPABILITY_REGISTRY.cliVersion}.`);
22
19
  validateSetupPlan(plan);
23
- const standard = read('anhedral.standard.json');
20
+ const standard = readProjectSection(root, 'standard');
24
21
  record('setup-plan', true, `Requirements recorded by CLI ${plan.cliVersion}`);
25
22
  try {
26
- const installed = read('anhedral.registry.json');
27
- const { status, workspaces: _workspaces, files: _files, resourcesProvisioned, ...snapshot } = installed;
23
+ const installed = readProjectSection(root, 'registry');
24
+ const { status, workspaces: _workspaces, files: _files, configuration: _configuration, resourcesProvisioned, ...snapshot } = installed;
28
25
  if (status !== 'scaffolded' ||
29
26
  resourcesProvisioned !== false ||
30
27
  !isDeepStrictEqual(snapshot, plan.registry))
@@ -73,9 +70,8 @@ export function validateSetupPlan(plan) {
73
70
  value.registryVersion !== 1 ||
74
71
  typeof value.cliVersion !== 'string')
75
72
  throw new Error('Unsupported setup plan version.');
76
- if (/^\d+\.\d+\.\d+$/.test(value.cliVersion) &&
77
- value.cliVersion !== CAPABILITY_REGISTRY.cliVersion)
78
- throw new Error(`Use anhedral@${value.cliVersion} for this project or review upgrade differences.`);
73
+ if (value.cliVersion !== CAPABILITY_REGISTRY.cliVersion)
74
+ throw new Error(`Project configuration must be generated by anhedral@${CAPABILITY_REGISTRY.cliVersion}.`);
79
75
  if (!Array.isArray(value.products) ||
80
76
  !value.products.length ||
81
77
  !value.products.every((id) => STANDARD_PRODUCTS.includes(id)))
@@ -1,11 +1,17 @@
1
1
  import type { StandardRunner } from './types.js';
2
+ import { type SourcePreview } from './preview.js';
2
3
  export interface AddRequest {
3
4
  items: string[];
4
5
  dryRun?: boolean;
5
6
  skipInstall?: boolean;
7
+ preview?: {
8
+ mode: 'diff' | 'view';
9
+ path?: string;
10
+ };
6
11
  }
7
12
  /** Add recipes to an initialized workspace, refusing edits to customer-owned source. */
8
13
  export declare function addStackItems(root: string, request: AddRequest, run?: StandardRunner): Promise<{
14
+ previews?: SourcePreview[] | undefined;
9
15
  schemaVersion: number;
10
16
  root: string;
11
17
  dryRun: boolean;
@@ -1,9 +1,10 @@
1
+ import { PROJECT_CONFIG_FILE, readProjectSection, writeProjectSection, hasProjectSection, } from '../project-config.js';
2
+ import { configureDependencyPatches } from '../dependency-patches.js';
1
3
  import { readBoundedFile, MAX_PROJECT_JSON_BYTES } from '../bounded-file.js';
2
- import { configureSecurityBackports } from '../security-backports.js';
3
4
  import { bootstrapWorkspace, assertWorkspaceRuntime } from '../scaffold/bootstrap.js';
4
5
  import { registerApplication } from '../project-state.js';
5
6
  import { registerVercelApplication } from '../vercel.js';
6
- import { existsSync, readFileSync, realpathSync } from 'node:fs';
7
+ import { existsSync, lstatSync, readFileSync, realpathSync, rmSync } from 'node:fs';
7
8
  import path from 'node:path';
8
9
  import { isDeepStrictEqual } from 'node:util';
9
10
  import { applyEdits, modify, parse } from 'jsonc-parser';
@@ -13,38 +14,64 @@ import { GENERATOR_VERSION } from '../version.js';
13
14
  import { runStagedTransaction } from '../transaction.js';
14
15
  import { inspectWorkspaceGraph } from '../workspace-graph.js';
15
16
  import { execFile } from '../util.js';
16
- import { json, put, readJson } from '../scaffold/files.js';
17
+ import { supportsVoidRuntime, usesVoidSelection } from '../runtime-policy.js';
18
+ import { put } from '../scaffold/files.js';
17
19
  import { writeStandardRoot } from '../scaffold/workspace.js';
20
+ import { configureVoidDelivery, refreshVoidEnvironment } from '../scaffold/void.js';
18
21
  import { createRecipeContext } from './context.js';
19
22
  import { resolveStackRegistry, resolveStandardProducts } from './resolve.js';
20
- import { sourceFiles } from './receipt.js';
23
+ import { sourceFiles, configurationFingerprints } from './receipt.js';
24
+ import { sourcePreview, validatePreviewPath, MAX_PREVIEW_TOTAL_BYTES, } from './preview.js';
21
25
  /** Add recipes to an initialized workspace, refusing edits to customer-owned source. */
22
26
  export async function addStackItems(root, request, run = execFile) {
23
27
  for (const key of Object.keys(request))
24
- if (!['items', 'dryRun', 'skipInstall'].includes(key))
28
+ if (!['items', 'dryRun', 'skipInstall', 'preview'].includes(key))
25
29
  throw new Error(`Unknown add option: ${key}. Only bundled registry items are supported.`);
30
+ if (request.preview) {
31
+ if (!request.dryRun ||
32
+ !['diff', 'view'].includes(request.preview.mode) ||
33
+ Object.keys(request.preview).some((key) => !['mode', 'path'].includes(key)))
34
+ throw new Error('Source previews require dry-run and one mode: diff or view.');
35
+ if (request.preview.path !== undefined)
36
+ validatePreviewPath(request.preview.path);
37
+ }
26
38
  if (!request.dryRun)
27
39
  assertWorkspaceRuntime(run);
28
40
  root = realpathSync(root);
29
41
  if (!request.items.length)
30
42
  throw new Error('Select at least one registry item.');
31
- const plan = readJson(root, 'anhedral.setup.json');
43
+ const plan = readProjectSection(root, 'setup');
32
44
  validateSetupPlan(plan);
33
45
  if (plan.cliVersion !== GENERATOR_VERSION)
34
46
  throw new Error('Use the project CLI version before adding recipes.');
35
47
  if (!inspectProject(root).localReady)
36
48
  throw new Error('Run doctor and resolve project provenance or workspace errors before add.');
37
- const receipt = readJson(root, 'anhedral.registry.json');
49
+ const receipt = readProjectSection(root, 'registry');
38
50
  if (!receipt.files || typeof receipt.files !== 'object' || Array.isArray(receipt.files))
39
- throw new Error('This project has no scaffold fingerprints; migrate it deliberately before using add.');
51
+ throw new Error('Add requires current scaffold fingerprints.');
40
52
  const baseline = receipt.files;
53
+ if (!receipt.configuration ||
54
+ typeof receipt.configuration !== 'object' ||
55
+ Array.isArray(receipt.configuration))
56
+ throw new Error('Add requires current configuration fingerprints.');
57
+ const originalConfiguration = configurationFingerprints(root);
41
58
  const selected = new Set(plan.products);
42
59
  for (const id of request.items) {
43
60
  if (!STANDARD_PRODUCTS.includes(id))
44
61
  throw new Error(`Unknown stack product: ${id}.`);
45
62
  selected.add(id);
46
63
  }
64
+ if ((selected.has('queues') || selected.has('basin')) &&
65
+ hasProjectSection(root, 'cloudflare') &&
66
+ readProjectSection(root, 'cloudflare').deliveryEngine === 'void')
67
+ throw new Error('Queues with dead-letter recovery and Basin require Wrangler delivery. They cannot be added to a Void project.');
47
68
  resolveStandardProducts(selected, plan.hosting, false);
69
+ const voidSelected = usesVoidSelection([...selected], plan.hosting);
70
+ if (!request.dryRun &&
71
+ voidSelected &&
72
+ run === execFile &&
73
+ !supportsVoidRuntime(process.versions.node))
74
+ throw new Error('Cloudflare workspaces using Void require Node.js 24.21.0 or newer.');
48
75
  const options = {
49
76
  root,
50
77
  name: plan.name ?? path.basename(root),
@@ -62,10 +89,10 @@ export async function addStackItems(root, request, run = execFile) {
62
89
  for (const item of registry.items) {
63
90
  const before = oldItems.get(item.name);
64
91
  if (before && before.targets.some((target) => !item.targets.includes(target)))
65
- throw new Error(`Adding this selection relocates ${item.name}; migrate its existing source explicitly.`);
92
+ throw new Error(`Adding this selection relocates ${item.name}; additions must preserve existing runtime ownership.`);
66
93
  }
67
94
  const before = sourceFiles(root);
68
- const receiptText = readBoundedFile(path.join(root, 'anhedral.registry.json'), MAX_PROJECT_JSON_BYTES).toString('utf8');
95
+ const receiptText = readBoundedFile(path.join(root, PROJECT_CONFIG_FILE), MAX_PROJECT_JSON_BYTES).toString('utf8');
69
96
  const commitPaths = [];
70
97
  const conflicts = [];
71
98
  const result = {
@@ -81,17 +108,20 @@ export async function addStackItems(root, request, run = execFile) {
81
108
  targets: recipes.flatMap((item) => item.targets),
82
109
  files: commitPaths,
83
110
  conflicts,
111
+ ...(request.preview ? { previews: [] } : {}),
84
112
  };
85
113
  // The upstream web generator requires network access and executes package scripts.
86
114
  // A preview reports the resolved selection without invoking that generator.
87
115
  if (request.dryRun && result.bootstrapRequired) {
88
116
  result.filesChecked = false;
117
+ if (request.preview)
118
+ throw new Error('Source preview requires a new web bootstrap and cannot run offline. Use add --dry-run for the selection plan.');
89
119
  return result;
90
120
  }
91
121
  await runStagedTransaction(root, {
92
122
  dryRun: !!request.dryRun,
93
123
  commitPaths,
94
- seedPaths: [...before.keys(), 'anhedral.registry.json'],
124
+ seedPaths: [...before.keys(), PROJECT_CONFIG_FILE],
95
125
  build: async (stage) => {
96
126
  const context = createRecipeContext(stage, options);
97
127
  for (const item of registry.items)
@@ -104,7 +134,8 @@ export async function addStackItems(root, request, run = execFile) {
104
134
  // Configuration items affect the existing runtime without regenerating its application source.
105
135
  const configurationItems = registry.items.filter((item) => !isDeepStrictEqual(oldItems.get(item.name), item) && item.bindings);
106
136
  if (configurationItems.length) {
107
- const file = `apps/${context.runtimeApp}/wrangler.jsonc`;
137
+ const directory = `apps/${context.runtimeApp}`;
138
+ const file = `${directory}/${existsSync(path.join(stage, directory, 'anhedral.cloudflare.json')) ? 'anhedral.cloudflare.json' : 'wrangler.jsonc'}`;
108
139
  let content = readFileSync(path.join(stage, file), 'utf8');
109
140
  const config = parse(content);
110
141
  for (const item of configurationItems)
@@ -118,48 +149,88 @@ export async function addStackItems(root, request, run = execFile) {
118
149
  put(stage, file, content);
119
150
  }
120
151
  writeStandardRoot(stage, options, registry, true);
152
+ if (voidSelected) {
153
+ configureVoidDelivery(stage);
154
+ refreshVoidEnvironment(stage);
155
+ }
121
156
  if (options.products.includes('next') && options.hosting === 'vercel')
122
157
  registerVercelApplication(stage);
123
- if ([...sourceFiles(stage).keys()].some((file) => /^apps\/[^/]+\/wrangler\.jsonc$/.test(file)))
158
+ if ([...sourceFiles(stage).keys()].some((file) => /^apps\/[^/]+\/(?:wrangler\.jsonc|anhedral\.cloudflare\.json)$/.test(file)))
124
159
  registerApplication(stage, true);
125
160
  if (!request.dryRun)
126
161
  run('pnpm', ['install', '--lockfile-only', '--no-frozen-lockfile', '--ignore-scripts'], stage);
127
- if (!request.dryRun && configureSecurityBackports(stage))
162
+ if (!request.dryRun && configureDependencyPatches(stage))
128
163
  run('pnpm', ['install', '--lockfile-only', '--no-frozen-lockfile', '--ignore-scripts'], stage);
129
164
  const after = sourceFiles(stage);
130
165
  const files = { ...baseline };
131
166
  for (const [file, hash] of after) {
132
167
  if (before.get(file) === hash)
133
168
  continue;
134
- if (before.has(file) &&
135
- baseline[file] !== before.get(file) &&
136
- file !== 'anhedral.project.json')
169
+ if (before.has(file) && baseline[file] !== before.get(file))
137
170
  conflicts.push(file);
138
171
  commitPaths.push(file);
139
172
  files[file] = hash;
140
173
  }
174
+ const configuration = configurationFingerprints(stage);
175
+ for (const [section, hash] of Object.entries(originalConfiguration)) {
176
+ // Hosting registration preserves existing user fields while adding new targets.
177
+ if (section !== 'cloudflare' &&
178
+ hash !== receipt.configuration[section] &&
179
+ configuration[section] !== hash)
180
+ conflicts.push(`${PROJECT_CONFIG_FILE} (${section})`);
181
+ }
141
182
  // Never delete preexisting source as a side effect of an addition.
142
183
  for (const file of before.keys())
143
184
  if (!after.has(file))
144
185
  conflicts.push(file);
145
186
  if (conflicts.length && !request.dryRun)
146
187
  throw new Error(`Addition conflicts with edited or untracked source: ${conflicts.join(', ')}. No files were installed.`);
147
- json(stage, 'anhedral.registry.json', {
188
+ writeProjectSection(stage, 'registry', {
148
189
  ...registry,
149
190
  status: 'scaffolded',
150
191
  resourcesProvisioned: false,
151
192
  workspaces: inspectWorkspaceGraph(stage),
152
193
  files,
194
+ configuration,
153
195
  });
154
- commitPaths.push('anhedral.registry.json');
196
+ commitPaths.push(PROJECT_CONFIG_FILE);
197
+ if (request.preview && result.previews) {
198
+ const preview = request.preview;
199
+ const selected = [...commitPaths]
200
+ .filter((file) => !preview.path || preview.path === file)
201
+ .sort();
202
+ if (preview.path && !selected.length)
203
+ throw new Error('Requested path is not a changed generated source file.');
204
+ let total = 0;
205
+ for (const file of selected) {
206
+ const content = sourcePreview(root, stage, file, preview.mode);
207
+ total += Buffer.byteLength(JSON.stringify(content));
208
+ if (total > MAX_PREVIEW_TOTAL_BYTES)
209
+ throw new Error('Source preview exceeds 1 MiB. Select a single file with --diff <path> or --view <path>.');
210
+ result.previews.push(content);
211
+ }
212
+ }
155
213
  // Detect concurrent changes even to source that this addition would otherwise preserve.
156
214
  if (!isDeepStrictEqual(sourceFiles(root), before) ||
157
- readBoundedFile(path.join(root, 'anhedral.registry.json'), MAX_PROJECT_JSON_BYTES).toString('utf8') !== receiptText)
215
+ readBoundedFile(path.join(root, PROJECT_CONFIG_FILE), MAX_PROJECT_JSON_BYTES).toString('utf8') !== receiptText)
158
216
  throw new Error('Workspace changed during addition; retry after reviewing source.');
159
217
  },
160
218
  afterCommit: () => {
161
- if (!request.skipInstall)
162
- run('pnpm', ['install', '--frozen-lockfile'], root);
219
+ if (request.skipInstall)
220
+ return;
221
+ const lockPath = path.join(root, 'pnpm-lock.yaml');
222
+ const lock = readBoundedFile(lockPath, 16 * 1024 * 1024);
223
+ const modules = path.join(root, 'node_modules');
224
+ const metadata = lstatSync(modules, { throwIfNoEntry: false });
225
+ if (metadata && (!metadata.isDirectory() || metadata.isSymbolicLink()))
226
+ throw new Error('Dependency installation requires a real project node_modules directory.');
227
+ // pnpm 10 can retain skipped optional packages after a new recipe makes
228
+ // them required. Rebuild generated links from the reviewed lock while
229
+ // retaining the separate content-addressed package store.
230
+ rmSync(modules, { recursive: true, force: true });
231
+ run('pnpm', ['install', '--frozen-lockfile'], root);
232
+ if (!readBoundedFile(lockPath, 16 * 1024 * 1024).equals(lock))
233
+ throw new Error('Frozen dependency installation changed the reviewed lockfile; review it before continuing.');
163
234
  },
164
235
  });
165
236
  return result;
@@ -1,2 +1,3 @@
1
- export declare function runRegistry(args: string[], json: boolean): Promise<void>;
2
- export declare function runAdd(args: string[]): Promise<void>;
1
+ import { type OutputOptions } from '../cli-output.js';
2
+ export declare function runRegistry(args: string[], json: boolean, output?: OutputOptions): Promise<void>;
3
+ export declare function runAdd(args: string[], output?: OutputOptions): Promise<void>;
@@ -1,16 +1,27 @@
1
- import path from 'node:path';
1
+ import { CAPABILITY_CONTRACT, formatCapabilityContract } from '../capability-contract.js';
2
2
  import { addStackItems } from './add.js';
3
- import { STACK_REGISTRY, getStackItem } from '../stack-registry.js';
4
- export async function runRegistry(args, json) {
3
+ import { STACK_REGISTRY, STANDARD_PRODUCTS, getStackItem } from '../stack-registry.js';
4
+ import { printResult } from '../cli-output.js';
5
+ import { commandHelp } from './usage.js';
6
+ import { CliArgumentError, suggest } from '../cli-arguments.js';
7
+ export async function runRegistry(args, json, output = { json }) {
5
8
  const positional = args.filter((arg) => arg !== '--json');
6
9
  if (positional.includes('--help') || positional.includes('-h')) {
7
- console.log('anhedral registry list|view [item] [--json]');
10
+ console.log(commandHelp('registry'));
8
11
  return;
9
12
  }
10
13
  if (positional.some((arg) => arg.startsWith('-')))
11
14
  throw new Error('Unknown registry option.');
12
15
  const [action = 'list', name, ...extra] = positional;
16
+ if (action === 'capabilities' && !name && !extra.length) {
17
+ if (output.quiet && !json)
18
+ return;
19
+ console.log(json ? JSON.stringify(CAPABILITY_CONTRACT, null, 2) : formatCapabilityContract());
20
+ return;
21
+ }
13
22
  if (action === 'list' && !name && !extra.length) {
23
+ if (output.quiet && !json)
24
+ return;
14
25
  console.log(json
15
26
  ? JSON.stringify(STACK_REGISTRY, null, 2)
16
27
  : STACK_REGISTRY.items
@@ -19,30 +30,56 @@ export async function runRegistry(args, json) {
19
30
  return;
20
31
  }
21
32
  if (action === 'view' && name && !extra.length) {
22
- console.log(JSON.stringify(getStackItem(name), null, 2));
33
+ if (!STACK_REGISTRY.items.some((item) => item.name === name)) {
34
+ const correction = suggest(name, STACK_REGISTRY.items.map((item) => item.name));
35
+ throw new CliArgumentError(`Unknown bundled registry item.${correction ? ` Did you mean ${correction}?` : ''}`, 'Run anhedral registry list.');
36
+ }
37
+ printResult('registry', getStackItem(name), { ...output, json });
23
38
  return;
24
39
  }
25
- throw new Error('Use registry list or registry view <item>.');
40
+ throw new Error('Use registry list, registry view <item>, or registry capabilities.');
26
41
  }
27
- export async function runAdd(args) {
42
+ export async function runAdd(args, output = {}) {
28
43
  if (args.includes('--help') || args.includes('-h')) {
29
- console.log('anhedral add <directory> <items...> [--dry-run] [--skip-install] [--json]');
44
+ console.log(commandHelp('add'));
30
45
  return;
31
46
  }
32
47
  const positional = [];
33
- for (const arg of args) {
48
+ let preview;
49
+ for (let index = 0; index < args.length; index++) {
50
+ const arg = args[index];
51
+ if (arg === '--diff' || arg === '--view') {
52
+ if (preview)
53
+ throw new Error('Select one source preview: --diff or --view.');
54
+ preview = { mode: arg === '--diff' ? 'diff' : 'view' };
55
+ const next = args[index + 1];
56
+ if (next &&
57
+ !next.startsWith('-') &&
58
+ !STANDARD_PRODUCTS.includes(next)) {
59
+ preview.path = next;
60
+ index++;
61
+ }
62
+ continue;
63
+ }
34
64
  if (['--dry-run', '--skip-install', '--json'].includes(arg))
35
65
  continue;
36
66
  if (arg.startsWith('-'))
37
67
  throw new Error(`Unknown add option: ${arg}.`);
38
68
  positional.push(arg);
39
69
  }
40
- const [directory, ...items] = positional;
41
- if (!directory || !items.length)
42
- throw new Error('Use add <directory> <items...>.');
43
- console.log(JSON.stringify(await addStackItems(path.resolve(directory), {
70
+ const items = positional;
71
+ if (!items.length)
72
+ throw new Error('Select bundled parts: anhedral add <items...> [--cwd <directory>].');
73
+ for (const item of items) {
74
+ if (STANDARD_PRODUCTS.includes(item))
75
+ continue;
76
+ const correction = suggest(item, STANDARD_PRODUCTS);
77
+ throw new CliArgumentError(`Unknown stack part.${correction ? ` Did you mean ${correction}?` : ''}`, 'Select a project with --cwd <directory> and run anhedral registry list for bundled parts.');
78
+ }
79
+ printResult('add', await addStackItems(process.cwd(), {
44
80
  items,
45
- dryRun: args.includes('--dry-run'),
81
+ dryRun: args.includes('--dry-run') || Boolean(preview),
46
82
  skipInstall: args.includes('--skip-install'),
47
- }), null, 2));
83
+ ...(preview ? { preview } : {}),
84
+ }), { ...output, json: args.includes('--json') });
48
85
  }
@@ -1,2 +1,2 @@
1
1
  import type { StandardOptions } from './types.js';
2
- export declare function parseStandardOptions(command: 'new' | 'init', args: readonly string[]): StandardOptions;
2
+ export declare function parseStandardOptions(args: readonly string[]): StandardOptions;
@@ -44,11 +44,12 @@ function parseStandardFlags(remaining) {
44
44
  hosting = 'vercel';
45
45
  return { products, hosting, hostingSpecified, gitSpecified };
46
46
  }
47
- export function parseStandardOptions(command, args) {
47
+ export function parseStandardOptions(args) {
48
48
  const remaining = [...args];
49
- const directory = command === 'new' ? remaining.shift() : process.cwd();
49
+ const hasDirectory = remaining[0] && !remaining[0].startsWith('-');
50
+ const directory = hasDirectory ? remaining.shift() : process.cwd();
50
51
  if (!directory || directory.startsWith('-'))
51
- throw new Error('new requires a destination directory.');
52
+ throw new Error('Specify a valid initialization directory.');
52
53
  const root = path.resolve(directory);
53
54
  const { products, hosting, hostingSpecified, gitSpecified } = parseStandardFlags(remaining);
54
55
  resolveStandardProducts(products, hosting, hostingSpecified);
@@ -60,6 +61,6 @@ export function parseStandardOptions(command, args) {
60
61
  skipInstall: remaining.includes('--skip-install'),
61
62
  dryRun: remaining.includes('--dry-run'),
62
63
  json: remaining.includes('--json'),
63
- initializeGit: gitSpecified ?? command === 'new',
64
+ initializeGit: gitSpecified ?? Boolean(hasDirectory),
64
65
  };
65
66
  }
@@ -0,0 +1,11 @@
1
+ export declare const MAX_PREVIEW_TOTAL_BYTES: number;
2
+ export interface SourcePreview {
3
+ path: string;
4
+ content?: string;
5
+ diff?: string;
6
+ unavailable?: string;
7
+ }
8
+ export declare function validatePreviewPath(file: string): void;
9
+ /** A single contextual hunk is linear in file size and remains an applicable unified patch. */
10
+ export declare function sourceDiff(file: string, before: string | undefined, after: string): string;
11
+ export declare function sourcePreview(root: string, stage: string, file: string, mode: 'diff' | 'view'): SourcePreview;
@@ -0,0 +1,91 @@
1
+ import path from 'node:path';
2
+ import { existsSync } from 'node:fs';
3
+ import { readBoundedFile } from '../bounded-file.js';
4
+ const MAX_PREVIEW_FILE_BYTES = 256 * 1024;
5
+ export const MAX_PREVIEW_TOTAL_BYTES = 1024 * 1024;
6
+ export function validatePreviewPath(file) {
7
+ if (!file ||
8
+ path.posix.isAbsolute(file) ||
9
+ file.includes('\\') ||
10
+ /[\x00-\x1f\x7f]/.test(file) ||
11
+ file
12
+ .split('/')
13
+ .some((part) => !part ||
14
+ ['.', '..', '.anhedral'].includes(part) ||
15
+ (/^(?:\.env|\.dev\.vars)(?:\.|$)/.test(part) && !part.endsWith('.example'))))
16
+ throw new Error('Select a relative generated source path; private environment and state files cannot be previewed.');
17
+ }
18
+ /** A single contextual hunk is linear in file size and remains an applicable unified patch. */
19
+ export function sourceDiff(file, before, after) {
20
+ const lines = (content) => content === '' ? [] : content.split('\n').slice(0, content.endsWith('\n') ? -1 : undefined);
21
+ const oldLines = lines(before ?? '');
22
+ const newLines = lines(after);
23
+ if (before === after)
24
+ return '';
25
+ let prefix = 0;
26
+ while (prefix < oldLines.length &&
27
+ prefix < newLines.length &&
28
+ oldLines[prefix] === newLines[prefix])
29
+ prefix++;
30
+ // Newline-only changes must still include the final line in the patch.
31
+ if (prefix && oldLines.length === newLines.length && prefix === oldLines.length)
32
+ prefix--;
33
+ let suffix = 0;
34
+ while ((before ?? '').endsWith('\n') === after.endsWith('\n') &&
35
+ suffix < oldLines.length - prefix &&
36
+ suffix < newLines.length - prefix &&
37
+ oldLines.at(-suffix - 1) === newLines.at(-suffix - 1))
38
+ suffix++;
39
+ const start = Math.max(0, prefix - 3);
40
+ const oldEnd = Math.min(oldLines.length, oldLines.length - suffix + 3);
41
+ const newEnd = Math.min(newLines.length, newLines.length - suffix + 3);
42
+ const output = [
43
+ `diff --git a/${file} b/${file}`,
44
+ ...(before === undefined ? ['new file mode 100644'] : []),
45
+ `--- ${before === undefined ? '/dev/null' : `a/${file}`}`,
46
+ `+++ b/${file}`,
47
+ `@@ -${oldEnd - start ? start + 1 : start},${oldEnd - start} +${newEnd - start ? start + 1 : start},${newEnd - start} @@`,
48
+ ];
49
+ if (before === undefined && !after)
50
+ return output.slice(0, 2).join('\n') + '\n';
51
+ const append = (prefix, line, last, content) => {
52
+ output.push(`${prefix}${line}`);
53
+ if (last && !content.endsWith('\n'))
54
+ output.push('\');
55
+ };
56
+ for (let index = start; index < prefix; index++)
57
+ output.push(` ${oldLines[index]}`);
58
+ for (let index = prefix; index < oldLines.length - suffix; index++)
59
+ append('-', oldLines[index], index === oldLines.length - 1, before ?? '');
60
+ for (let index = prefix; index < newLines.length - suffix; index++)
61
+ append('+', newLines[index], index === newLines.length - 1, after);
62
+ for (let index = oldLines.length - suffix; index < oldEnd; index++)
63
+ append(' ', oldLines[index], index === oldLines.length - 1, after);
64
+ return output.join('\n') + '\n';
65
+ }
66
+ export function sourcePreview(root, stage, file, mode) {
67
+ validatePreviewPath(file);
68
+ const decode = (directory) => new TextDecoder('utf-8', { fatal: true }).decode(readBoundedFile(path.join(directory, file), MAX_PREVIEW_FILE_BYTES));
69
+ let after;
70
+ let before;
71
+ try {
72
+ after = decode(stage);
73
+ if (after.includes('\x00'))
74
+ throw new Error('Binary file');
75
+ if (mode === 'diff' && existsSync(path.join(root, file))) {
76
+ before = decode(root);
77
+ if (before.includes('\x00'))
78
+ throw new Error('Binary file');
79
+ }
80
+ }
81
+ catch {
82
+ return {
83
+ path: file,
84
+ unavailable: 'Binary, nonregular or oversized file; source preview is unavailable (256 KiB limit).',
85
+ };
86
+ }
87
+ return {
88
+ path: file,
89
+ ...(mode === 'view' ? { content: after } : { diff: sourceDiff(file, before, after) }),
90
+ };
91
+ }
@@ -1,2 +1,3 @@
1
1
  export declare function sourceFiles(root: string): Map<string, string>;
2
+ export declare function configurationFingerprints(root: string): Record<string, string>;
2
3
  export declare function recordScaffoldFiles(root: string): void;
@@ -1,7 +1,7 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { readFileSync, readdirSync } from 'node:fs';
3
3
  import path from 'node:path';
4
- import { json, readJson } from '../scaffold/files.js';
4
+ import { PROJECT_CONFIG_FILE, readProjectConfig, readProjectSection, writeProjectSection, } from '../project-config.js';
5
5
  const excluded = new Set([
6
6
  '.pnpm-store',
7
7
  '.artifacts',
@@ -10,6 +10,9 @@ const excluded = new Set([
10
10
  '.next',
11
11
  '.open-next',
12
12
  '.wrangler',
13
+ '.void',
14
+ '.vinext',
15
+ '.void-wrangler.jsonc',
13
16
  '.turbo',
14
17
  'dist',
15
18
  '.output',
@@ -19,7 +22,7 @@ const excluded = new Set([
19
22
  '.anhedral-audit-report.json',
20
23
  '.anhedral.lock',
21
24
  '.anhedral-txn',
22
- 'anhedral.registry.json',
25
+ PROJECT_CONFIG_FILE,
23
26
  ]);
24
27
  export function sourceFiles(root) {
25
28
  const files = new Map();
@@ -28,6 +31,9 @@ export function sourceFiles(root) {
28
31
  if (excluded.has(entry.name))
29
32
  continue;
30
33
  const relative = directory ? `${directory}/${entry.name}` : entry.name;
34
+ // Deployment mirrors are disposable; reviewed SQL lives in packages/db/drizzle.
35
+ if (/^apps\/[^/]+\/db\/migrations$/.test(relative))
36
+ continue;
31
37
  // Local credentials are never seeded into an addition transaction or fingerprint receipt.
32
38
  if (/^(?:\.env|\.dev\.vars)(?:\.|$)/.test(entry.name) && !entry.name.endsWith('.example'))
33
39
  continue;
@@ -44,10 +50,19 @@ export function sourceFiles(root) {
44
50
  visit('');
45
51
  return files;
46
52
  }
53
+ export function configurationFingerprints(root) {
54
+ return Object.fromEntries(Object.entries(readProjectConfig(root))
55
+ .filter(([section]) => !['schemaVersion', 'registry'].includes(section))
56
+ .map(([section, value]) => [
57
+ section,
58
+ createHash('sha256').update(JSON.stringify(value)).digest('hex'),
59
+ ]));
60
+ }
47
61
  export function recordScaffoldFiles(root) {
48
- const receipt = readJson(root, 'anhedral.registry.json');
49
- json(root, 'anhedral.registry.json', {
62
+ const receipt = readProjectSection(root, 'registry');
63
+ writeProjectSection(root, 'registry', {
50
64
  ...receipt,
51
65
  files: Object.fromEntries(sourceFiles(root)),
66
+ configuration: configurationFingerprints(root),
52
67
  });
53
68
  }
@@ -34,7 +34,11 @@ export function resolveStandardProducts(selected, hosting, hostingSpecified) {
34
34
  getStackDefinition(id);
35
35
  if (![...selected].some((id) => getStackDefinition(id).type === 'application'))
36
36
  selected.add(hosting === 'vercel' ? 'next' : 'vinext');
37
- for (const id of selected) {
37
+ // Resolve single-provider defaults before alternatives (e.g. Realtime's Neon
38
+ // before Better Auth chooses a database), independently of CLI flag order.
39
+ const defaults = [...selected].sort((left, right) => (getStackDefinition(left).selection.requiresAny?.length ?? 0) -
40
+ (getStackDefinition(right).selection.requiresAny?.length ?? 0) || left.localeCompare(right));
41
+ for (const id of defaults) {
38
42
  const definition = getStackDefinition(id);
39
43
  const alternatives = definition.selection.requiresAny ?? [];
40
44
  if (definition.fallbackDependency &&
@@ -1 +1,11 @@
1
+ export declare const COMMAND_HELP: {
2
+ [k: string]: {
3
+ options: string[];
4
+ description: string;
5
+ usage: string;
6
+ examples: readonly string[];
7
+ note?: string;
8
+ };
9
+ };
10
+ export declare function commandHelp(command: string): string | undefined;
1
11
  export declare const STANDARD_USAGE: string;