anhedral 0.17.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/README.md +33 -68
  2. package/assets/contracts/LICENSE +201 -0
  3. package/assets/contracts/LICENSE.environment +201 -0
  4. package/assets/contracts/LICENSE.operations +201 -0
  5. package/assets/contracts/deployment-provenance.json +15 -0
  6. package/assets/contracts/environment-provenance.json +11 -0
  7. package/assets/contracts/operations-provenance.json +11 -0
  8. package/assets/launch/application.server.ts.txt +13 -0
  9. package/assets/launch/auth-client.ts.txt +4 -0
  10. package/assets/launch/home.tsx.txt +20 -0
  11. package/assets/launch/minimal-application.server.ts.txt +5 -0
  12. package/assets/launch/minimal-server.ts.txt +7 -0
  13. package/assets/launch/request-context.ts.txt +3 -0
  14. package/assets/launch/root.tsx.txt +27 -0
  15. package/assets/launch/router.tsx.txt +21 -0
  16. package/assets/launch/server.ts.txt +13 -0
  17. package/assets/launch/sign-in.tsx.txt +53 -0
  18. package/assets/launch/styles.css.txt +19 -0
  19. package/assets/security/credential-patterns.d.mts +3 -0
  20. package/assets/security/credential-patterns.mjs +59 -0
  21. package/assets/stack/api-index.ts.txt +6 -1
  22. package/assets/stack/event-retention.sql.txt +10 -0
  23. package/assets/stack/stripe.ts.txt +30 -13
  24. package/dist/bin.js +55 -36
  25. package/dist/capabilities.d.ts +1 -1
  26. package/dist/capability-catalog.d.ts +44 -11
  27. package/dist/capability-catalog.js +96 -11
  28. package/dist/capability-command.d.ts +2 -2
  29. package/dist/capability-command.js +178 -27
  30. package/dist/capability-editor.js +6 -5
  31. package/dist/capability-recipes.js +54 -6
  32. package/dist/cli-arguments.d.ts +2 -0
  33. package/dist/cli-arguments.js +101 -50
  34. package/dist/cli-commands.d.ts +1 -1
  35. package/dist/cli-commands.js +30 -6
  36. package/dist/cli-errors.d.ts +18 -0
  37. package/dist/cli-errors.js +63 -0
  38. package/dist/cli-output.d.ts +22 -0
  39. package/dist/cli-output.js +42 -7
  40. package/dist/command-runner.d.ts +1 -0
  41. package/dist/command-runner.js +88 -0
  42. package/dist/command-schema.d.ts +16 -0
  43. package/dist/command-schema.js +390 -21
  44. package/dist/completion.d.ts +2 -0
  45. package/dist/completion.js +201 -0
  46. package/dist/composition.d.ts +35 -0
  47. package/dist/composition.js +28 -0
  48. package/dist/contracts/cli-transport.d.ts +217 -0
  49. package/dist/contracts/cli-transport.js +167 -0
  50. package/dist/contracts/deployment.d.ts +282 -0
  51. package/dist/contracts/deployment.js +234 -0
  52. package/dist/contracts/environment-file.d.ts +7 -0
  53. package/dist/contracts/environment-file.js +112 -0
  54. package/dist/contracts/environment-transport.d.ts +79 -0
  55. package/dist/contracts/environment-transport.js +110 -0
  56. package/dist/contracts/runtime-logs-transport.d.ts +127 -0
  57. package/dist/contracts/runtime-logs-transport.js +50 -0
  58. package/dist/contracts/source-bundle.d.ts +11 -0
  59. package/dist/contracts/source-bundle.js +197 -0
  60. package/dist/contracts/source-profile.d.ts +4 -0
  61. package/dist/contracts/source-profile.js +5 -0
  62. package/dist/contracts/staging-transport.d.ts +79 -0
  63. package/dist/contracts/staging-transport.js +43 -0
  64. package/dist/dependencies.d.ts +10 -1
  65. package/dist/dependencies.js +18 -1
  66. package/dist/index.d.ts +6 -0
  67. package/dist/index.js +4 -0
  68. package/dist/launch.d.ts +21 -0
  69. package/dist/launch.js +250 -0
  70. package/dist/platform-command.d.ts +9 -0
  71. package/dist/platform-command.js +584 -0
  72. package/dist/platform-environment.d.ts +18 -0
  73. package/dist/platform-environment.js +257 -0
  74. package/dist/platform-operations.d.ts +26 -0
  75. package/dist/platform-operations.js +155 -0
  76. package/dist/platform-source.d.ts +8 -0
  77. package/dist/platform-source.js +111 -0
  78. package/dist/platform-state.d.ts +13 -0
  79. package/dist/platform-state.js +207 -0
  80. package/dist/platforms/tanstack.d.ts +8 -0
  81. package/dist/platforms/tanstack.js +155 -0
  82. package/dist/registry/options.js +34 -31
  83. package/dist/registry/usage.d.ts +4 -1
  84. package/dist/registry/usage.js +58 -4
  85. package/dist/scaffold/styling.d.ts +1 -1
  86. package/dist/scaffold/workspace.js +11 -1
  87. package/dist/stack-registry.d.ts +2 -2
  88. package/dist/standard.js +21 -6
  89. package/dist/transaction.js +28 -3
  90. package/dist/ui-command.d.ts +4 -2
  91. package/dist/ui-command.js +79 -38
  92. package/dist/ui-project.d.ts +2 -0
  93. package/dist/ui-project.js +38 -8
  94. package/dist/util.js +40 -61
  95. package/dist/version.d.ts +1 -1
  96. package/dist/version.js +1 -1
  97. package/docs/capabilities.md +22 -88
  98. package/docs/software-factory.md +169 -9
  99. package/docs/stack-standard.md +7 -17
  100. package/docs/ui.md +9 -22
  101. package/package.json +27 -20
  102. package/docs/anhedral-stack.md +0 -12
  103. package/docs/assets/anhedral-stack-light.png +0 -0
  104. package/docs/assets/anhedral-stack.png +0 -0
  105. package/docs/native-ui.md +0 -47
