anhedral 0.23.0 → 0.24.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/README.md +3 -3
  2. package/assets/launch/AGENTS.md.txt +7 -0
  3. package/assets/launch/README.md.txt +40 -0
  4. package/assets/launch/application.server.ts.txt +19 -7
  5. package/assets/launch/application.test.mjs.txt +8 -0
  6. package/assets/launch/backend-vite.config.ts.txt +18 -0
  7. package/assets/launch/home.tsx.txt +25 -2
  8. package/assets/launch/minimal-application.server.ts.txt +2 -2
  9. package/assets/launch/root.tsx.txt +38 -5
  10. package/assets/launch/router.tsx.txt +3 -2
  11. package/assets/launch/sign-in.tsx.txt +68 -5
  12. package/assets/launch/storage-page.tsx.txt +57 -0
  13. package/assets/launch/styles.css.txt +55 -16
  14. package/assets/launch/styling-tokens.cjs +45 -0
  15. package/assets/launch/vite.config.ts.txt +13 -0
  16. package/assets/stack/api-eslint.config.mjs.txt +2 -0
  17. package/assets/stack/api-index.ts.txt +1 -0
  18. package/assets/stack/api-proxy.ts.txt +112 -0
  19. package/assets/stack/auth-routes.ts.txt +3 -1
  20. package/assets/stack/auth.ts.txt +5 -4
  21. package/assets/stack/backend.test.mjs.txt +10 -0
  22. package/assets/stack/base-eslint.js.txt +16 -0
  23. package/assets/stack/billing-mode.ts.txt +2 -0
  24. package/assets/stack/billing-providers.ts.txt +8 -0
  25. package/assets/stack/db-index.ts.txt +7 -0
  26. package/assets/stack/db-migrate.mjs.txt +23 -0
  27. package/assets/stack/drizzle.config.ts.txt +2 -0
  28. package/assets/stack/entitlement-guard.ts.txt +2 -0
  29. package/assets/stack/entitlements.ts.txt +3 -1
  30. package/assets/stack/payment.test.mjs.txt +61 -0
  31. package/assets/stack/security.ts.txt +2 -0
  32. package/assets/stack/shared-eslint.config.mjs.txt +6 -0
  33. package/assets/stack/storage.test.mjs.txt +47 -0
  34. package/assets/stack/storage.ts.txt +3 -1
  35. package/assets/stack/stripe.ts.txt +4 -2
  36. package/dist/bounded-file.d.ts +2 -1
  37. package/dist/bounded-file.js +3 -2
  38. package/dist/cli-output.js +1 -1
  39. package/dist/composition/command.js +5 -2
  40. package/dist/composition/composition.d.ts +1 -0
  41. package/dist/composition/composition.js +9 -0
  42. package/dist/composition/editor.d.ts +2 -1
  43. package/dist/composition/editor.js +15 -3
  44. package/dist/composition/recipes.d.ts +2 -2
  45. package/dist/composition/recipes.js +62 -52
  46. package/dist/composition/update.js +15 -15
  47. package/dist/dependencies.d.ts +5 -6
  48. package/dist/dependencies.js +9 -1
  49. package/dist/launch.d.ts +1 -1
  50. package/dist/launch.js +26 -91
  51. package/dist/platform/deploy.js +5 -13
  52. package/dist/platform/environment.js +10 -2
  53. package/dist/platform/source.d.ts +2 -0
  54. package/dist/platform/source.js +52 -11
  55. package/dist/platform/state.js +9 -2
  56. package/dist/pnpm-policy.d.ts +1 -0
  57. package/dist/pnpm-policy.js +27 -0
  58. package/dist/render.d.ts +0 -10
  59. package/dist/render.js +1 -38
  60. package/dist/scaffold/bootstrap.d.ts +1 -2
  61. package/dist/scaffold/bootstrap.js +4 -8
  62. package/dist/scaffold/files.d.ts +12 -24
  63. package/dist/scaffold/files.js +9 -103
  64. package/dist/scaffold/styling.d.ts +2 -4
  65. package/dist/scaffold/styling.js +46 -69
  66. package/dist/scaffold/tanstack.d.ts +2 -2
  67. package/dist/scaffold/tanstack.js +37 -39
  68. package/dist/version.d.ts +1 -1
  69. package/dist/version.js +1 -1
  70. package/docs/capabilities.md +8 -0
  71. package/docs/software-factory.md +16 -7
  72. package/package.json +4 -2
  73. package/dist/api-proxy.d.ts +0 -1
  74. package/dist/api-proxy.js +0 -48
