anhedral 0.23.0 → 0.24.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 (36) hide show
  1. package/assets/launch/application.server.ts.txt +19 -7
  2. package/assets/launch/application.test.mjs.txt +8 -0
  3. package/assets/launch/home.tsx.txt +23 -1
  4. package/assets/launch/minimal-application.server.ts.txt +2 -2
  5. package/assets/launch/sign-in.tsx.txt +66 -4
  6. package/assets/launch/storage-page.tsx.txt +56 -0
  7. package/assets/stack/backend.test.mjs.txt +10 -0
  8. package/assets/stack/payment.test.mjs.txt +55 -0
  9. package/assets/stack/storage.test.mjs.txt +47 -0
  10. package/dist/bounded-file.d.ts +2 -1
  11. package/dist/bounded-file.js +3 -2
  12. package/dist/composition/command.js +5 -2
  13. package/dist/composition/composition.d.ts +1 -0
  14. package/dist/composition/composition.js +9 -0
  15. package/dist/composition/editor.d.ts +2 -1
  16. package/dist/composition/editor.js +15 -3
  17. package/dist/composition/recipes.d.ts +1 -1
  18. package/dist/composition/recipes.js +17 -2
  19. package/dist/composition/update.js +15 -15
  20. package/dist/dependencies.d.ts +5 -0
  21. package/dist/dependencies.js +9 -0
  22. package/dist/launch.js +14 -1
  23. package/dist/platform/deploy.js +5 -13
  24. package/dist/platform/environment.js +10 -2
  25. package/dist/platform/source.d.ts +2 -0
  26. package/dist/platform/source.js +52 -11
  27. package/dist/platform/state.js +9 -2
  28. package/dist/pnpm-policy.d.ts +1 -0
  29. package/dist/pnpm-policy.js +27 -0
  30. package/dist/scaffold/tanstack.d.ts +1 -1
  31. package/dist/scaffold/tanstack.js +17 -4
  32. package/dist/version.d.ts +1 -1
  33. package/dist/version.js +1 -1
  34. package/docs/capabilities.md +8 -0
  35. package/docs/software-factory.md +15 -6
  36. package/package.json +1 -1
@@ -1,13 +1,25 @@
1
1
  import type { ApplicationContext } from './request-context';
2
2
 