@@ -0,0 +1,207 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { createHash, randomUUID } from 'node:crypto';
3
+ import { dirname, join } from 'node:path';
4
+ import { lstat, mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
5
+ import { CliArgumentError } from './cli-arguments.js';
6
+ import { CliFailure } from './cli-errors.js';
7
+ export const platformFailure = (message, nextAction = 'Run anhedral login --help.', category = 'context', retryable = false) => new CliFailure(message, 'PLATFORM_ACCESS_FAILED', nextAction, category, retryable);
8
+ export function platformOrigin(value = 'https://platform.anhedral.com') {
9
+ let url;
10
+ try {
11
+ url = new URL(value);
12
+ }
13
+ catch {
14
+ throw new CliArgumentError('Choose a valid HTTPS API origin with --api-url.', 'Run anhedral login --help.');
15
+ }
16
+ if (url.username ||
17
+ url.password ||
18
+ url.search ||
19
+ url.hash ||
20
+ url.pathname !== '/' ||
21
+ (url.protocol !== 'https:' &&
22
+ !(url.protocol === 'http:' && ['127.0.0.1', '[::1]'].includes(url.hostname))))
23
+ throw new CliArgumentError('Choose an HTTPS API origin (literal loopback is allowed for local testing).', 'Run anhedral login --help.');
24
+ return url.origin;
25
+ }
26
+ async function safeDirectory(path, privateMode = true) {
27
+ const parent = dirname(path);
28
+ if (parent !== path) {
29
+ const info = await lstat(parent).catch(() => null);
30
+ if (!info)
31
+ await safeDirectory(parent, false);
32
+ else if (info.isSymbolicLink() || !info.isDirectory())
33
+ throw platformFailure('State directory is unsafe.');
34
+ }
35
+ await mkdir(path, { mode: 0o700 }).catch(async (error) => {
36
+ if (error.code !== 'EEXIST')
37
+ throw error;
38
+ });
39
+ const info = await lstat(path);
40
+ if (!info.isDirectory() ||
41
+ info.isSymbolicLink() ||
42
+ (privateMode &&
43
+ process.platform !== 'win32' &&
44
+ ((info.mode & 0o077) !== 0 || info.uid !== process.getuid?.())))
45
+ throw platformFailure('State directory must be owned by you with mode 0700.');
46
+ }
47
+ export async function readPrivate(path) {
48
+ // Validate every existing ancestor before following it.
49
+ for (let p = dirname(path);; p = dirname(p)) {
50
+ const info = await lstat(p).catch(() => null);
51
+ if (info?.isSymbolicLink() || (info && !info.isDirectory()))
52
+ throw platformFailure('State directory is unsafe.');
53
+ if (dirname(p) === p)
54
+ break;
55
+ }
56
+ const info = await lstat(path).catch((error) => {
57
+ if (error.code === 'ENOENT')
58
+ return null;
59
+ throw error;
60
+ });
61
+ if (!info)
62
+ return null;
63
+ if (!info.isFile() ||
64
+ info.isSymbolicLink() ||
65
+ info.size > 65536 ||
66
+ (process.platform !== 'win32' && ((info.mode & 0o077) !== 0 || info.uid !== process.getuid?.())))
67
+ throw platformFailure('State file must be owned by you with mode 0600.');
68
+ const text = await readFile(path, 'utf8');
69
+ try {
70
+ return JSON.parse(text);
71
+ }
72
+ catch {
73
+ throw platformFailure('Saved Platform state is not valid JSON. Preserve the file and reconcile the selected context.', 'Run anhedral whoami --context --help.');
74
+ }
75
+ }
76
+ export async function writePrivate(path, data) {
77
+ await safeDirectory(dirname(path));
78
+ await readPrivate(path);
79
+ const temp = join(dirname(path), `.state-${randomUUID()}`);
80
+ try {
81
+ await writeFile(temp, JSON.stringify(data) + '\n', { mode: 0o600, flag: 'wx' });
82
+ await rename(temp, path);
83
+ }
84
+ finally {
85
+ await unlink(temp).catch(() => { });
86
+ }
87
+ }
88
+ export function runCredentialProcess(binary, args, input = '', timeoutMs = 30000) {
89
+ return new Promise((resolve, reject) => {
90
+ const child = spawn(binary, args, { stdio: ['pipe', 'pipe', 'pipe'] });
91
+ let result = '';
92
+ let failure;
93
+ const timer = setTimeout(() => {
94
+ failure = platformFailure('System credential storage timed out. Check the credential service before retrying.');
95
+ child.kill('SIGKILL');
96
+ }, timeoutMs);
97
+ child.stdout.on('data', (data) => {
98
+ result += data;
99
+ if (result.length > 65536) {
100
+ failure = platformFailure('System credential storage returned too much data.');
101
+ child.kill('SIGKILL');
102
+ }
103
+ });
104
+ child.on('error', () => {
105
+ clearTimeout(timer);
106
+ reject(platformFailure('System credential storage is unavailable. Choose an explicit --credential-file if needed.'));
107
+ });
108
+ child.on('close', (code) => {
109
+ clearTimeout(timer);
110
+ if (failure)
111
+ reject(failure);
112
+ else if (code === 0)
113
+ resolve(result.trim());
114
+ else
115
+ reject(platformFailure('System credential storage could not be accessed.'));
116
+ });
117
+ child.stdin.on('error', () => { });
118
+ child.stdin.end(input);
119
+ });
120
+ }
121
+ export function secretStore(origin, file, runProcess = runCredentialProcess, platform = process.platform) {
122
+ if (file && platform === 'win32')
123
+ throw platformFailure('Secure Windows credential storage is not implemented. Use macOS Keychain or Linux Secret Service for this preview.');
124
+ if (file)
125
+ return {
126
+ read: () => readPrivate(file),
127
+ write: (data) => writePrivate(file, data),
128
+ clear: async () => {
129
+ await readPrivate(file);
130
+ await unlink(file).catch((e) => {
131
+ if (e.code !== 'ENOENT')
132
+ throw e;
133
+ });
134
+ },
135
+ };
136
+ const account = createHash('sha256').update(origin).digest('hex');
137
+ if (platform === 'darwin') {
138
+ // -i reads commands on stdin, keeping secret values out of process argv.
139
+ const run = (command) => runProcess('/usr/bin/security', ['-i'], command + '\n');
140
+ const quote = (v) => '"' + v.replaceAll('\\', '\\\\').replaceAll('"', '\\"') + '"';
141
+ return {
142
+ read: async () => {
143
+ try {
144
+ return JSON.parse(await runProcess('/usr/bin/security', [
145
+ 'find-generic-password',
146
+ '-s',
147
+ 'dev.anhedral.cli.v1',
148
+ '-a',
149
+ account,
150
+ '-w',
151
+ ]));
152
+ }
153
+ catch {
154
+ return null;
155
+ }
156
+ },
157
+ write: async (data) => {
158
+ await run(`add-generic-password -U -s dev.anhedral.cli.v1 -a ${account} -w ${quote(JSON.stringify(data))}`);
159
+ const stored = await runProcess('/usr/bin/security', [
160
+ 'find-generic-password',
161
+ '-s',
162
+ 'dev.anhedral.cli.v1',
163
+ '-a',
164
+ account,
165
+ '-w',
166
+ ]);
167
+ if (stored !== JSON.stringify(data))
168
+ throw platformFailure('Credential storage could not be verified.');
169
+ },
170
+ clear: async () => {
171
+ await runProcess('/usr/bin/security', [
172
+ 'delete-generic-password',
173
+ '-s',
174
+ 'dev.anhedral.cli.v1',
175
+ '-a',
176
+ account,
177
+ ]);
178
+ },
179
+ };
180
+ }
181
+ if (platform === 'linux')
182
+ return {
183
+ read: async () => {
184
+ const value = await runProcess('secret-tool', [
185
+ 'lookup',
186
+ 'service',
187
+ 'dev.anhedral.cli.v1',
188
+ 'origin',
189
+ account,
190
+ ]).catch(() => '');
191
+ return value ? JSON.parse(value) : null;
192
+ },
193
+ write: async (data) => {
194
+ await runProcess('secret-tool', ['store', '--label=Anhedral CLI', 'service', 'dev.anhedral.cli.v1', 'origin', account], JSON.stringify(data));
195
+ },
196
+ clear: async () => {
197
+ await runProcess('secret-tool', [
198
+ 'clear',
199
+ 'service',
200
+ 'dev.anhedral.cli.v1',
201
+ 'origin',
202
+ account,
203
+ ]);
204
+ },
205
+ };
206
+ throw platformFailure('Secure credential storage is unsupported on this platform.');
207
+ }
@@ -0,0 +1,8 @@
1
+ import { CapabilityEditor } from '../capability-editor.js';
2
+ import type { Capability } from '../capability-catalog.js';
3
+ /** The launch foundation is a web service; Hono owns application services and data. */
4
+ export declare function scaffoldTanstack(root: string, name: string): void;
5
+ /** Fingerprinted composition adapters; application routes stay source-owned. */
6
+ export declare function composeTanstack(e: CapabilityEditor, installed: readonly Capability[]): void;
7
+ /** Install account source only when the backend authentication capability is added. */
8
+ export declare function addTanstackAuth(e: CapabilityEditor): void;
@@ -0,0 +1,155 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { ANHEDRAL_STACK_DEPENDENCIES, WEB_DEPENDENCIES } from '../dependencies.js';
4
+ import { CapabilityEditor } from '../capability-editor.js';
5
+ import { resourceName } from '../render.js';
6
+ import { json, put, workerConfig } from '../scaffold/files.js';
7
+ import { initializeUiMetadata } from '../ui-project.js';
8
+ const template = (name) => readFileSync(new URL(`../../assets/launch/${name}`, import.meta.url), 'utf8');
9
+ /** The launch foundation is a web service; Hono owns application services and data. */
10
+ export function scaffoldTanstack(root, name) {
11
+ const app = 'apps/web';
12
+ const web = WEB_DEPENDENCIES.dependencies;
13
+ const dev = WEB_DEPENDENCIES.devDependencies;
14
+ json(root, `${app}/package.json`, {
15
+ name: '@workspace/web',
16
+ private: true,
17
+ version: '0.1.0',
18
+ type: 'module',
19
+ scripts: {
20
+ dev: 'vite dev --host 0.0.0.0 --port 3000',
21
+ build: 'vite build',
22
+ preview: 'vite preview --host 0.0.0.0 --port 3000',
23
+ typecheck: 'wrangler types && tsr generate && tsc --noEmit',
24
+ lint: 'eslint . --max-warnings 0',
25
+ },
26
+ dependencies: {
27
+ '@tanstack/react-start': ANHEDRAL_STACK_DEPENDENCIES['@tanstack/react-start'],
28
+ '@tanstack/react-router': ANHEDRAL_STACK_DEPENDENCIES['@tanstack/react-router'],
29
+ react: web.react,
30
+ 'react-dom': web['react-dom'],
31
+ '@base-ui/react': web['@base-ui/react'],
32
+ 'class-variance-authority': web['class-variance-authority'],
33
+ clsx: web.clsx,
34
+ 'tailwind-merge': web['tailwind-merge'],
35
+ '@workspace/styling': 'workspace:*',
36
+ },
37
+ devDependencies: {
38
+ '@cloudflare/vite-plugin': ANHEDRAL_STACK_DEPENDENCIES['@cloudflare/vite-plugin'],
39
+ '@tanstack/router-cli': ANHEDRAL_STACK_DEPENDENCIES['@tanstack/router-cli'],
40
+ '@vitejs/plugin-react': ANHEDRAL_STACK_DEPENDENCIES['@vitejs/plugin-react'],
41
+ vite: ANHEDRAL_STACK_DEPENDENCIES.vite,
42
+ wrangler: ANHEDRAL_STACK_DEPENDENCIES.wrangler,
43
+ typescript: dev.typescript,
44
+ '@types/node': dev['@types/node'],
45
+ '@types/react': dev['@types/react'],
46
+ '@types/react-dom': dev['@types/react-dom'],
47
+ tailwindcss: dev.tailwindcss,
48
+ '@tailwindcss/postcss': dev['@tailwindcss/postcss'],
49
+ eslint: dev.eslint,
50
+ '@workspace/eslint-config': 'workspace:*',
51
+ },
52
+ });
53
+ json(root, `${app}/wrangler.jsonc`, {
54
+ ...workerConfig(resourceName(name, 'web')),
55
+ main: 'src/server.ts',
56
+ compatibility_date: '2026-11-02',
57
+ services: [],
58
+ });
59
+ json(root, `${app}/tsconfig.json`, {
60
+ compilerOptions: {
61
+ target: 'ES2022',
62
+ lib: ['DOM', 'DOM.Iterable', 'ES2022'],
63
+ skipLibCheck: true,
64
+ strict: true,
65
+ noEmit: true,
66
+ esModuleInterop: true,
67
+ module: 'ESNext',
68
+ moduleResolution: 'Bundler',
69
+ resolveJsonModule: true,
70
+ isolatedModules: true,
71
+ jsx: 'react-jsx',
72
+ types: ['vite/client'],
73
+ paths: { '@/*': ['./src/*'] },
74
+ },
75
+ include: ['src/**/*.ts', 'src/**/*.tsx', 'vite.config.ts', 'worker-configuration.d.ts'],
76
+ exclude: ['node_modules', 'dist'],
77
+ });
78
+ json(root, `${app}/tsr.config.json`, {
79
+ routesDirectory: './src/routes',
80
+ generatedRouteTree: './src/routeTree.gen.ts',
81
+ });
82
+ put(root, `${app}/eslint.config.mjs`, `import { config } from '@workspace/eslint-config/react-internal';
83
+ export default [...config, { ignores: ['dist/**', '.wrangler/**', 'src/routeTree.gen.ts', 'worker-configuration.d.ts'] }];
84
+ `);
85
+ json(root, `${app}/components.json`, {
86
+ $schema: 'https://ui.shadcn.com/schema.json',
87
+ style: 'base-nova',
88
+ rsc: false,
89
+ tsx: true,
90
+ tailwind: { config: '', css: 'src/styles.css', baseColor: 'neutral', cssVariables: true },
91
+ aliases: {
92
+ components: '@/components',
93
+ ui: '@/components/ui',
94
+ utils: '@/lib/utils',
95
+ lib: '@/lib',
96
+ hooks: '@/hooks',
97
+ },
98
+ iconLibrary: 'lucide',
99
+ });
100
+ initializeUiMetadata(path.join(root, app), 'web');
101
+ put(root, `${app}/src/lib/utils.ts`, `import { clsx, type ClassValue } from 'clsx';
102
+ import { twMerge } from 'tailwind-merge';
103
+ export function cn(...values: ClassValue[]) { return twMerge(clsx(values)); }
104
+ `);
105
+ for (const component of ['button', 'input', 'label'])
106
+ put(root, `${app}/src/components/ui/${component}.tsx`, readFileSync(new URL(`../../assets/ui/web/${component}.tsx`, import.meta.url), 'utf8'));
107
+ for (const file of ['LICENSE.shadcn', 'UPSTREAM.json'])
108
+ put(root, `${app}/${file}`, readFileSync(new URL(`../../assets/ui/${file}`, import.meta.url), 'utf8'));
109
+ put(root, `${app}/postcss.config.mjs`, "export default { plugins: { '@tailwindcss/postcss': {} } };\n");
110
+ put(root, `${app}/src/starter.ts`, `export const starterTitle = ${JSON.stringify(name)};\n`);
111
+ const files = {
112
+ 'src/router.tsx': 'router.tsx.txt',
113
+ 'src/lib/request-context.ts': 'request-context.ts.txt',
114
+ 'src/routes/__root.tsx': 'root.tsx.txt',
115
+ 'src/routes/index.tsx': 'home.tsx.txt',
116
+ 'src/styles.css': 'styles.css.txt',
117
+ };
118
+ for (const [destination, source] of Object.entries(files))
119
+ put(root, `${app}/${destination}`, template(source).replaceAll('__APPLICATION_NAME__', JSON.stringify(name)));
120
+ put(root, `${app}/public/robots.txt`, 'User-agent: *\nAllow: /\n');
121
+ put(root, `${app}/public/_headers`, '/assets/*\n Cache-Control: public, max-age=31536000, immutable\n/*\n X-Content-Type-Options: nosniff\n');
122
+ }
123
+ function isTanstack(e) {
124
+ return Boolean(e.json('apps/web/package.json').dependencies?.['@tanstack/react-start']);
125
+ }
126
+ /** Fingerprinted composition adapters; application routes stay source-owned. */
127
+ export function composeTanstack(e, installed) {
128
+ if (!isTanstack(e))
129
+ return;
130
+ const backend = installed.includes('hono');
131
+ const auth = installed.includes('database-auth');
132
+ e.owned('apps/web/src/server.ts', template(backend ? 'server.ts.txt' : 'minimal-server.ts.txt'));
133
+ e.owned('apps/web/src/lib/application.server.ts', template(backend ? 'application.server.ts.txt' : 'minimal-application.server.ts.txt').replaceAll('__AUTHENTICATION__', String(auth)));
134
+ e.owned('apps/web/vite.config.ts', `import { fileURLToPath } from 'node:url';
135
+ import { defineConfig } from 'vite';
136
+ import { cloudflare } from '@cloudflare/vite-plugin';
137
+ import { tanstackStart } from '@tanstack/react-start/plugin/vite';
138
+ import react from '@vitejs/plugin-react';
139
+ export default defineConfig({
140
+ resolve: { alias: { '@': fileURLToPath(new URL('./src', import.meta.url)) } },
141
+ plugins: [
142
+ cloudflare({ viteEnvironment: { name: 'ssr' }, ${backend ? "auxiliaryWorkers: [{ configPath: '../api/wrangler.jsonc' }], persistState: { path: fileURLToPath(new URL('../api/.wrangler/state', import.meta.url)) }, " : ''}remoteBindings: false }),
143
+ tanstackStart({ server: { entry: './server.ts' } }),
144
+ react(),
145
+ ],
146
+ });
147
+ `);
148
+ }
149
+ /** Install account source only when the backend authentication capability is added. */
150
+ export function addTanstackAuth(e) {
151
+ if (!isTanstack(e))
152
+ return;
153
+ e.create('apps/web/src/lib/auth-client.ts', template('auth-client.ts.txt'));
154
+ e.create('apps/web/src/routes/sign-in.tsx', template('sign-in.tsx.txt'));
155
+ }
@@ -1,44 +1,47 @@
1
1
  import { resolveStandardProducts } from './resolve.js';
2
2
  import path from 'node:path';
3
3
  import { packageNameFromText } from '../render.js';
4
- function readGitFlag(token, previous) {
5
- const value = token === '--git';
6
- if (previous !== undefined && value !== previous)
7
- throw new Error('Conflicting Git options.');
8
- return value;
9
- }
10
- function parseStandardFlags(remaining) {
11
- const products = new Set();
12
- const hosting = 'cloudflare';
13
- let gitSpecified;
14
- for (const token of remaining) {
15
- if (['--skip-install', '--dry-run', '--json', '--verbose'].includes(token))
16
- continue;
17
- if (token === '--git' || token === '--no-git') {
18
- gitSpecified = readGitFlag(token, gitSpecified);
19
- continue;
20
- }
21
- throw new Error(`Unknown init option: ${token}. Run anhedral init --help.`);
22
- }
23
- return { products, hosting, gitSpecified };
24
- }
4
+ import { CliArgumentError, commandArguments } from '../cli-arguments.js';
25
5
  export function parseStandardOptions(args) {
26
- const remaining = [...args];
27
- const hasDirectory = remaining[0] && !remaining[0].startsWith('-');
28
- const directory = hasDirectory ? remaining.shift() : process.cwd();
29
- if (!directory || directory.startsWith('-'))
30
- throw new Error('Specify a valid initialization directory.');
6
+ // The exported parser historically accepted repeated identical booleans.
7
+ // Executable validation still rejects duplicates before calling this API.
8
+ const legacyBooleans = new Set([
9
+ '--skip-install',
10
+ '--dry-run',
11
+ '--json',
12
+ '--verbose',
13
+ '--git',
14
+ '--no-git',
15
+ ]);
16
+ const seen = new Set();
17
+ let literal = false;
18
+ const normalized = args.filter((arg) => {
19
+ if (arg === '--')
20
+ literal = true;
21
+ if (literal || !legacyBooleans.has(arg))
22
+ return true;
23
+ if (seen.has(arg))
24
+ return false;
25
+ seen.add(arg);
26
+ return true;
27
+ });
28
+ const parsed = commandArguments('init', normalized);
29
+ const hasDirectory = parsed.positional.length > 0;
30
+ const directory = hasDirectory ? parsed.positional[0] : process.cwd();
31
+ if (!directory)
32
+ throw new CliArgumentError('Specify a valid initialization directory.', 'Run anhedral init --help.');
31
33
  const root = path.resolve(directory);
32
- const { products, hosting, gitSpecified } = parseStandardFlags(remaining);
34
+ const products = new Set();
35
+ const hosting = 'cloudflare';
33
36
  resolveStandardProducts(products, hosting);
34
37
  return {
35
38
  root,
36
39
  name: packageNameFromText(path.basename(root)),
37
40
  products: [...products].sort(),
38
41
  hosting,
39
- skipInstall: remaining.includes('--skip-install'),
40
- dryRun: remaining.includes('--dry-run'),
41
- json: remaining.includes('--json'),
42
- initializeGit: gitSpecified ?? Boolean(hasDirectory),
42
+ skipInstall: parsed.has('--skip-install'),
43
+ dryRun: parsed.has('--dry-run'),
44
+ json: parsed.has('--json'),
45
+ initializeGit: parsed.has('--git') || (!parsed.has('--no-git') && hasDirectory),
43
46
  };
44
47
  }
@@ -5,7 +5,10 @@ export declare const COMMAND_HELP: {
5
5
  usage: string;
6
6
  examples: readonly string[];
7
7
  note?: string;
8
+ children?: Readonly<Record<string, import("../command-schema.js").CommandDefinition>>;
9
+ positional?: import("../command-schema.js").CommandPositional;
10
+ conflicts?: readonly (readonly string[])[];
8
11
  };
9
12
  };