@@ -0,0 +1,112 @@
1
+ export interface ApiBinding {
2
+ fetch(request: Request): Promise<Response>;
3
+ }
4
+
5
+ type Options = {
6
+ binding?: ApiBinding;
7
+ development: boolean;
8
+ devOrigin?: string;
9
+ send?: typeof fetch;
10
+ };
11
+
12
+ function developmentOrigin(configured?: string): string {
13
+ const url = new URL(configured || 'http://127.0.0.1:8787');
14
+ const loopback = new Set(['127.0.0.1', 'localhost', '[::1]']);
15
+ const invalid = [
16
+ url.protocol !== 'http:',
17
+ !loopback.has(url.hostname),
18
+ url.username,
19
+ url.password,
20
+ url.pathname !== '/',
21
+ url.search,
22
+ url.hash,
23
+ ];
24
+ if (invalid.some(Boolean)) throw Error('API_INTERNAL_URL must be a loopback HTTP origin.');
25
+ return url.origin;
26
+ }
27
+
28
+ function backendOrigin(options: Options): string {
29
+ if (options.development) return developmentOrigin(options.devOrigin);
30
+ if ([!options.binding, options.devOrigin].some(Boolean))
31
+ throw Error('Production requires the API service binding.');
32
+ return 'https://api.internal';
33
+ }
34
+
35
+ function apiTarget(request: Request, origin: string): URL {
36
+ const url = new URL(request.url);
37
+ if (!/^\/api(?:\/|$)/.test(url.pathname)) throw Error('Unexpected API path.');
38
+ return new URL(url.pathname + url.search, origin);
39
+ }
40
+
41
+ function forwardedHeaders(request: Request): Headers {
42
+ const headers = new Headers();
43
+ for (const name of [
44
+ 'accept',
45
+ 'content-type',
46
+ 'cookie',
47
+ 'origin',
48
+ 'authorization',
49
+ 'sec-fetch-site',
50
+ 'expo-origin',
51
+ 'idempotency-key',
52
+ 'stripe-signature',
53
+ 'last-event-id',
54
+ ]) {
55
+ const value = request.headers.get(name);
56
+ if (value) headers.set(name, value);
57
+ }
58
+ return headers;
59
+ }
60
+
61
+ function upstreamRequest(request: Request, target: URL): Request {
62
+ const settings: RequestInit & { duplex?: 'half' } = {
63
+ method: request.method,
64
+ headers: forwardedHeaders(request),
65
+ redirect: 'manual',
66
+ signal: AbortSignal.any([
67
+ request.signal,
68
+ AbortSignal.timeout(
69
+ request.headers.get('accept')?.includes('text/event-stream') ? 35000 : 15000,
70
+ ),
71
+ ]),
72
+ };
73
+ if (!['GET', 'HEAD'].includes(request.method)) {
74
+ settings.body = request.body;
75
+ settings.duplex = 'half';
76
+ }
77
+ return new Request(target, settings);
78
+ }
79
+
80
+ function privateResponse(response: Response, development: boolean): Response {
81
+ const headers = new Headers(response.headers);
82
+ for (const name of [
83
+ 'connection',
84
+ 'transfer-encoding',
85
+ 'access-control-allow-origin',
86
+ 'access-control-allow-credentials',
87
+ ])
88
+ headers.delete(name);
89
+ // Node fetch already decoded the local HTTP response. The server must frame/compress
90
+ // those decoded bytes itself; the sidecar's wire headers no longer describe them.
91
+ if (development) {
92
+ headers.delete('content-encoding');
93
+ headers.delete('content-length');
94
+ }
95
+ headers.set('cache-control', 'private, no-store');
96
+ return new Response(response.body, { status: response.status, headers });
97
+ }
98
+
99
+ export async function proxyApi(request: Request, options: Options): Promise<Response> {
100
+ try {
101
+ const upstream = upstreamRequest(request, apiTarget(request, backendOrigin(options)));
102
+ const response = options.development
103
+ ? await (options.send ?? fetch)(upstream)
104
+ : await options.binding!.fetch(upstream);
105
+ return privateResponse(response, options.development);
106
+ } catch {
107
+ return Response.json(
108
+ { error: 'API unavailable' },
109
+ { status: 503, headers: { 'cache-control': 'private, no-store' } },
110
+ );
111
+ }
112
+ }
@@ -1,7 +1,9 @@
1
1
  import { Hono } from 'hono';