3
- export async function readApplicationStatus(context: ApplicationContext): Promise<{ api: boolean | null; authentication: boolean }> {
3
+ async function backendConnected(api: ApplicationContext['api']): Promise<boolean> {
4
+ if (!api) return false;
4
5
  try {
5
- if (!context.api) return { api: false, authentication: __AUTHENTICATION__ };
6
- const response = await context.api.fetch(new Request('https://api.internal/api/health', { signal: AbortSignal.timeout(5000) }));
7
- if (!response.ok) return { api: false, authentication: __AUTHENTICATION__ };
8
- const result: unknown = await response.json();
9
- return { api: typeof result === 'object' && result !== null && Reflect.get(result, 'ok') === true, authentication: __AUTHENTICATION__ };
6
+ const request = new Request('https://api.internal/api/health', {
7
+ signal: AbortSignal.timeout(5000),
8
+ });
9
+ const response = await api.fetch(request);
10
+ if (!response.ok) return false;
11
+ const body: unknown = await response.json();
12
+ return typeof body === 'object' && body !== null && Reflect.get(body, 'ok') === true;
10
13
  } catch {
11
- return { api: false, authentication: __AUTHENTICATION__ };
14
+ return false;
12
15
  }
13
16
  }
17
+
18
+ export async function readApplicationStatus(context: ApplicationContext) {
19
+ return {
20
+ api: await backendConnected(context.api),
21
+ authentication: __AUTHENTICATION__,
22
+ storage: __STORAGE__,
23
+ payment: __PAYMENT__,
24
+ };
25
+ }
@@ -0,0 +1,8 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+ import { readApplicationStatus } from '../src/lib/application.server.ts';
4
+
5
+ test('the starter renders when no API binding is available', async () => {
6
+ const status = await readApplicationStatus({});
7
+ assert.equal(status.api, status.authentication ? false : null);
8
+ });
@@ -16,5 +16,27 @@ export const Route = createFileRoute('/')({
16
16
  function Home() {
17
17
  const router = useRouter();
18
18
  const status = Route.useLoaderData();
19
- return <section className="stack"><h1>{starterTitle}</h1><p>Your web application is ready to build.</p><p data-rendering="server">Rendered on the server. {status.api === null ? 'Backend not added' : status.api ? 'API: connected' : 'API: unavailable'}.</p>{status.authentication && <a href="/sign-in">Your account</a>}<Button onClick={() => void router.invalidate()}>Check connection</Button></section>;
19
+ return (
20
+ <section className="stack">
21
+ <h1>{starterTitle}</h1>
22
+ <p>
23
+ Edit <code>apps/web/src/routes/index.tsx</code> to change this page.
24
+ </p>
25
+ <p data-rendering="server">
26
+ Rendered on the server.{' '}
27
+ {status.api === null
28
+ ? 'Backend not added'
29
+ : status.api
30
+ ? 'API: connected'
31
+ : 'API: unavailable'}
32
+ .
33
+ </p>
34
+ {status.authentication && <a href="/sign-in">Your account</a>}
35
+ {status.storage && <a href="/storage">Private files</a>}
36
+ {status.payment && <a href="/api/billing/status">Check subscription status</a>}
37
+ {status.api !== null && (
38
+ <Button onClick={() => void router.invalidate()}>Check connection</Button>
39
+ )}
40
+ </section>
41
+ );
20
42
  }
@@ -1,5 +1,5 @@
1
1
  import type { ApplicationContext } from './request-context';
2
2
 
3
- export async function readApplicationStatus(_context: ApplicationContext): Promise<{ api: boolean | null; authentication: boolean }> {
4
- return { api: null, authentication: false };
3
+ export async function readApplicationStatus(_context: ApplicationContext) {
4
+ return { api: null, authentication: false, storage: false, payment: false };
5
5
  }
@@ -24,7 +24,8 @@ function Account() {
24
24
  const result = creating
25
25
  ? await authClient.signUp.email({ email, password, name: String(data.get('name') ?? '') })
26
26
  : await authClient.signIn.email({ email, password });
27
- if (result.error) setError(result.error.message ?? 'Unable to sign in. Check your details and try again.');
27
+ if (result.error)
28
+ setError(result.error.message ?? 'Unable to sign in. Check your details and try again.');
28
29
  else await refetch();
29
30
  } catch {
30
31
  setError('Unable to reach the account service. Try again.');
@@ -47,7 +48,68 @@ function Account() {
47
48
  }
48
49
  }
49
50
  if (isPending) return <p role="status">Loading your account…</p>;
50
- if (sessionError) return <section className="stack"><h1>Account unavailable</h1><p role="alert">Unable to load your account. Check that the API and authentication are configured.</p><Button onClick={() => void refetch()}>Try again</Button></section>;
51
- if (session) return <section className="stack"><h1>Your account</h1><p>{session.user.email}</p>{error && <p role="alert">{error}</p>}<Button disabled={busy} onClick={() => void signOut()}>{busy ? 'Signing out…' : 'Sign out'}</Button></section>;
52
- return <section className="stack"><h1>{creating ? 'Create an account' : 'Sign in'}</h1><p className="muted">Email and password must be explicitly enabled in the API authentication configuration.</p><form onSubmit={submit}>{creating && <><Label htmlFor="name">Name</Label><Input id="name" name="name" autoComplete="name" required maxLength={160} /></>}<Label htmlFor="email">Email</Label><Input id="email" name="email" type="email" autoComplete="email" required maxLength={254} /><Label htmlFor="password">Password</Label><Input id="password" name="password" type="password" autoComplete={creating ? 'new-password' : 'current-password'} required minLength={8} maxLength={128} />{error && <p role="alert">{error}</p>}<Button type="submit" disabled={busy}>{busy ? 'Working…' : creating ? 'Create account' : 'Sign in'}</Button><Button type="button" variant="ghost" disabled={busy} onClick={() => { setCreating(!creating); setError(''); }}>{creating ? 'Already have an account? Sign in' : 'Create an account'}</Button></form></section>;
51
+ if (sessionError)
52
+ return (
53
+ <section className="stack">
54
+ <h1>Account unavailable</h1>
55
+ <p role="alert">
56
+ Unable to load your account. Check that the API and authentication are configured.
57
+ </p>
58
+ <Button onClick={() => void refetch()}>Try again</Button>
59
+ </section>
60
+ );
61
+ if (session)
62
+ return (
63
+ <section className="stack">
64
+ <h1>Your account</h1>
65
+ <p>{session.user.email}</p>
66
+ {error && <p role="alert">{error}</p>}
67
+ <Button disabled={busy} onClick={() => void signOut()}>
68
+ {busy ? 'Signing out…' : 'Sign out'}
69
+ </Button>
70
+ </section>
71
+ );
72
+ return (
73
+ <section className="stack">
74
+ <h1>{creating ? 'Create an account' : 'Sign in'}</h1>
75
+ <p className="muted">
76
+ Email and password must be explicitly enabled in the API authentication configuration.
77
+ </p>
78
+ <form onSubmit={submit}>
79
+ {creating && (
80
+ <>
81
+ <Label htmlFor="name">Name</Label>
82
+ <Input id="name" name="name" autoComplete="name" required maxLength={160} />
83
+ </>
84
+ )}
85
+ <Label htmlFor="email">Email</Label>
86
+ <Input id="email" name="email" type="email" autoComplete="email" required maxLength={254} />
87
+ <Label htmlFor="password">Password</Label>
88
+ <Input
89
+ id="password"
90
+ name="password"
91
+ type="password"
92
+ autoComplete={creating ? 'new-password' : 'current-password'}
93
+ required
94
+ minLength={8}
95
+ maxLength={128}
96
+ />
97
+ {error && <p role="alert">{error}</p>}
98
+ <Button type="submit" disabled={busy}>
99
+ {busy ? 'Working…' : creating ? 'Create account' : 'Sign in'}
100
+ </Button>
101
+ <Button
102
+ type="button"
103
+ variant="ghost"
104
+ disabled={busy}
105
+ onClick={() => {
106
+ setCreating(!creating);
107
+ setError('');
108
+ }}
109
+ >
110
+ {creating ? 'Already have an account? Sign in' : 'Create an account'}
111
+ </Button>
112
+ </form>
113
+ </section>
114
+ );
53
115
  }
@@ -0,0 +1,56 @@
1
+ import { createFileRoute } from '@tanstack/react-router';
2
+ import { useState, type FormEvent } from 'react';
3
+ import { Button } from '@/components/ui/button';
4
+
5
+ export const Route = createFileRoute('/storage')({ component: Storage });
6
+
7
+ function Storage() {
8
+ const [stored, setStored] = useState('');
9
+ const [message, setMessage] = useState('');
10
+ const [busy, setBusy] = useState(false);
11
+
12
+ async function upload(event: FormEvent<HTMLFormElement>) {
13
+ event.preventDefault();
14
+ const file = new FormData(event.currentTarget).get('file');
15
+ if (!(file instanceof File) || !file.name || busy) return;
16
+ setStored('');
17
+ setBusy(true);
18
+ try {
19
+ const path = '/api/files/' + encodeURIComponent(file.name);
20
+ const response = await fetch(path, { method: 'PUT', body: file });
21
+ if (response.ok) setStored(path);
22
+ setMessage(
23
+ response.ok
24
+ ? 'File stored.'
25
+ : response.status === 401
26
+ ? 'Sign in to upload.'
27
+ : 'Upload failed. Check the file name, size, and storage configuration.',
28
+ );
29
+ } catch {
30
+ setMessage('Storage is unavailable.');
31
+ } finally {
32
+ setBusy(false);
33
+ }
34
+ }
35
+
36
+ return (
37
+ <section className="stack">
38
+ <h1>Private files</h1>
39
+ <form onSubmit={upload}>
40
+ <label>
41
+ Choose a file up to 1 MiB <input type="file" name="file" required />
42
+ </label>
43
+ <Button disabled={busy} type="submit">
44
+ Upload
45
+ </Button>
46
+ </form>
47
+ <p role="status">{message}</p>
48
+ {stored && (
49
+ <a href={stored} download>
50
+ Download your file
51
+ </a>
52
+ )}
53
+ <a href="/sign-in">Your account</a>
54
+ </section>
55
+ );
56
+ }
@@ -0,0 +1,10 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+ import app from '../src/index.ts';
4
+
5
+ test('health is public and account data requires configured authentication', async () => {
6
+ const health = await app.request('/api/health', {}, {});
7
+ assert.deepEqual(await health.json(), { ok: true });
8
+ const session = await app.request('/api/session', {}, {});
9
+ assert.equal(session.status, 503);
10
+ });
@@ -0,0 +1,55 @@
1
+ import assert from 'node:assert/strict';
2
+ import { execFileSync } from 'node:child_process';
3
+ import { createHmac, randomUUID } from 'node:crypto';
4
+ import { cp, mkdtemp, readdir, readFile, rm } from 'node:fs/promises';
5
+ import { createRequire } from 'node:module';
6
+ import { tmpdir } from 'node:os';
7
+ import { dirname, join } from 'node:path';
8
+ import { fileURLToPath } from 'node:url';
9
+ import { DatabaseSync } from 'node:sqlite';
10
+ import test from 'node:test';
11
+ import app from '../src/index.ts';
12
+
13
+ test('reviewable local migrations support idempotent signed webhook delivery', async (t) => {
14
+ const root = new URL('../../../packages/db/', import.meta.url);
15
+ const work = await mkdtemp(join(tmpdir(), 'billing-migrations-'));
16
+ t.after(() => rm(work, { recursive: true, force: true }));
17
+ const migrations = join(work, 'drizzle');
18
+ await cp(new URL('drizzle/', root), migrations, { recursive: true });
19
+ const require = createRequire(new URL('package.json', root));
20
+ const cli = join(dirname(require.resolve('drizzle-kit/api')), 'bin.cjs');
21
+ execFileSync(
22
+ process.execPath,
23
+ [cli, 'generate', '--dialect=sqlite', '--schema=' + fileURLToPath(new URL('src/schema.ts', root)), '--out=./drizzle'],
24
+ { cwd: work, stdio: 'pipe' },
25
+ );
26
+ const db = new DatabaseSync(':memory:');
27
+ t.after(() => db.close());
28
+ for (const file of (await readdir(migrations)).filter((name) => name.endsWith('.sql')).sort())
29
+ db.exec(await readFile(join(migrations, file), 'utf8'));
30
+ const env = {
31
+ DB: {
32
+ prepare: (sql) => ({ bind: (...params) => ({ run: () => db.prepare(sql).run(...params) }) }),
33
+ },
34
+ STRIPE_SECRET_KEY: 'sk_test_' + randomUUID(),
35
+ STRIPE_WEBHOOK_SECRET: randomUUID(),
36
+ };
37
+ const body = JSON.stringify({ id: 'evt_local', object: 'event', livemode: false });
38
+ const timestamp = Math.floor(Date.now() / 1000);
39
+ const signature = createHmac('sha256', env.STRIPE_WEBHOOK_SECRET)
40
+ .update(timestamp + '.' + body)
41
+ .digest('hex');
42
+ for (let delivery = 0; delivery < 2; delivery++) {
43
+ const result = await app.request(
44
+ '/api/webhooks/stripe',
45
+ {
46
+ method: 'POST',
47
+ headers: { 'stripe-signature': 't=' + timestamp + ',v1=' + signature },
48
+ body,
49
+ },
50
+ env,
51
+ );
52
+ assert.equal(result.status, 200);
53
+ }
54
+ assert.equal(db.prepare('SELECT COUNT(*) AS count FROM billing_receipt').get().count, 1);
55
+ });
@@ -0,0 +1,47 @@
1
+ import assert from 'node:assert/strict';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { readFile } from 'node:fs/promises';
4
+ import test from 'node:test';
5
+ import { getPlatformProxy } from 'wrangler';
6
+ import { betterAuth } from 'better-auth/minimal';
7
+ import { createAuth } from '../src/auth.ts';
8
+ import app from '../src/index.ts';
9
+
10
+ test('private file round trip and upload size boundary', async (t) => {
11
+ const proxy = await getPlatformProxy({ persist: false, remoteBindings: false, envFiles: [] });
12
+ t.after(() => proxy.dispose());
13
+ const origin = 'http://localhost';
14
+ const env = { ...proxy.env, PUBLIC_APP_URL: origin, BETTER_AUTH_SECRET: randomUUID() };
15
+ const sql = await readFile(
16
+ new URL('../../../packages/db/drizzle/0000_better_auth.sql', import.meta.url),
17
+ 'utf8',
18
+ );
19
+ for (const statement of sql.split('--> statement-breakpoint'))
20
+ await env.DB.prepare(statement.trim()).run();
21
+ const auth = betterAuth({ ...createAuth(env).options, emailAndPassword: { enabled: true } });
22
+ const signup = await auth.api.signUpEmail({
23
+ body: { name: 'Example', email: 'example@example.com', password: randomUUID() },
24
+ asResponse: true,
25
+ });
26
+ assert.equal(signup.status, 200);
27
+ const cookie = signup.headers
28
+ .getSetCookie()
29
+ .map((value) => value.split(';')[0])
30
+ .join('; ');
31
+ const file = '/api/files/sample.bin';
32
+ const limit = 1024 * 1024;
33
+ const bytes = new Uint8Array(limit).fill(42);
34
+ for (const size of [limit, limit + 1]) {
35
+ const body = new Blob([size === limit ? bytes : new Uint8Array(size)]).stream();
36
+ const result = await app.request(
37
+ file,
38
+ { method: 'PUT', headers: { cookie, origin }, body, duplex: 'half' },
39
+ env,
40
+ );
41
+ assert.equal(result.status, size === limit ? 201 : 413);
42
+ }
43
+ const download = await app.request(file, { headers: { cookie } }, env);
44
+ assert.equal(download.status, 200);
45
+ assert.deepEqual(new Uint8Array(await download.arrayBuffer()), bytes);
46
+ assert.equal((await app.request(file, {}, env)).status, 401);
47
+ });
@@ -1,3 +1,4 @@
1
+ import { type Stats } from 'node:fs';
1
2
  export declare const MAX_PROJECT_JSON_BYTES: number;
2
3
  /** Reject devices, links and oversized or growing files before parsing local input. */
3
- export declare function readBoundedFile(filePath: string, maximumBytes: number): Buffer;
4
+ export declare function readBoundedFile(filePath: string, maximumBytes: number, validate?: (opened: Stats) => void): Buffer;
@@ -1,7 +1,7 @@
1
- import { closeSync, constants, fstatSync, lstatSync, openSync, readSync } from 'node:fs';
1
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, } from 'node:fs';
2
2
  export const MAX_PROJECT_JSON_BYTES = 2 * 1024 * 1024;
3
3
  /** Reject devices, links and oversized or growing files before parsing local input. */
4
- export function readBoundedFile(filePath, maximumBytes) {
4
+ export function readBoundedFile(filePath, maximumBytes, validate) {
5
5
  const stat = lstatSync(filePath);
6
6
  if (!stat.isFile() || stat.isSymbolicLink())
7
7
  throw new Error(`Input file must be a regular file: ${filePath}`);
@@ -10,6 +10,7 @@ export function readBoundedFile(filePath, maximumBytes) {
10
10
  const opened = fstatSync(descriptor);
11
11
  if (!opened.isFile())
12
12
  throw new Error(`Input file must be a regular file: ${filePath}`);
13
+ validate?.(opened);
13
14
  if (opened.size > maximumBytes)
14
15
  throw new Error(`Input file exceeds size limit: ${filePath}`);
15
16
  const chunks = [];
@@ -12,7 +12,7 @@ import { put } from '../scaffold/files.js';
12
12
  import { execFile } from '../util.js';
13
13
  import { capabilityReferences } from './references.js';
14
14
  import { configureDependencyPatches } from '../dependency-patches.js';
15
- import { composeSourceProvenance } from './composition.js';
15
+ import { composeSourceProvenance, newerSourceMessage } from './composition.js';
16
16
  export function projectRoot(cwd, allowRecovery = false) {
17
17
  let root = realpathSync(cwd);
18
18
  for (;;) {
@@ -191,6 +191,9 @@ export async function runCapabilityCommand(command, args, output, run = execFile
191
191
  const additions = capabilityOrder(requested, state.installed, parsed.has('--with-dependencies'));
192
192
  const installed = [...state.installed, ...additions];
193
193
  const beforeConfiguration = e.json('anhedral.json');
194
+ const newer = newerSourceMessage(beforeConfiguration.composition?.generatorVersion);
195
+ if (newer)
196
+ throw commandArgumentError('add', newer);
194
197
  const metadataChanged = beforeConfiguration.setup?.cliVersion !== GENERATOR_VERSION ||
195
198
  beforeConfiguration.composition?.generatorVersion !== GENERATOR_VERSION;
196
199
  const foundationChanged = normalizeOjFoundation(e, state.installed, metadataChanged);
@@ -270,7 +273,7 @@ export async function runCapabilityCommand(command, args, output, run = execFile
270
273
  }
271
274
  const format = () => {
272
275
  if (command === 'add')
273
- return `${parsed.has('--dry-run') ? 'Plan' : 'Source additions'}: ${result.added.join(', ') || 'already installed'}\n${result.files.map((file) => ' ' + file).join('\n')}\nReview capability configuration and migrations before deployment. No resources were provisioned.`;
276
+ return `${parsed.has('--dry-run') ? 'Plan' : 'Source additions'}: ${result.added.join(', ') || 'already installed'}\n${result.files.map((file) => ' ' + file).join('\n')}\nReview capability configuration and migrations before deployment. No resources were provisioned.${!parsed.has('--dry-run') && parsed.positional.includes('payment') ? '\nRun pnpm db:generate, review the billing SQL, then run pnpm db:migrate --local before testing webhooks.' : ''}`;
274
277
  else {
275
278
  const rows = parsed.positional[0] === 'list'
276
279
  ? PUBLIC_STACK_ADDITIONS.map((id) => `${id}\t${ANHEDRAL_STACK.additions[id].name}`)
@@ -15,6 +15,7 @@ export declare const launchCompositionSchema: z.ZodObject<{
15
15
  contractVersion: z.ZodLiteral<2>;
16
16
  foundation: z.ZodLiteral<"tanstack-start">;
17
17
  }, z.core.$strict>;
18
+ export declare function newerSourceMessage(version: unknown): string | undefined;
18
19
  /** Local source provenance is never a hosting receipt or a provider activation claim. */
19
20
  export declare function composeSourceProvenance(previous: unknown, installed: readonly Capability[], additions: readonly Capability[]): {
20
21
  generatorVersion: string | null;
@@ -7,6 +7,15 @@ export const launchCompositionSchema = sourceCompositionSchema.safeExtend({
7
7
  foundation: z.literal('tanstack-start'),
8
8
  });
9
9
  const compositionSchema = launchCompositionSchema;
10
+ export function newerSourceMessage(version) {
11
+ if (typeof version !== 'string')
12
+ return;
13
+ const source = version.split(/[.-]/).slice(0, 3).map(Number);
14
+ const current = GENERATOR_VERSION.split(/[.-]/).slice(0, 3).map(Number);
15
+ const different = source.findIndex((part, index) => part !== current[index]);
16
+ if (different >= 0 && source[different] > current[different])
17
+ return 'This source was generated by a newer CLI. Use that version or a newer published CLI; source downgrades are not supported.';
18
+ }
10
19
  /** Local source provenance is never a hosting receipt or a provider activation claim. */
11
20
  export function composeSourceProvenance(previous, installed, additions) {
12
21
  const old = compositionSchema.parse(previous);
@@ -3,9 +3,10 @@ export declare const fingerprint: (source: string | Buffer) => string;
3
3
  export declare class CapabilityEditor {
4
4
  readonly root: string;
5
5
  readonly managed: Record<string, string>;
6
+ private readonly operation;
6
7
  readonly writes: Map<string, string>;
7
8
  readonly before: Map<string, string | null>;
8
- constructor(root: string, managed: Record<string, string>);
9
+ constructor(root: string, managed: Record<string, string>, operation?: 'add' | 'update');
9
10
  private file;
10
11
  read(relative: string): string | null;
11
12
  json(relative: string): Record<string, any>;
@@ -8,11 +8,13 @@ export const fingerprint = (source) => createHash('sha256').update(source).diges
8
8
  export class CapabilityEditor {
9
9
  root;
10
10
  managed;
11
+ operation;
11
12
  writes = new Map();
12
13
  before = new Map();
13
- constructor(root, managed) {
14
+ constructor(root, managed, operation = 'add') {
14
15
  this.root = root;
15
16
  this.managed = managed;
17
+ this.operation = operation;
16
18
  }
17
19
  file(relative) {
18
20
  if (!relative ||
@@ -81,12 +83,22 @@ export class CapabilityEditor {
81
83
  }
82
84
  owned(relative, source) {
83
85
  const current = this.read(relative);
86
+ const desiredDigest = fingerprint(source);
87
+ // The recorded digest is the common baseline for release and local edits.
88
+ if (this.operation === 'update' && current !== null) {
89
+ if (current === source) {
90
+ this.managed[relative] = desiredDigest;
91
+ return;
92
+ }
93
+ if (this.managed[relative] === desiredDigest)
94
+ return;
95
+ }
84
96
  if (current !== null &&
85
97
  !this.writes.has(relative) &&
86
98
  this.managed[relative] !== fingerprint(current))
87
- throw Error(`Preserve edited generated source: ${relative}. Reconcile it before adding capabilities. No files were changed.`);
99
+ throw Error(`Preserve edited generated source: ${relative}. Reconcile it before applying stack changes. No files were changed.`);
88
100
  this.writes.set(relative, source);
89
- this.managed[relative] = fingerprint(source);
101
+ this.managed[relative] = desiredDigest;
90
102
  }
91
103
  set(relative, keys, value) {
92
104
  const source = this.read(relative);
@@ -1,4 +1,4 @@
1
1
  import { CapabilityEditor } from './editor.js';
2
2
  import type { Capability } from './catalog.js';
3
3
  export declare function addCapabilityRecipe(e: CapabilityEditor, id: Capability, name: string): void;
4
- export declare function composeCapabilities(e: CapabilityEditor, installed: Capability[]): void;
4
+ export declare function composeCapabilities(e: CapabilityEditor, installed: Capability[], operation?: 'compose' | 'update'): void;
@@ -47,15 +47,24 @@ function schemaExport(e, module) {
47
47
  e.writes.set(file, source + `\nexport * from './${module}';\n`);
48
48
  }
49
49
  export function addCapabilityRecipe(e, id, name) {
50
+ if (id === 'r2' || id === 'stripe') {
51
+ const manifest = e.json('apps/api/package.json');
52
+ if (!manifest.scripts?.test)
53
+ e.set('apps/api/package.json', ['scripts', 'test'], 'node --import tsx --test tests/*.test.mjs');
54
+ if (!manifest.devDependencies?.tsx && !manifest.dependencies?.tsx)
55
+ e.set('apps/api/package.json', ['devDependencies', 'tsx'], P.tsx);
56
+ }
50
57
  switch (id) {
51
58
  case 'hono': {
52
59
  project(e, 'apps/api', '@workspace/api', {
60
+ test: 'node --import tsx --test tests/*.test.mjs',
53
61
  dev: 'wrangler dev --port 8787 --inspector-port 9231',
54
62
  build: 'wrangler deploy --dry-run --outdir dist',
55
63
  deploy: 'wrangler deploy',
56
64
  typecheck: 'wrangler types && tsc --noEmit',
57
65
  lint: 'eslint . --max-warnings 0',
58
66
  }, { hono: D.hono }, {
67
+ tsx: P.tsx,
59
68
  wrangler: D.wrangler,
60
69
  '@types/node': D['@types/node'],
61
70
  eslint: D.eslint,
@@ -83,6 +92,7 @@ export function addCapabilityRecipe(e, id, name) {
83
92
  include: ['src/**/*.ts', 'worker-configuration.d.ts'],
84
93
  }));
85
94
  e.create('apps/api/eslint.config.mjs', "import { config } from '@workspace/eslint-config/base';\nexport default [...config, {ignores:['dist/**','.wrangler/**','worker-configuration.d.ts']}];\n");
95
+ e.create('apps/api/tests/backend.test.mjs', template('backend.test.mjs.txt'));
86
96
  e.create('apps/api/src/index.ts', template('api-index.ts.txt'));
87
97
  e.create('apps/api/src/custom-environment.ts', 'export type CustomBindings = Record<never, never>;\nexport type CustomVariables = Record<never, never>;\n');
88
98
  const web = 'apps/web/wrangler.jsonc';
@@ -167,10 +177,13 @@ export function addCapabilityRecipe(e, id, name) {
167
177
  break;
168
178
  }
169
179
  case 'r2':
180
+ e.create('apps/api/tests/storage.test.mjs', template('storage.test.mjs.txt'));
181
+ e.create('apps/web/src/routes/storage.tsx', readFileSync(new URL('../../assets/launch/storage-page.tsx.txt', import.meta.url), 'utf8'));
170
182
  apiConfig(e, 'r2_buckets', [{ binding: 'FILES', bucket_name: resourceName(name, 'files') }]);
171
183
  e.create('apps/api/src/features/storage.ts', template('storage.ts.txt'));
172
184
  break;
173
185
  case 'stripe':
186
+ e.create('apps/api/tests/payment.test.mjs', template('payment.test.mjs.txt'));
174
187
  dependency(e, 'apps/api', { stripe: P.stripe });
175
188
  e.create('apps/api/src/features/stripe.ts', template('stripe.ts.txt'));
176
189
  e.create('apps/api/src/billing-mode.ts', template('billing-mode.ts.txt'));
@@ -181,8 +194,8 @@ export function addCapabilityRecipe(e, id, name) {
181
194
  break;
182
195
  }
183
196
  }
184
- export function composeCapabilities(e, installed) {
185
- composeTanstack(e, installed);
197
+ export function composeCapabilities(e, installed, operation = 'compose') {
198
+ composeTanstack(e, installed, operation === 'update');
186
199
  if (!installed.includes('hono'))
187
200
  return;
188
201
  const features = [
@@ -214,6 +227,8 @@ export function composeCapabilities(e, installed) {
214
227
  if (installed.includes('stripe'))
215
228
  bindings.push('STRIPE_SECRET_KEY?: string', 'STRIPE_WEBHOOK_SECRET?: string', 'STRIPE_PRICE_ID?: string', 'BILLING_ENVIRONMENT?: string', 'BILLING_PROVIDER?: string');
216
229
  e.owned('apps/api/src/environment.ts', `import type { CustomBindings, CustomVariables } from './custom-environment';\nexport type AppEnv = { Bindings: CustomBindings & {${bindings.join(';\n')}}; Variables: CustomVariables & {userId:string;fileKey:string} };\n`);
230
+ if (operation === 'update')
231
+ return;
217
232
  appendExample(e, 'apps/api/.dev.vars.example', bindings
218
233
  .filter((binding) => binding.includes('string'))
219
234
  .map((binding) => binding.split('?')[0]));
@@ -9,8 +9,8 @@ import { CliFailure } from '../cli-errors.js';
9
9
  import { createReporter } from '../cli-output.js';
10
10
  import { assertPublicWorkspace, projectRoot, readState } from './command.js';
11
11
  import { CapabilityEditor, fingerprint } from './editor.js';
12
- import { normalizeOjFoundation } from '../scaffold/tanstack.js';
13
- import { composeSourceProvenance } from './composition.js';
12
+ import { composeCapabilities } from './recipes.js';
13
+ import { composeSourceProvenance, newerSourceMessage } from './composition.js';
14
14
  import { GENERATOR_VERSION } from '../version.js';
15
15
  import { runStagedTransaction } from '../transactions/transaction.js';
16
16
  import { put } from '../scaffold/files.js';
@@ -162,22 +162,15 @@ export function planStackUpdate(root, artifact) {
162
162
  (!isPublishedCliArtifact(artifact) || artifact.version !== GENERATOR_VERSION))
163
163
  throw Error('Only a verified published artifact matching this CLI can update deployment provenance.');
164
164
  assertPublicWorkspace(root, false, 'stack');
165
- const e = new CapabilityEditor(root, {});
165
+ const e = new CapabilityEditor(root, {}, 'update');
166
166
  const state = readState(e);
167
167
  Object.assign(e.managed, state.managedFiles);
168
168
  const configuration = e.json('anhedral.json');
169
169
  const previousVersion = configuration.composition.generatorVersion;
170
170
  const conflicts = [];
171
- if (typeof previousVersion === 'string') {
172
- const old = previousVersion.split(/[.-]/).slice(0, 3).map(Number);
173
- const current = GENERATOR_VERSION.split(/[.-]/).slice(0, 3).map(Number);
174
- const differing = old.findIndex((value, index) => value !== current[index]);
175
- if (differing >= 0 && old[differing] > current[differing])
176
- conflicts.push({
177
- code: 'NEWER_SOURCE',
178
- message: 'This source was generated by a newer CLI. Use that version or a newer published CLI; source downgrades are not supported.',
179
- });
180
- }
171
+ const newer = newerSourceMessage(previousVersion);
172
+ if (newer)
173
+ conflicts.push({ code: 'NEWER_SOURCE', message: newer });
181
174
  const attempt = (action) => {
182
175
  try {
183
176
  action();
@@ -196,7 +189,7 @@ export function planStackUpdate(root, artifact) {
196
189
  });
197
190
  attempt(() => {
198
191
  updateRootStylesheet(e);
199
- normalizeOjFoundation(e, state.installed, true);
192
+ composeCapabilities(e, state.installed, 'update');
200
193
  });
201
194
  attempt(() => updatePnpmPolicy(e));
202
195
  let artifactRequired = true;
@@ -342,5 +335,12 @@ export async function runStackUpdate(args, output, dependencies = {}) {
342
335
  if (plan.conflicts.length)
343
336
  process.exitCode = 1;
344
337
  const terminalSafe = (value) => stripVTControlCharacters(value.replace(/\r\n/g, '\n')).replace(/[\x00-\x08\x0b-\x1f\x7f]/g, '');
345
- createReporter(output, () => terminalSafe(`${applied ? 'Applied' : 'Preview'} source update ${plan.fromVersion ?? 'unknown'} → ${plan.toVersion}\nPlan: ${plan.planId}\n${plan.changes.map((change) => change.diff).join('\n')}${plan.conflicts.map((conflict) => conflict.message).join('\n')}\n${plan.nextAction}`)).result({ ...plan, dryRun: parsed.has('--dry-run'), applied });
338
+ const nextAction = plan.conflicts.length
339
+ ? 'Resolve the listed conflicts, then preview the update again.'
340
+ : !entries.length
341
+ ? 'Your generated stack files are up to date.'
342
+ : applied
343
+ ? 'Run pnpm install and pnpm check in the project directory.'
344
+ : `Apply this preview with pnpm dlx anhedral@${GENERATOR_VERSION} stack update${parsed.has('--offline') ? ' --offline' : ''} --expect-plan ${plan.planId}`;
345
+ createReporter(output, () => terminalSafe(`${applied ? 'Applied' : 'Preview'} source update ${plan.fromVersion ?? 'unknown'} → ${plan.toVersion}\nPlan: ${plan.planId}\n${plan.changes.map((change) => change.diff).join('\n')}${plan.conflicts.map((conflict) => conflict.message).join('\n')}\n${nextAction}`)).result({ ...plan, nextAction, dryRun: parsed.has('--dry-run'), applied });
346
346
  }
@@ -39,7 +39,12 @@ export declare const WORKER_DEV_PORTS: {
39
39
  };
40
40
  };
41
41
  export declare const CAPABILITY_DEPENDENCIES: {
42
+ readonly tsx: "4.23.15";
42
43
  readonly 'better-auth': "1.7.7";
43
44
  readonly '@better-auth/drizzle-adapter': "1.7.7";
44
45
  readonly stripe: "23.0.0";
45
46
  };
47
+ export declare const SECURITY_OVERRIDES: {
48
+ readonly 'esbuild@0.18.20': "0.28.2";
49
+ readonly 'minimatch@10.2.6': "11.0.1";
50
+ };
@@ -88,9 +88,18 @@ export const STACK_DEPENDENCIES = {
88
88
  export const WORKER_DEV_PORTS = { api: { http: 8787, inspector: 9231 } };
89
89
  // Backend, storage and payments extend the same Anhedral Stack foundation.
90
90
  export const CAPABILITY_DEPENDENCIES = {
91
+ tsx: '4.23.15',
91
92
  // renovate: datasource=npm depName=better-auth
92
93
  'better-auth': '1.7.7',
93
94
  // renovate: datasource=npm depName=@better-auth/drizzle-adapter
94
95
  '@better-auth/drizzle-adapter': '1.7.7',
95
96
  stripe: '23.0.0',
96
97
  };
98
+ // renovate: datasource=npm depName=esbuild
99
+ const DRIZZLE_ESBUILD_VERSION = '0.28.2';
100
+ // renovate: datasource=npm depName=minimatch
101
+ const ESLINT_MINIMATCH_VERSION = '11.0.1';
102
+ export const SECURITY_OVERRIDES = {
103
+ 'esbuild@0.18.20': DRIZZLE_ESBUILD_VERSION,
104
+ 'minimatch@10.2.6': ESLINT_MINIMATCH_VERSION,
105
+ };
package/dist/launch.js CHANGED
@@ -13,7 +13,7 @@ import { runStagedTransaction } from './transactions/transaction.js';
13
13
  import { configureDependencyPatches, writeDependencyAudit } from './dependency-patches.js';
14
14
  import { setPnpmPolicy } from './pnpm-policy.js';
15
15
  import { GENERATOR_VERSION } from './version.js';
16
- import { PACKAGE_MANAGER, STACK_DEPENDENCIES, WORKSPACE_NODE_ENGINE } from './dependencies.js';
16
+ import { PACKAGE_MANAGER, SECURITY_OVERRIDES, STACK_DEPENDENCIES, WORKSPACE_NODE_ENGINE, } from './dependencies.js';
17
17
  import { execFile, appendGitignore } from './util.js';
18
18
  import { printProgress, printResult } from './cli-output.js';
19
19
  import { CliArgumentError, commandArguments } from './cli-arguments.js';
@@ -68,6 +68,7 @@ function rootFiles(root, name) {
68
68
  setPnpmPolicy(root, {
69
69
  packages: ['apps/*', 'packages/*'],
70
70
  sharedWorkspaceLockfile: true,
71
+ overrides: SECURITY_OVERRIDES,
71
72
  allowBuilds: { esbuild: true, workerd: true },
72
73
  });
73
74
  json(root, 'anhedral.json', {
@@ -135,6 +136,18 @@ run pnpm db:generate, review the SQL, then deliberately apply the local migratio
135
136
  before exercising subscription/webhook flows. Configure Stripe test credentials,
136
137
  allowed prices and signed webhooks; activation and live payments are separate.
137
138
 
139
+ ## Update the stack
140
+
141
+ From the project directory, preview a release before applying it:
142
+
143
+ \`\`\`sh
144
+ pnpm dlx anhedral@latest stack update --dry-run --human
145
+ \`\`\`
146
+
147
+ Review the diff and run the version-pinned apply command printed by the CLI.
148
+ Then run \`pnpm install\` and \`pnpm check\`. The updater refreshes CLI-managed
149
+ adapters for installed features. Your routes, UI and migrations belong to you.
150
+
138
151
  ## Ownership and deployment
139
152
 
140
153
  Hono owns data, identity and private storage. Web server functions call its scoped
@@ -1,5 +1,5 @@
1
1
  import { createHash, randomUUID } from 'node:crypto';
2
- import { constants } from 'node:fs';
2
+ import { readBoundedFile } from '../bounded-file.js';
3
3
  import { join, resolve } from 'node:path';
4
4
  import { z } from 'zod';
5
5
  import { commandArgumentError } from '../cli-arguments.js';
@@ -58,21 +58,13 @@ export async function runDeploy({ options, origin, actor, token, stateDir, link,
58
58
  const file = options.value('--manifest');
59
59
  if (!file)
60
60
  throw commandArgumentError(command, 'Use deploy plan --manifest <file>.');
61
- const handle = await import('node:fs/promises').then((fs) => fs.open(resolve(file), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK));
61
+ const source = readBoundedFile(resolve(file), 32768);
62
62
  let manifest;
63
63
  try {
64
- const info = await handle.stat();
65
- if (!info.isFile() || info.size > 32768)
66
- throw platformFailure('Deployment manifest exceeds its limit.');
67
- try {
68
- manifest = JSON.parse(await handle.readFile('utf8'));
69
- }
70
- catch {
71
- throw commandArgumentError(command, 'The deployment manifest is not valid JSON. Review it before retrying.');
72
- }
64
+ manifest = JSON.parse(source.toString('utf8'));
73
65
  }
74
- finally {
75
- await handle.close();
66
+ catch {
67
+ throw commandArgumentError(command, 'The deployment manifest is not valid JSON. Review it before retrying.');
76
68
  }
77
69
  const checkedManifest = deploymentManifestSchema.safeParse(manifest);
78
70
  if (!checkedManifest.success)
@@ -1,6 +1,6 @@
1
1
  import { randomUUID } from 'node:crypto';
2
- import { closeSync, constants, fstatSync, lstatSync, openSync, readSync } from 'node:fs';
3
- import { dirname, join, resolve } from 'node:path';
2
+ import { closeSync, constants, existsSync, fstatSync, lstatSync, openSync, readSync, } from 'node:fs';
3
+ import { basename, dirname, join, resolve } from 'node:path';
4
4
  import { z } from 'zod';
5
5
  import { commandArgumentError, commandArguments } from '../cli-arguments.js';
6
6
  import { createReporter } from '../cli-output.js';
@@ -30,10 +30,17 @@ const planSchema = z
30
30
  .strict();
31
31
  export function readEnvironmentSecret(file) {
32
32
  const path = resolve(file);
33
+ const cwd = lstatSync('.');
34
+ let excluded = /^(?:\.env|\.dev\.vars)/i.test(basename(path));
33
35
  for (let parent = dirname(path);; parent = dirname(parent)) {
34
36
  const info = lstatSync(parent);
35
37
  if (!info.isDirectory() || info.isSymbolicLink())
36
38
  throw platformFailure('Environment input has a symlinked or invalid directory.');
39
+ if (!excluded &&
40
+ ((info.dev === cwd.dev && info.ino === cwd.ino) || existsSync(join(parent, 'anhedral.json'))))
41
+ throw platformFailure('Environment input inside a project must use an excluded .env file or .anhedral directory. Use --stdin or a private file outside the project.');
42
+ if (basename(parent).toLowerCase() === '.anhedral')
43
+ excluded = true;
37
44
  if (dirname(parent) === parent)
38
45
  break;
39
46
  }
@@ -41,6 +48,7 @@ export function readEnvironmentSecret(file) {
41
48
  try {
42
49
  const info = fstatSync(descriptor);
43
50
  if (!info.isFile() ||
51
+ info.nlink !== 1 ||
44
52
  info.size > ENVIRONMENT_FILE_MAX_BYTES ||
45
53
  (process.platform !== 'win32' &&
46
54
  (info.uid !== process.getuid?.() || (info.mode & 0o077) !== 0)))
@@ -1,3 +1,5 @@
1
+ import { type FileHandle } from 'node:fs/promises';
2
+ export declare function anchoredDirectory(handle: FileHandle): Promise<string>;
1
3
  export declare function packageSource(root: string): Promise<{
2
4
  archive: Uint8Array<ArrayBuffer>;
3
5
  inventoryDigest: string;
@@ -1,18 +1,39 @@
1
1
  import ignore from 'ignore';
2
+ import { readBoundedFile } from '../bounded-file.js';
2
3
  import { constants } from 'node:fs';
3
- import { lstat, open, readFile, readdir } from 'node:fs/promises';
4
- import { join } from 'node:path';
4
+ import { lstat, open, readdir, stat } from 'node:fs/promises';
5
+ import { join, resolve } from 'node:path';
5
6
  import { sourceContainsCredential as localCredentialMaterial } from '../../assets/security/credential-patterns.mjs';
6
7
  import { SOURCE_LIMITS, sourceContainsCredential, uploadExcluded, uploadSecret, } from '../contracts/cli-transport.js';
7
8
  import { packSource, setSourceExecutable, sourceInventory, validateSourcePath, } from '../contracts/source-bundle.js';
8
9
  import { excludedSource, generatedSource, secretSource } from '../contracts/source-profile.js';
9
10
  import { platformFailure } from './state.js';
11
+ // Keep the directory open throughout all child lookups. These OS namespaces
12
+ // address the open object even if a writer renames its original directory.
13
+ export async function anchoredDirectory(handle) {
14
+ const identity = await handle.stat({ bigint: true });
15
+ const path = process.platform === 'linux'
16
+ ? '/proc/self/fd/' + handle.fd
17
+ : '/.vol/' + identity.dev + '/' + identity.ino;
18
+ const resolved = await stat(path, { bigint: true }).catch(() => null);
19
+ if (!identity.isDirectory() || identity.dev !== resolved?.dev || identity.ino !== resolved.ino)
20
+ throw platformFailure('This filesystem cannot safely anchor source directories for upload.');
21
+ return path;
22
+ }
10
23
  export async function packageSource(root) {
24
+ if (!['linux', 'darwin'].includes(process.platform))
25
+ throw platformFailure('Source packaging requires Linux procfs or a macOS volume supporting directory IDs. On Windows, run the CLI inside WSL.');
26
+ const directoryFlags = constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW;
11
27
  const files = new Map();
12
28
  let bytes = 0;
13
- async function walk(relative, rules) {
14
- const directory = join(root, relative);
15
- const gitignore = await lstat(join(directory, '.gitignore')).catch(() => null);
29
+ async function walk(handle, relative, rules) {
30
+ const directory = await anchoredDirectory(handle);
31
+ const ignorePath = join(directory, '.gitignore');
32
+ const gitignore = await lstat(ignorePath).catch((error) => {
33
+ if (error.code === 'ENOENT')
34
+ return null;
35
+ throw error;
36
+ });
16
37
  if (gitignore && (!gitignore.isFile() || gitignore.isSymbolicLink()))
17
38
  throw platformFailure('Source ignore file is unsafe.');
18
39
  if (gitignore) {
@@ -22,13 +43,17 @@ export async function packageSource(root) {
22
43
  ...rules,
23
44
  {
24
45
  base: relative,
25
- matcher: ignore().add(await readFile(join(directory, '.gitignore'), 'utf8')),
46
+ matcher: ignore().add(readBoundedFile(ignorePath, 65536, (opened) => {
47
+ if (opened.dev !== gitignore.dev || opened.ino !== gitignore.ino)
48
+ throw platformFailure('Source ignore file changed during packaging.');
49
+ }).toString('utf8')),
26
50
  },
27
51
  ];
28
52
  }
29
53
  for (const entry of (await readdir(directory, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
30
54
  const path = relative ? `${relative}/${entry.name}` : entry.name;
31
- if (excludedSource.test(path) ||
55
+ if (/^(?:\.env|\.dev\.vars|\.anhedral$)/i.test(entry.name) ||
56
+ excludedSource.test(path) ||
32
57
  generatedSource.test(path) ||
33
58
  secretSource.test(path) ||
34
59
  uploadExcluded.test(path) ||
@@ -44,17 +69,27 @@ export async function packageSource(root) {
44
69
  }
45
70
  if (ignored)
46
71
  continue;
47
- const info = await lstat(join(root, path));
72
+ const childPath = join(directory, entry.name);
73
+ const info = await lstat(childPath);
48
74
  if (info.isSymbolicLink() || (!info.isFile() && !info.isDirectory()))
49
75
  throw platformFailure('Source contains a symbolic link or special file. Exclude it before uploading.');
50
76
  validateSourcePath(path);
51
77
  if (info.isDirectory()) {
52
- await walk(path, rules);
78
+ const child = await open(childPath, directoryFlags);
79
+ try {
80
+ const opened = await child.stat();
81
+ if (opened.dev !== info.dev || opened.ino !== info.ino)
82
+ throw platformFailure('Source directory changed during packaging.');
83
+ await walk(child, path, rules);
84
+ }
85
+ finally {
86
+ await child.close();
87
+ }
53
88
  continue;
54
89
  }
55
90
  if (files.size >= SOURCE_LIMITS.files || (bytes += info.size) > SOURCE_LIMITS.bytes)
56
91
  throw platformFailure('Source exceeds its file or byte limit.');
57
- const handle = await open(join(root, path), constants.O_RDONLY | constants.O_NOFOLLOW);
92
+ const handle = await open(childPath, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
58
93
  let content;
59
94
  try {
60
95
  const before = await handle.stat();
@@ -86,7 +121,13 @@ export async function packageSource(root) {
86
121
  setSourceExecutable(files, path, Boolean(info.mode & 0o111));
87
122
  }
88
123
  }
89
- await walk('', []);
124
+ const rootHandle = await open(resolve(root) === process.cwd() ? '.' : root, directoryFlags);
125
+ try {
126
+ await walk(rootHandle, '', []);
127
+ }
128
+ finally {
129
+ await rootHandle.close();
130
+ }
90
131
  const config = files.get('anhedral.json');
91
132
  if (!config || !files.has('pnpm-lock.yaml'))
92
133
  throw platformFailure('Upload requires anhedral.json and pnpm-lock.yaml.');
@@ -1,7 +1,8 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import { createHash, randomUUID } from 'node:crypto';
3
- import { lstat, mkdir, open, readFile, rename, unlink, writeFile } from 'node:fs/promises';
3
+ import { lstat, mkdir, open, rename, unlink, writeFile } from 'node:fs/promises';
4
4
  import { dirname, join } from 'node:path';
5
+ import { readBoundedFile } from '../bounded-file.js';
5
6
  import { CliArgumentError } from '../cli-arguments.js';
6
7
  import { CliFailure } from '../cli-errors.js';
7
8
  import { trustedLinuxCredentialHelper } from './credential-helper.js';
@@ -65,7 +66,13 @@ export async function readPrivate(path) {
65
66
  info.size > 65536 ||
66
67
  (process.platform !== 'win32' && ((info.mode & 0o077) !== 0 || info.uid !== process.getuid?.())))
67
68
  throw platformFailure('State file must be owned by you with mode 0600.');
68
- const text = await readFile(path, 'utf8');
69
+ const text = readBoundedFile(path, 65536, (opened) => {
70
+ if (opened.dev !== info.dev ||
71
+ opened.ino !== info.ino ||
72
+ (process.platform !== 'win32' &&
73
+ ((opened.mode & 0o077) !== 0 || opened.uid !== process.getuid?.())))
74
+ throw platformFailure('State file changed or has unsafe permissions.');
75
+ }).toString('utf8');
69
76
  try {
70
77
  return JSON.parse(text);
71
78
  }
@@ -2,3 +2,4 @@
2
2
  export declare function setPnpmPolicy(root: string, policy: Record<string, unknown>): void;
3
3
  /** Extend a pnpm patch map without replacing unrelated patches or YAML comments. */
4
4
  export declare function pnpmPatchPolicy(source: string, coordinate: string, patch: string): string;
5
+ export declare function secureWorkspacePolicy(source: string): string;
@@ -1,3 +1,4 @@
1
+ import { SECURITY_OVERRIDES } from './dependencies.js';
1
2
  import { existsSync, readFileSync } from 'node:fs';
2
3
  import path from 'node:path';
3
4
  import { writeFile } from './util.js';
@@ -38,3 +39,29 @@ export function pnpmPatchPolicy(source, coordinate, patch) {
38
39
  mapping.set(coordinate, patch);
39
40
  return document.toString({ lineWidth: 0 });
40
41
  }
42
+ export function secureWorkspacePolicy(source) {
43
+ const document = parseDocument(source);
44
+ if (document.errors.length || !isMap(document.contents))
45
+ throw Error('Invalid pnpm workspace YAML; review dependency overrides.');
46
+ if (!document.has('overrides')) {
47
+ const newline = source.includes('\r\n') ? '\r\n' : '\n';
48
+ return (source +
49
+ (source.endsWith('\n') ? '' : newline) +
50
+ 'overrides: ' +
51
+ JSON.stringify(SECURITY_OVERRIDES) +
52
+ newline);
53
+ }
54
+ const overrides = document.get('overrides', true);
55
+ if (!isMap(overrides))
56
+ throw Error('Expected an explicit pnpm overrides mapping.');
57
+ let changed = false;
58
+ for (const [selector, version] of Object.entries(SECURITY_OVERRIDES)) {
59
+ if (overrides.get(selector) === version)
60
+ continue;
61
+ if (overrides.has(selector))
62
+ throw Error('Review conflicting pnpm override for ' + selector);
63
+ overrides.set(selector, version);
64
+ changed = true;
65
+ }
66
+ return changed ? document.toString({ lineWidth: 0 }) : source;
67
+ }
@@ -5,6 +5,6 @@ export declare function scaffoldTanstack(root: string, name: string): void;
5
5
  /** One-time source upgrade, planned in the same bounded overlay as each addition. */
6
6
  export declare function normalizeOjFoundation(e: CapabilityEditor, installed: readonly Capability[], refreshConfiguration?: boolean): boolean;
7
7
  /** Fingerprinted composition adapters; application routes stay source-owned. */
8
- export declare function composeTanstack(e: CapabilityEditor, installed: readonly Capability[]): void;
8
+ export declare function composeTanstack(e: CapabilityEditor, installed: readonly Capability[], refreshConfiguration?: boolean): void;
9
9
  /** Install account source only when the backend authentication capability is added. */
10
10
  export declare function addTanstackAuth(e: CapabilityEditor): void;
@@ -1,3 +1,4 @@
1
+ import { secureWorkspacePolicy } from '../pnpm-policy.js';
1
2
  import { readFileSync } from 'node:fs';
2
3
  import { ANHEDRAL_STACK_DEPENDENCIES, WEB_DEPENDENCIES } from '../dependencies.js';
3
4
  import { CapabilityEditor, fingerprint } from '../composition/editor.js';
@@ -15,6 +16,7 @@ export function scaffoldTanstack(root, name) {
15
16
  version: '0.1.0',
16
17
  type: 'module',
17
18
  scripts: {
19
+ test: 'node --experimental-strip-types --test tests/*.test.mjs',
18
20
  dev: 'node ../../scripts/oj.mjs dev . --host=0.0.0.0 --port 3000',
19
21
  build: 'node ../../scripts/oj.mjs build .',
20
22
  preview: 'wrangler dev --config dist/ssr/wrangler.json --port 3000',
@@ -107,6 +109,7 @@ export function cn(...values: ClassValue[]) { return twMerge(clsx(values)); }
107
109
  put(root, `${app}/postcss.config.mjs`, "export default { plugins: { '@tailwindcss/postcss': {} } };\n");
108
110
  put(root, `${app}/src/starter.ts`, `export const starterTitle = ${JSON.stringify(name)};\n`);
109
111
  const files = {
112
+ 'tests/application.test.mjs': 'application.test.mjs.txt',
110
113
  'src/router.tsx': 'router.tsx.txt',
111
114
  'src/lib/request-context.ts': 'request-context.ts.txt',
112
115
  'src/routes/__root.tsx': 'root.tsx.txt',
@@ -170,7 +173,14 @@ export function normalizeOjFoundation(e, installed, refreshConfiguration = false
170
173
  if (current !== undefined && current !== desired && current !== previous && !previousOjDev)
171
174
  throw Error(`Preserve customized web launcher scripts.${name}. Reconcile it with the pinned OJ runtime before adding capabilities. No files were changed.`);
172
175
  }
173
- let changed = false;
176
+ const workspace = 'pnpm-workspace.yaml';
177
+ const previousPolicy = e.read(workspace);
178
+ if (previousPolicy === null)
179
+ throw Error('Missing pnpm workspace configuration.');
180
+ const policy = secureWorkspacePolicy(previousPolicy);
181
+ let changed = policy !== previousPolicy;
182
+ if (changed)
183
+ e.writes.set(workspace, policy);
174
184
  const serverEntry = 'apps/web/src/server.ts';
175
185
  const currentEntry = e.read(serverEntry);
176
186
  // Repair only the exact shipped adapter whose default-entry shim drops Start context in OJ.
@@ -228,13 +238,16 @@ export function normalizeOjFoundation(e, installed, refreshConfiguration = false
228
238
  return changed;
229
239
  }
230
240
  /** Fingerprinted composition adapters; application routes stay source-owned. */
231
- export function composeTanstack(e, installed) {
241
+ export function composeTanstack(e, installed, refreshConfiguration = false) {
232
242
  assertTanstack(e);
233
- normalizeOjFoundation(e, installed);
243
+ normalizeOjFoundation(e, installed, refreshConfiguration);
234
244
  const backend = installed.includes('hono');
235
245
  const auth = installed.includes('database-auth');
236
246
  e.owned('apps/web/src/server.ts', template(backend ? 'server.ts.txt' : 'minimal-server.ts.txt'));
237
- e.owned('apps/web/src/lib/application.server.ts', template(backend ? 'application.server.ts.txt' : 'minimal-application.server.ts.txt').replaceAll('__AUTHENTICATION__', String(auth)));
247
+ e.owned('apps/web/src/lib/application.server.ts', template(backend ? 'application.server.ts.txt' : 'minimal-application.server.ts.txt')
248
+ .replaceAll('__AUTHENTICATION__', String(auth))
249
+ .replaceAll('__STORAGE__', String(installed.includes('r2')))
250
+ .replaceAll('__PAYMENT__', String(installed.includes('stripe'))));
238
251
  e.owned('apps/web/vite.config.ts', tanstackViteConfiguration(installed));
239
252
  }
240
253
  /** Install account source only when the backend authentication capability is added. */
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const GENERATOR_VERSION = "0.23.0";
1
+ export declare const GENERATOR_VERSION = "0.24.0";
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const GENERATOR_VERSION = '0.23.0';
1
+ export const GENERATOR_VERSION = '0.24.0';
@@ -21,6 +21,12 @@ Use `add storage` in place of `add r2`, and `add payment` in place of `add strip
21
21
 
22
22
  `backend` is one public selection; its provenance records the concrete Hono and database/auth capabilities. Use `--with-dependencies` to include missing prerequisites in the same planned source transaction. `stack list` describes this stack's additions. `status`/`doctor` check source completeness, not live service activation.
23
23
 
24
+ ## Updating an existing app
25
+
26
+ Run `pnpm dlx anhedral@latest stack update --dry-run --human` from the project. Review the diff, then run the version-pinned apply command in the preview. It checks that the plan still matches. After applying, run `pnpm install` and `pnpm check`. Use `--offline` for a local source update with deployment provenance pending.
27
+
28
+ Updates refresh the managed web and API adapters for the installed additions. Product routes, feature implementations and migrations stay application-owned. The updater preserves local adapter edits when the release still supplies the same baseline. If both changed differently, the preview identifies the conflicting file before any writes.
29
+
24
30
  ## Source protection
25
31
 
26
32
  Adding a capability also upgrades a canonical earlier TanStack Start foundation to the pinned OJ launchers and runtime helpers in the same source transaction, including when that capability is already installed. The exact earlier canonical document also receives the OJ-compatible side-effect CSS import; safe customized documents stay untouched, while edited documents retaining the earlier stylesheet URL import require reconciliation. Customized launchers or generated configuration require reconciliation before any writes. Additions never reinitialize an application. They plan all selected changes before writing, reject collisions and preserve unrelated JSON/JSONC settings. Composition adapters are fingerprinted in `anhedral.json`; modified adapters require reconciliation instead of silent replacement. Add product routes in `apps/api/src/index.ts`, custom types in `custom-environment.ts`, and auth method configuration in `auth-features.ts`/`auth.ts`.
@@ -43,4 +49,6 @@ Stripe adds source/schema, not a live payment service. Generate and review its b
43
49
 
44
50
  `anhedral.json` records nonsecret generator/capability versions and identity. Source provenance never grants hosting authority. The public deployment manifest uses runtime profile `anhedral-stack` for the web foundation and selected backend/R2/Stripe composition. Artifact identity, resource provisioning, secrets, migrations, runtime checks and production approval remain server-owned. See [the workflow](software-factory.md#platform-cli-access-and-source-upload).
45
51
 
52
+ The starter includes local tests for each installed addition. Storage tests use ephemeral Worker bindings. Payment tests generate and apply SQL only to a disposable fixture and sign webhook events locally. The workspace scopes security overrides to the affected transitive dependency versions.
53
+
46
54
  Run `pnpm check` and `pnpm audit:deps` in generated applications. Framework/runtime, provider and browser acceptance are distinct; source installation alone establishes none of them.
@@ -107,9 +107,10 @@ Use the host's configured marketplace: Codex refreshes its marketplace with
107
107
  and reload/restart the host when required before relying on its new guidance.
108
108
  Run `stack update --dry-run --json`, inspect the bounded file diffs and conflicts,
109
109
  then apply `stack update --expect-plan <planId> --json`. The plan binds source
110
- preimages, target generator and resolved release artifact. Changed plans and
111
- customized generated files stop the update; authored routes and assets remain
112
- owned by the application. This operation uses the existing journaled transaction
110
+ preimages, target generator and resolved release artifact. A stale plan requires
111
+ a new preview. Fingerprinted adapters retain local edits when their release
112
+ baseline is unchanged. Divergent edits to the same adapter require reconciliation.
113
+ The application owns its routes and assets. This operation uses the existing journaled transaction
113
114
  without installing dependencies or running project scripts. Resolve source
114
115
  conflicts before another preview, then install dependencies and run application
115
116
  checks/build separately. It never changes authentication or deployment authority.
@@ -175,8 +176,13 @@ responses. `source status` reads its server receipt. Changed source requires an
175
176
  explicit `source upload --new`; an expired request also requires a new request.
176
177
  The client honors nested `.gitignore`, excludes generated output and secret paths,
177
178
  rejects symlinks and recognized credential material, and hashes every bounded
178
- chunk plus the complete archive and canonical source inventory. The generated
179
- `apps/web/src/routeTree.gen.ts` is excluded because the router regenerates it during
179
+ chunk plus the complete archive and canonical source inventory.
180
+
181
+ Source packaging holds directory handles throughout traversal. It requires Linux
182
+ with procfs or a macOS filesystem supporting volume file IDs. Run the CLI in WSL
183
+ for Windows source uploads.
184
+
185
+ The generated `apps/web/src/routeTree.gen.ts` is excluded because the router regenerates it during
180
186
  checks/builds; authored routes, router configuration and server source remain
181
187
  included. Credential scanning is deliberately conservative; inspect source before uploading.
182
188
 
@@ -230,7 +236,10 @@ pipe. `env set <NAME>` reads one literal value from a file or pipe. Values are
230
236
  never arguments, output or retry-state contents. Non-public names default to
231
237
  secrets; `--type config` is explicit readable configuration. Public-prefixed
232
238
  secrets, reserved names, duplicate names and oversized input fail before upload.
233
- Files require owner-only permissions and a regular non-symlink final file;
239
+ Use stdin, an owner-only file outside the project, or an input under the
240
+ project’s always-excluded `.anhedral/` directory. Project `.env*` and `.dev.vars*`
241
+ filenames are also excluded. A project-specific gitignore rule alone is insufficient.
242
+ Files must have a single hard link and a regular non-symlink final component;
234
243
  ancestor checks reject observed symlinks but are not an atomic directory lock.
235
244
  Use `--dry-run` without authentication for names/types only. Actual imports bind
236
245
  API origin, principal, team, project and environment, require `--replace` for
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "anhedral",
3
- "version": "0.23.0",
3
+ "version": "0.24.0",
4
4
  "description": "The open-source Anhedral API client for building, configuring and deploying apps, with editable source generation.",
5
5
  "type": "module",
6
6
  "exports": {