10
- export declare function commandHelp(command: string): string | undefined;
13
+ export declare function commandHelp(command: string | readonly string[]): string | undefined;
11
14
  export declare const STANDARD_USAGE: string;
@@ -1,12 +1,66 @@
1
- import { COMMANDS, GLOBAL_OPTIONS, optionHelp } from '../command-schema.js';
1
+ import { COMMANDS, GLOBAL_OPTIONS, optionHelp, commandTopic } from '../command-schema.js';
2
2
  export const COMMAND_HELP = Object.fromEntries(Object.entries(COMMANDS).map(([name, entry]) => [
3
3
  name,
4
4
  { ...entry, options: entry.options.map(optionHelp) },
5
5
  ]));
6
6
  export function commandHelp(command) {
7
- const entry = COMMAND_HELP[command];
7
+ const topic = typeof command === 'string' ? command.trim().split(/\s+/) : command;
8
+ const entry = commandTopic(topic);
8
9
  if (!entry)
9
10
  return undefined;
10
- return `${entry.description}\n\nUsage: anhedral ${entry.usage}\n\nOptions:\n${[...entry.options, ...GLOBAL_OPTIONS.map(optionHelp)].map((option) => ` ${option}`).join('\n')}\n\n${entry.note}\n`;
11
+ const children = entry.children
12
+ ? '\nCommands:\n' +
13
+ Object.entries(entry.children)
14
+ .map(([name, child]) => ` ${name.padEnd(10)} ${child.description}`)
15
+ .join('\n') +
16
+ '\n'
17
+ : '';
18
+ const examples = entry.examples.length
19
+ ? '\nExamples:\n' + entry.examples.map((example) => ` anhedral ${example}`).join('\n') + '\n'
20
+ : '';
21
+ return `${entry.description}\n\nUsage: anhedral ${entry.usage}\n${children}${examples}\nOptions:\n${[
22
+ ...entry.options,
23
+ ...GLOBAL_OPTIONS,
24
+ ]
25
+ .filter((option) => !option.hidden)
26
+ .map((option) => ` ${optionHelp(option)}`)
27
+ .join('\n')}\n${entry.note ? `\n${entry.note}\n` : ''}\nDocs: https://github.com/anhedral/anhedral-cli#readme\n`;
11
28
  }