2
+
2
3
  import { createAuth, authConfiguration } from '../auth';
3
- import { requireSession } from '../security';
4
4
  import type { AppEnv } from '../environment';
5
+ import { requireSession } from '../security';
6
+
5
7
  export const authRoutes = new Hono<AppEnv>();
6
8
  authRoutes.on(['GET', 'POST'], '/auth/*', (c) => {
7
9
  if (!authConfiguration.safeParse(c.env).success)
@@ -1,11 +1,12 @@
1
- import { z } from 'zod';
2
- import { betterAuth } from 'better-auth/minimal';
3
1
  import { drizzleAdapter } from '@better-auth/drizzle-adapter';
4
- import { platformAuthPlugins } from './auth-platform';
5
- import { bearer } from 'better-auth/plugins/bearer';
6
2
  import { createDatabase } from '@workspace/db';
7
3
  import * as schema from '@workspace/db/schema';
4
+ import { betterAuth } from 'better-auth/minimal';
5
+ import { bearer } from 'better-auth/plugins/bearer';
6
+ import { z } from 'zod';
7
+
8
8
  import { authFeatures } from './auth-features';
9
+ import { platformAuthPlugins } from './auth-platform';
9
10
  import type { AppEnv } from './environment';
10
11
 
11
12
  export const authConfiguration = z.object({
@@ -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,16 @@
1
+ import parser from '@typescript-eslint/parser';
2
+ import plugin from '@typescript-eslint/eslint-plugin';
3
+ export const config = [
4
+ { ignores: ['dist/**', '.output/**', '.wrangler/**', 'worker-configuration.d.ts'] },
5
+ {
6
+ files: ['**/*.{ts,tsx,cts,mts}'],
7
+ languageOptions: { parser, parserOptions: { ecmaFeatures: { jsx: true } } },
8
+ plugins: { '@typescript-eslint': plugin },
9
+ rules: {
10
+ ...plugin.configs.recommended.rules,
11
+ 'no-undef': 'off',
12
+ 'no-unused-vars': 'off',
13
+ '@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
14
+ },
15
+ },
16
+ ];
@@ -1,5 +1,7 @@
1
1
  import { z } from 'zod';
2
+
2
3
  import type { AppEnv } from './environment';
4
+
3
5
  const environment = z.enum(['sandbox', 'live']);
4
6
  export function billingEnvironment(env: AppEnv['Bindings']) {
5
7
  return environment.parse(env.BILLING_ENVIRONMENT || 'sandbox');
@@ -0,0 +1,8 @@
1
+ import type { AppEnv } from './environment';
2
+ import { stripeEntitled } from './features/stripe';
3
+
4
+ type EntitlementCheck = (env: AppEnv['Bindings'], userId: string) => Promise<boolean>;
5
+
6
+ export const billingProviders: Record<string, EntitlementCheck> = {
7
+ stripe: stripeEntitled,
8
+ };
@@ -0,0 +1,7 @@
1
+ import { drizzle } from 'drizzle-orm/d1';
2
+
3
+ import * as schema from './schema';
4
+
5
+ export function createDatabase(binding: Parameters<typeof drizzle>[0]) {
6
+ return drizzle(binding, { schema });
7
+ }
@@ -0,0 +1,23 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { fileURLToPath } from 'node:url';
3
+ const args = process.argv.slice(2);
4
+ if (args.length > 1 || args.some((v) => !['--local', '--remote'].includes(v)))
5
+ throw Error('Use --local or explicitly --remote.');
6
+ if (!process.env.npm_execpath) throw Error('Run through pnpm db:migrate.');
7
+ const cwd = fileURLToPath(new URL('../../../apps/api/', import.meta.url));
8
+ const result = spawnSync(
9
+ process.execPath,
10
+ [
11
+ process.env.npm_execpath,
12
+ 'exec',
13
+ 'wrangler',
14
+ 'd1',
15
+ 'migrations',
16
+ 'apply',
17
+ 'DB',
18
+ args[0] ?? '--local',
19
+ ],
20
+ { cwd, stdio: 'inherit', shell: false },
21
+ );
22
+ if (result.error) throw result.error;
23
+ process.exitCode = result.status ?? 1;
@@ -0,0 +1,2 @@
1
+ import { defineConfig } from 'drizzle-kit';
2
+ export default defineConfig({ dialect: 'sqlite', schema: './src/schema.ts', out: './drizzle' });
@@ -1,7 +1,9 @@
1
1
  import { type MiddlewareHandler } from 'hono';
2
2
  import { z } from 'zod';
3
+
3
4
  import { billingProviders } from './billing-providers';
4
5
  import type { AppEnv } from './environment';
6
+
5
7
  const policy = z.enum(['stripe', 'revenuecat', 'either']);
6
8
  function selectedProviders(env: AppEnv['Bindings']) {
7
9
  const selected = policy.parse(env.BILLING_PROVIDER);
@@ -1,7 +1,9 @@
1
1
  import { Hono } from 'hono';
2
- import { requireSession } from '../security';
2
+
3
3
  import { requireEntitlement } from '../entitlement-guard';
4
4
  import type { AppEnv } from '../environment';
5
+ import { requireSession } from '../security';
6
+
5
7
  export const entitlementRoutes = new Hono<AppEnv>();
6
8
  entitlementRoutes.get('/billing/access', requireSession, requireEntitlement, (c) =>
7
9
  c.json({ allowed: true }),
@@ -0,0 +1,61 @@
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
+ [
24
+ cli,
25
+ 'generate',
26
+ '--dialect=sqlite',
27
+ '--schema=' + fileURLToPath(new URL('src/schema.ts', root)),
28
+ '--out=./drizzle',
29
+ ],
30
+ { cwd: work, stdio: 'pipe' },
31
+ );
32
+ const db = new DatabaseSync(':memory:');
33
+ t.after(() => db.close());
34
+ for (const file of (await readdir(migrations)).filter((name) => name.endsWith('.sql')).sort())
35
+ db.exec(await readFile(join(migrations, file), 'utf8'));
36
+ const env = {
37
+ DB: {
38
+ prepare: (sql) => ({ bind: (...params) => ({ run: () => db.prepare(sql).run(...params) }) }),
39
+ },
40
+ STRIPE_SECRET_KEY: 'sk_test_' + randomUUID(),
41
+ STRIPE_WEBHOOK_SECRET: randomUUID(),
42
+ };
43
+ const body = JSON.stringify({ id: 'evt_local', object: 'event', livemode: false });
44
+ const timestamp = Math.floor(Date.now() / 1000);
45
+ const signature = createHmac('sha256', env.STRIPE_WEBHOOK_SECRET)
46
+ .update(timestamp + '.' + body)
47
+ .digest('hex');
48
+ for (let delivery = 0; delivery < 2; delivery++) {
49
+ const result = await app.request(
50
+ '/api/webhooks/stripe',
51
+ {
52
+ method: 'POST',
53
+ headers: { 'stripe-signature': 't=' + timestamp + ',v1=' + signature },
54
+ body,
55
+ },
56
+ env,
57
+ );
58
+ assert.equal(result.status, 200);
59
+ }
60
+ assert.equal(db.prepare('SELECT COUNT(*) AS count FROM billing_receipt').get().count, 1);
61
+ });
@@ -1,6 +1,8 @@
1
1
  import type { MiddlewareHandler } from 'hono';
2
+
2
3
  import { createAuth, authConfiguration } from './auth';
3
4
  import type { AppEnv } from './environment';
5
+
4
6
  const bearer = (headers: Headers) => (headers.get('authorization') ?? '').startsWith('Bearer ');
5
7
  function sessionHeaders(request: Request) {
6
8
  const headers = new Headers(request.headers);
@@ -0,0 +1,6 @@
1
+ import { config } from '@workspace/eslint-config/base';
2
+ export default [
3
+ ...config,
4
+ { ignores: ['dist/**', '.wrangler/**', 'worker-configuration.d.ts'] },
5
+ { files: ['**/*.ts'], rules: { 'no-undef': 'off', 'no-unused-vars': 'off' } },
6
+ ];
@@ -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,6 +1,8 @@
1
1
  import { Hono } from 'hono';
2
- import { requireSession } from '../security';
2
+
3
3
  import type { AppEnv } from '../environment';
4
+ import { requireSession } from '../security';
5
+
4
6
  export const storageRoutes = new Hono<AppEnv>();
5
7
  storageRoutes.use('/files/*', requireSession);
6
8
  storageRoutes.use('/files/:name', async (c, next) => {
@@ -1,9 +1,11 @@
1
1
  import { Hono } from 'hono';
2
- import { z } from 'zod';
3
2
  import Stripe from 'stripe';
4
- import { requireSession } from '../security';
3
+ import { z } from 'zod';
4
+
5
5
  import { billingEnvironment } from '../billing-mode';
6
6
  import type { AppEnv } from '../environment';
7
+ import { requireSession } from '../security';
8
+
7
9
  export const stripeRoutes = new Hono<AppEnv>();
8
10
  const client = (key: string) =>
9
11
  new Stripe(key, {
@@ -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 = [];
@@ -38,7 +38,7 @@ export function formatResult(_command, value) {
38
38
  if (data.stack === 'anhedral-stack' && !data.generated)
39
39
  return `Foundation preview for ${data.root}.\nStack: Anhedral Stack.\nNo files were written or resources provisioned.`;
40
40
  if (data.stack === 'anhedral-stack' && data.generated)
41
- return `Created ${data.root}.\nStack: Anhedral Stack.\n${data.dependenciesInstalled ? 'Run pnpm dev' : 'Run pnpm install, then pnpm dev'} in the project directory.\nAdd services when needed: anhedral add backend, then anhedral add storage or anhedral add payment.\nReview README.md for configuration and deployment.`;
41
+ return `Created ${data.root}.\nStack: Anhedral Stack.\n${data.dependenciesInstalled ? 'Run pnpm dev' : 'Run pnpm install, then pnpm dev'} in the project directory.\nEdit apps/web/src/routes/index.tsx to change the home page.\nSee README.md for checks, additions, and updates.`;
42
42
  return (`${data.generated ? 'Created' : 'Foundation preview for'} ${data.root}.\nComponents: ${data.products.join(', ')}.\n` +
43
43
  (data.generated
44
44
  ? 'Review README.md, then run pnpm dev in the project directory. You own development, integrations and hosting.'
@@ -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
- import { CapabilityEditor } from './editor.js';
2
1
  import type { Capability } from './catalog.js';
2
+ import { CapabilityEditor } from './editor.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;