12
- export const STANDARD_USAGE = `Anhedral — an open-source stack foundation\n\n${commandHelp('init')}\n${commandHelp('ui')}\n${commandHelp('add')}\n${commandHelp('stack')}\n -v, --version Show the CLI version.\n`;
29
+ export const STANDARD_USAGE = `Anhedral CLI — source generation and optional Platform access
30
+
31
+ Usage: anhedral <command> [options]
32
+
33
+ Start a project:
34
+ init Create the Anhedral Stack with web UI.
35
+ add Add backend, private storage or payments.
36
+
37
+ Inspect source and UI:
38
+ stack Inspect the Anhedral Stack or run doctor.
39
+ ui Initialize, add, list, diff or check UI components.
40
+
41
+ Optional Platform access:
42
+ login/logout Approve or revoke a CLI session.
43
+ whoami Inspect the current identity and optional local context.
44
+ link/unlink Select an existing project or remove its local link.
45
+ source Upload source or inspect its receipt.
46
+ deploy Plan, prepare or inspect a candidate; never activates it.
47
+ env Import private configuration or list variable metadata.
48
+ staging Deploy verified candidates to persistent staging.
49
+ logs Read redacted runtime logs for a linked project.
50
+
51
+ Shell setup:
52
+ completion Print Bash or zsh completion without editing profiles.
53
+
54
+ Examples:
55
+ anhedral init my-app
56
+ anhedral add backend --dry-run
57
+ anhedral stack list
58
+
59
+ Global options:
60
+ ${GLOBAL_OPTIONS.map((option) => ' ' + optionHelp(option)).join('\n')}
61
+ -v, --version Show the CLI version.
62
+
63
+ Run anhedral <command> --help for options and examples.
64
+ Docs: https://github.com/anhedral/anhedral-cli#readme
65
+ Issues: https://github.com/anhedral/anhedral-cli/issues
66
+ `;
@@ -1,3 +1,3 @@
1
1
  import type { RecipeContext } from '../registry/types.js';
2
2
  /** One shared token source for native components and DOM CSS. */
3
- export declare function scaffoldStyling({ root }: RecipeContext): void;
3
+ export declare function scaffoldStyling({ root }: Pick<RecipeContext, 'root'>): void;
@@ -1,4 +1,6 @@
1
1
  import { writeProjectSection } from '../project-config.js';
2
+ import { sourceCompositionSchema } from '../contracts/deployment.js';
3
+ import { GENERATOR_VERSION } from '../version.js';
2
4
  import { OPENNEXT_GLOB_VERSION, STACK_DEPENDENCIES, WORKSPACE_NODE_ENGINE, PACKAGE_MANAGER, } from '../dependencies.js';
3
5
  import { writeDependencyAudit } from '../dependency-patches.js';
4
6
  import { setPnpmPolicy } from '../pnpm-policy.js';
@@ -83,7 +85,7 @@ process.exitCode = result.status ?? 1;
83
85
  });
84
86
  setPnpmPolicy(root, {
85
87
  ...(!updating ? { packages: ['apps/*', 'packages/*'] } : {}),
86
- // OpenNext's node-minify dependency pins the vulnerable glob CLI.
88
+ // Override node-minify's glob with the reviewed cancellation fix.
87
89
  overrides: {
88
90
  '@node-minify/core>glob': OPENNEXT_GLOB_VERSION,
89
91
  'miniflare>undici': STACK_DEPENDENCIES.undici,
@@ -126,6 +128,14 @@ process.exitCode = result.status ?? 1;
126
128
  resourcesProvisioned: false,
127
129
  });
128
130
  writeProjectSection(root, 'setup', createSetupPlan({ ...options, dryRun: false }, registry));
131
+ if (!updating && options.products.every((id) => ['next', 'styling'].includes(id)))
132
+ writeProjectSection(root, 'composition', sourceCompositionSchema.parse({
133
+ contractVersion: 1,
134
+ foundation: 'next-opennext',
135
+ generatorVersion: GENERATOR_VERSION,
136
+ identity: 'none',
137
+ capabilities: {},
138
+ }));
129
139
  if (!updating)
130
140
  writeSetupDocumentation(root, options);
131
141
  }
@@ -8,7 +8,7 @@ declare const PRODUCT_ITEMS: {
8
8
  styling: ItemDefinition;
9
9
  };
10
10
  export type StandardProduct = keyof typeof PRODUCT_ITEMS;
11
- export declare const STANDARD_PRODUCTS: readonly ("hono" | "r2" | "next" | "styling" | "d1")[];
11
+ export declare const STANDARD_PRODUCTS: readonly ("next" | "hono" | "r2" | "styling" | "d1")[];
12
12
  declare const DEFINITIONS: {
13
13
  next: ItemDefinition;
14
14
  hono: ItemDefinition;
@@ -22,7 +22,7 @@ declare const DEFINITIONS: {
22
22
  export type StackItemId = keyof typeof DEFINITIONS;
23
23
  export declare function getStackDefinition(name: string): ItemDefinition;
24
24
  export declare function getStackItem(name: string): StackRegistryItem;
25
- export declare const STACK_ITEMS: Record<"hono" | "r2" | "next" | "eslint" | "typescript" | "workspace" | "styling" | "d1", StackRegistryItem>;
25
+ export declare const STACK_ITEMS: Record<"next" | "hono" | "r2" | "eslint" | "typescript" | "workspace" | "styling" | "d1", StackRegistryItem>;
26
26
  export declare const STACK_REGISTRY: {
27
27
  schemaVersion: number;
28
28
  name: string;
package/dist/standard.js CHANGED
@@ -14,7 +14,26 @@ import { STANDARD_USAGE } from './registry/usage.js';
14
14
  import { printProgress, printResult } from './cli-output.js';
15
15
  export { parseStandardOptions, STANDARD_USAGE };
16
16
  export { STANDARD_PRODUCTS } from './stack-registry.js';
17
+ function assertInitDestination(root, allowRecovery = false) {
18
+ let info;
19
+ try {
20
+ info = lstatSync(root);
21
+ }
22
+ catch (error) {
23
+ if (error.code === 'ENOENT')
24
+ return;
25
+ throw error;
26
+ }
27
+ if (info.isSymbolicLink() || !info.isDirectory())
28
+ throw Error('Destination must be a real directory.');
29
+ if (allowRecovery)
30
+ return;
31
+ const unexpected = readdirSync(root).filter((name) => !['.git', '.gitignore'].includes(name));
32
+ if (unexpected.length)
33
+ throw Error(`Destination must be empty (apart from .git/.gitignore): ${unexpected[0]}`);
34
+ }
17
35
  export async function scaffoldStandardProject(options, run = execFile, output = {}) {
36
+ assertInitDestination(options.root, !options.dryRun);
18
37
  const plan = createSetupPlan(options);
19
38
  const display = { ...output, json: options.json };
20
39
  if (options.dryRun) {
@@ -32,11 +51,7 @@ export async function scaffoldStandardProject(options, run = execFile, output =
32
51
  mkdirSync(root, { recursive: true });
33
52
  created = true;
34
53
  }
35
- if (lstatSync(root).isSymbolicLink() || !lstatSync(root).isDirectory())
36
- throw new Error('Destination must be a real directory.');
37
- const unexpected = readdirSync(root).filter((name) => !['.git', '.gitignore'].includes(name));
38
- if (unexpected.length)
39
- throw new Error(`Destination must be empty (apart from .git/.gitignore): ${unexpected[0]}`);
54
+ assertInitDestination(root, true);
40
55
  const commitPaths = [];
41
56
  await runStagedTransaction(root, {
42
57
  commitPaths,
@@ -44,7 +59,7 @@ export async function scaffoldStandardProject(options, run = execFile, output =
44
59
  prepare: () => {
45
60
  const entries = readdirSync(root).filter((name) => !['.git', '.gitignore', '.anhedral.lock', '.anhedral-txn'].includes(name));
46
61
  if (entries.length)
47
- throw new Error('Destination changed before generation.');
62
+ throw new Error(`Destination must be empty (apart from .git/.gitignore): ${entries[0]}`);
48
63
  },
49
64
  build: async (stageRoot) => {
50
65
  printProgress('Creating the Next.js and Anhedral UI workspace…', display);