anhedral 0.13.0 → 0.15.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 (170) hide show
  1. package/README.md +35 -232
  2. package/assets/patches/audit-deps.mjs +12 -2
  3. package/assets/ui/LICENSE.shadcn +21 -0
  4. package/assets/ui/UPSTREAM.json +33 -0
  5. package/assets/ui/native/button.tsx +85 -0
  6. package/assets/ui/native/card.tsx +33 -0
  7. package/assets/ui/native/dialog.tsx +75 -0
  8. package/assets/ui/native/input.tsx +27 -0
  9. package/assets/ui/native/label.tsx +4 -0
  10. package/assets/ui/native/layout.tsx +26 -0
  11. package/assets/ui/native/text.tsx +20 -0
  12. package/assets/ui/native/theme-switcher.tsx +22 -0
  13. package/assets/ui/theme-storage.ts +25 -0
  14. package/assets/ui/theme.tsx +66 -0
  15. package/assets/ui/web/button.tsx +59 -0
  16. package/assets/ui/web/input.tsx +21 -0
  17. package/assets/ui/web/label.tsx +19 -0
  18. package/dist/capabilities.d.ts +5 -5
  19. package/dist/capabilities.js +3 -21
  20. package/dist/capability-contract.d.ts +3 -3
  21. package/dist/capability-contract.js +11 -50
  22. package/dist/cli-delivery.d.ts +1 -1
  23. package/dist/cli-delivery.js +5 -65
  24. package/dist/cli-output.js +3 -3
  25. package/dist/command-schema.js +35 -86
  26. package/dist/delivery-evidence.d.ts +1 -1
  27. package/dist/delivery-evidence.js +7 -36
  28. package/dist/delivery.d.ts +2 -8
  29. package/dist/delivery.js +20 -101
  30. package/dist/dependencies.d.ts +6 -57
  31. package/dist/dependencies.js +54 -188
  32. package/dist/index.d.ts +1 -4
  33. package/dist/index.js +1 -4
  34. package/dist/inspector-model.d.ts +2 -2
  35. package/dist/integration-service-readers.d.ts +1 -2
  36. package/dist/integration-service-readers.js +3 -84
  37. package/dist/lifecycle-model.d.ts +1 -1
  38. package/dist/lifecycle-model.js +1 -1
  39. package/dist/mobile-delivery.d.ts +1 -1
  40. package/dist/mobile-delivery.js +4 -0
  41. package/dist/platforms/mobile.js +30 -121
  42. package/dist/platforms/web.d.ts +3 -0
  43. package/dist/platforms/web.js +299 -0
  44. package/dist/project-config.d.ts +1 -1
  45. package/dist/project-config.js +0 -1
  46. package/dist/project-inspector.js +5 -36
  47. package/dist/project-state.d.ts +1 -3
  48. package/dist/project-state.js +2 -85
  49. package/dist/provider-auth.js +3 -38
  50. package/dist/provider-readiness.d.ts +1 -1
  51. package/dist/provider-readiness.js +5 -24
  52. package/dist/providers/adapters.js +0 -175
  53. package/dist/providers/api.d.ts +1 -1
  54. package/dist/providers/api.js +3 -3
  55. package/dist/providers/config.js +2 -48
  56. package/dist/providers/definitions.d.ts +1 -204
  57. package/dist/providers/definitions.js +0 -85
  58. package/dist/providers/provision.d.ts +1 -1
  59. package/dist/providers/receipts.js +1 -11
  60. package/dist/providers/recovery-verification.js +1 -61
  61. package/dist/providers/runtime.js +4 -35
  62. package/dist/providers/state.js +1 -7
  63. package/dist/provision.d.ts +5 -13
  64. package/dist/provision.js +4 -80
  65. package/dist/readiness.d.ts +1 -1
  66. package/dist/readiness.js +3 -8
  67. package/dist/registry/add.js +10 -70
  68. package/dist/registry/bootstrap.d.ts +3 -2
  69. package/dist/registry/bootstrap.js +4 -13
  70. package/dist/registry/commands.js +8 -10
  71. package/dist/registry/context.js +0 -1
  72. package/dist/registry/options.js +8 -38
  73. package/dist/registry/resolve.d.ts +3 -4
  74. package/dist/registry/resolve.js +26 -108
  75. package/dist/registry/types.d.ts +1 -7
  76. package/dist/registry/usage.js +2 -2
  77. package/dist/runtime-policy.d.ts +0 -2
  78. package/dist/runtime-policy.js +0 -16
  79. package/dist/scaffold/auth.d.ts +1 -2
  80. package/dist/scaffold/auth.js +55 -130
  81. package/dist/scaffold/backend.d.ts +0 -4
  82. package/dist/scaffold/backend.js +1 -186
  83. package/dist/scaffold/billing-schema.d.ts +1 -1
  84. package/dist/scaffold/billing-schema.js +4 -4
  85. package/dist/scaffold/billing.js +11 -19
  86. package/dist/scaffold/bootstrap.d.ts +2 -3
  87. package/dist/scaffold/bootstrap.js +37 -43
  88. package/dist/scaffold/compose.js +2 -14
  89. package/dist/scaffold/database.d.ts +1 -1
  90. package/dist/scaffold/database.js +18 -126
  91. package/dist/scaffold/documentation.d.ts +0 -1
  92. package/dist/scaffold/documentation.js +22 -86
  93. package/dist/scaffold/expo-auth.js +33 -22
  94. package/dist/scaffold/expo-billing.js +17 -52
  95. package/dist/scaffold/expo-runtime.d.ts +2 -2
  96. package/dist/scaffold/expo-runtime.js +6 -97
  97. package/dist/scaffold/integrations.d.ts +1 -3
  98. package/dist/scaffold/integrations.js +9 -10
  99. package/dist/scaffold/managed-email.d.ts +3 -0
  100. package/dist/scaffold/managed-email.js +47 -0
  101. package/dist/scaffold/native-ui.d.ts +2 -0
  102. package/dist/scaffold/native-ui.js +69 -0
  103. package/dist/scaffold/password-reset.d.ts +1 -0
  104. package/dist/scaffold/password-reset.js +99 -0
  105. package/dist/scaffold/private-files.d.ts +2 -0
  106. package/dist/scaffold/private-files.js +78 -0
  107. package/dist/scaffold/stack-documentation.d.ts +0 -1
  108. package/dist/scaffold/stack-documentation.js +3 -49
  109. package/dist/scaffold/styling.d.ts +1 -1
  110. package/dist/scaffold/styling.js +20 -28
  111. package/dist/scaffold/web-billing.d.ts +2 -0
  112. package/dist/scaffold/web-billing.js +48 -0
  113. package/dist/scaffold/workspace.js +53 -194
  114. package/dist/service-deletion.js +1 -1
  115. package/dist/service-descriptor.js +5 -12
  116. package/dist/service-model.d.ts +1 -1
  117. package/dist/service-operations.js +2 -32
  118. package/dist/service-readers.js +1 -32
  119. package/dist/services-command.d.ts +1 -1
  120. package/dist/services-command.js +3 -9
  121. package/dist/ship.d.ts +3 -316
  122. package/dist/ship.js +10 -142
  123. package/dist/stack-registry.d.ts +2 -52
  124. package/dist/stack-registry.js +55 -403
  125. package/dist/standard.js +7 -14
  126. package/dist/version.d.ts +1 -1
  127. package/dist/version.js +1 -1
  128. package/docs/anhedral-stack.md +23 -122
  129. package/docs/assets/anhedral-stack-light.png +0 -0
  130. package/docs/assets/anhedral-stack.png +0 -0
  131. package/docs/software-factory.md +24 -557
  132. package/docs/stack-standard.md +47 -294
  133. package/docs/verification.md +320 -0
  134. package/package.json +20 -22
  135. package/dist/neon-service-data.d.ts +0 -8
  136. package/dist/neon-service-data.js +0 -117
  137. package/dist/platforms/desktop.d.ts +0 -2
  138. package/dist/platforms/desktop.js +0 -415
  139. package/dist/platforms/extension.d.ts +0 -2
  140. package/dist/platforms/extension.js +0 -328
  141. package/dist/registry/presets.d.ts +0 -4
  142. package/dist/registry/presets.js +0 -41
  143. package/dist/scaffold/cloudflare-services.d.ts +0 -8
  144. package/dist/scaffold/cloudflare-services.js +0 -198
  145. package/dist/scaffold/lint.d.ts +0 -4
  146. package/dist/scaffold/lint.js +0 -56
  147. package/dist/scaffold/neon-realtime.d.ts +0 -2
  148. package/dist/scaffold/neon-realtime.js +0 -97
  149. package/dist/scaffold/services.d.ts +0 -5
  150. package/dist/scaffold/services.js +0 -108
  151. package/dist/scaffold/stream.d.ts +0 -2
  152. package/dist/scaffold/stream.js +0 -114
  153. package/dist/scaffold/void.d.ts +0 -4
  154. package/dist/scaffold/void.js +0 -264
  155. package/dist/scaffold/web.d.ts +0 -2
  156. package/dist/scaffold/web.js +0 -130
  157. package/dist/vercel-project.d.ts +0 -101
  158. package/dist/vercel-project.js +0 -305
  159. package/dist/vercel.d.ts +0 -67
  160. package/dist/vercel.js +0 -581
  161. package/dist/vinext.d.ts +0 -2
  162. package/dist/vinext.js +0 -86
  163. package/dist/void-execution.d.ts +0 -10
  164. package/dist/void-execution.js +0 -94
  165. package/dist/void-migrations.d.ts +0 -6
  166. package/dist/void-migrations.js +0 -110
  167. package/dist/void-state.d.ts +0 -16
  168. package/dist/void-state.js +0 -65
  169. package/dist/void.d.ts +0 -3
  170. package/dist/void.js +0 -5
@@ -0,0 +1,99 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { put } from './files.js';
4
+ export function scaffoldPasswordReset(root) {
5
+ put(root, 'packages/contracts/src/password-reset.ts', PASSWORD_RESET_CLIENT);
6
+ const contracts = readFileSync(path.join(root, 'packages/contracts/src/index.ts'), 'utf8');
7
+ put(root, 'packages/contracts/src/index.ts', contracts + "\nexport { submitPasswordReset, passwordResetLabel } from './password-reset';\n");
8
+ put(root, 'apps/web/app/reset-password/page.tsx', `import { PasswordReset } from '@/components/password-reset';
9
+ export default async function Page({ searchParams }: { searchParams: Promise<Record<string, string | string[] | undefined>> }) {
10
+ const params = await searchParams;
11
+ return <PasswordReset key={JSON.stringify([params.token, params.error])} token={typeof params.token === 'string' ? params.token : undefined} invalid={Boolean(params.error)} />;
12
+ }
13
+ `);
14
+ put(root, 'apps/web/components/password-reset.tsx', WEB_PASSWORD_RESET);
15
+ put(root, 'apps/mobile/app/reset-password.tsx', NATIVE_PASSWORD_RESET);
16
+ }
17
+ const WEB_PASSWORD_RESET = `'use client';
18
+ import { useState, type FormEvent } from 'react';
19
+ import Link from 'next/link';
20
+ import { authClient } from '@/lib/auth-client';
21
+ import { Button } from '@/components/ui/button';
22
+ import { Input } from '@/components/ui/input';
23
+ import { Label } from '@/components/ui/label';
24
+ import { submitPasswordReset, passwordResetLabel } from '@workspace/contracts';
25
+ function ResetFields({ token }: { token?: string }) {
26
+ return token ? <Label>New password<Input name="password" type="password" autoComplete="new-password" minLength={8} required /></Label> : <Label>Email<Input name="email" type="email" autoComplete="email" required /></Label>;
27
+ }
28
+ export function PasswordReset({ token, invalid }: { token?: string; invalid: boolean }) {
29
+ const [pending, setPending] = useState(false);
30
+ const [complete, setComplete] = useState(false);
31
+ const [message, setMessage] = useState(invalid ? 'This link is invalid or expired. Request a new one.' : '');
32
+ async function submit(event: FormEvent<HTMLFormElement>) {
33
+ event.preventDefault(); if (pending) return;
34
+ const form = event.currentTarget; const data = new FormData(form);
35
+ setPending(true); setMessage('');
36
+ try {
37
+ const message = await submitPasswordReset(authClient, { token, email: String(data.get('email')), password: String(data.get('password')) }, new URL('/reset-password', window.location.origin).href);
38
+ form.reset(); setComplete(Boolean(token)); setMessage(message);
39
+ } catch { setMessage('Unable to complete this request. Try again or request a new link.'); }
40
+ finally { setPending(false); }
41
+ }
42
+ return <section className="stack"><h1>Reset password</h1>{!complete && <form onSubmit={submit}>
43
+ <ResetFields token={token} />
44
+ <Button disabled={pending} type="submit">{passwordResetLabel(pending, token)}</Button>
45
+ </form>}<p role="status">{message}</p><Link href="/reset-password">Request a new link</Link><Link href="/sign-in">Back to sign in</Link></section>;
46
+ }
47
+ `;
48
+ const NATIVE_PASSWORD_RESET = `import { useState } from 'react';
49
+ import { Link, useLocalSearchParams } from 'expo-router';
50
+ import * as Linking from 'expo-linking';
51
+ import { Screen, Text, Input } from '@workspace/native-ui';
52
+ import { Button } from '@/components/ui/button';
53
+ import { getAuthClient } from '@/lib/auth-client';
54
+ import { AuthConfiguration } from '@/components/auth-configuration';
55
+ import { submitPasswordReset, passwordResetLabel } from '@workspace/contracts';
56
+ function disabled(pending: boolean, token: string | undefined, password: string, email: string): boolean { return pending || (token ? password.length < 8 : !email); }
57
+ function ResetFields({ token, password, setPassword, email, setEmail }: { token?: string; password: string; setPassword: (value: string) => void; email: string; setEmail: (value: string) => void }) {
58
+ return token ? <Input accessibilityLabel="New password" value={password} onChangeText={setPassword} secureTextEntry autoComplete="new-password" /> : <Input accessibilityLabel="Email" value={email} onChangeText={setEmail} keyboardType="email-address" autoCapitalize="none" autoComplete="email" />;
59
+ }
60
+ export default function ResetPasswordRoute() {
61
+ const params = useLocalSearchParams<{ token?: string; error?: string }>();
62
+ return <AuthConfiguration><ResetPassword key={JSON.stringify([params.token, params.error])} /></AuthConfiguration>;
63
+ }
64
+ function ResetPassword() {
65
+ const params = useLocalSearchParams<{ token?: string; error?: string }>();
66
+ const token = typeof params.token === 'string' ? params.token : undefined;
67
+ const [email, setEmail] = useState(''); const [password, setPassword] = useState('');
68
+ const [message, setMessage] = useState(params.error ? 'This link is invalid or expired. Request a new one.' : '');
69
+ const [complete, setComplete] = useState(false); const [pending, setPending] = useState(false);
70
+ async function submit() {
71
+ if (pending) return; setPending(true); setMessage('');
72
+ try {
73
+ const message = await submitPasswordReset(getAuthClient(), { token, email, password }, Linking.createURL('reset-password'));
74
+ setPassword(''); setComplete(Boolean(token)); setMessage(message);
75
+ } catch { setMessage('Unable to complete this request. Try again or request a new link.'); }
76
+ finally { setPending(false); }
77
+ }
78
+ return <Screen><Text accessibilityRole="header">Reset password</Text>{!complete && <>
79
+ <ResetFields token={token} password={password} setPassword={setPassword} email={email} setEmail={setEmail} />
80
+ <Button disabled={disabled(pending, token, password, email)} onPress={() => void submit()}>{passwordResetLabel(pending, token)}</Button>
81
+ </>}<Text accessibilityLiveRegion="polite">{message}</Text><Link href="/reset-password">Request a new link</Link><Link href="/sign-in">Back to sign in</Link></Screen>;
82
+ }
83
+ `;
84
+ const PASSWORD_RESET_CLIENT = `interface PasswordResetClient {
85
+ resetPassword(input: { token: string; newPassword: string }): Promise<{ error: unknown }>;
86
+ requestPasswordReset(input: { email: string; redirectTo: string }): Promise<{ error: unknown }>;
87
+ }
88
+ export async function submitPasswordReset(client: PasswordResetClient, values: { token?: string; email: string; password: string }, redirectTo: string): Promise<string> {
89
+ const result = values.token
90
+ ? await client.resetPassword({ token: values.token, newPassword: values.password })
91
+ : await client.requestPasswordReset({ email: values.email, redirectTo });
92
+ if (result.error) throw Error('Reset unavailable');
93
+ return values.token ? 'Password updated. Sign in again.' : 'If an account exists, check your email for the reset link.';
94
+ }
95
+ export function passwordResetLabel(pending: boolean, token?: string): string {
96
+ if (pending) return 'Working…';
97
+ return token ? 'Update password' : 'Send reset link';
98
+ }
99
+ `;
@@ -0,0 +1,2 @@
1
+ /** Generated server code: the caller never selects the owner's R2 namespace. */
2
+ export declare const PRIVATE_FILES_SOURCE = "import { Hono } from 'hono';\nimport { createAuth } from '@workspace/auth';\nimport { createDatabase } from '@workspace/db';\n\nconst MAX_FILE_BYTES = 1024 * 1024;\ntype Identity = (request: Request, env: Env) => Promise<string | null>;\nasync function authenticate(request: Request, env: Env): Promise<string | null> {\n const session = await createAuth(createDatabase(env.DB), env.BETTER_AUTH_SECRET, env.BETTER_AUTH_URL, env).api.getSession({ headers: request.headers });\n return session?.user.id ?? null;\n}\nasync function readFileBody(request: Request): Promise<Uint8Array | null> {\n if (!request.body) return new Uint8Array();\n return readFileStream(request.body);\n}\nasync function readFileStream(body: ReadableStream<Uint8Array>): Promise<Uint8Array | null> {\n const reader = body.getReader();\n const chunks: Uint8Array[] = [];\n let size = 0;\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n size += value.byteLength;\n if (size > MAX_FILE_BYTES) { await reader.cancel(); return null; }\n chunks.push(value);\n }\n } finally { reader.releaseLock(); }\n return combineChunks(chunks, size);\n}\nfunction combineChunks(chunks: Uint8Array[], size: number): Uint8Array {\n const result = new Uint8Array(size);\n let offset = 0;\n for (const chunk of chunks) { result.set(chunk, offset); offset += chunk.byteLength; }\n return result;\n}\nfunction trustedMutation(request: Request, baseURL: string): boolean {\n if (request.headers.get('sec-fetch-site') === 'cross-site') return false;\n const origin = request.headers.get('origin');\n return !origin || origin === new URL(baseURL).origin;\n}\nfunction createPrivateFileRoutes(identity: Identity = authenticate) {\n const routes = new Hono<{ Bindings: Env; Variables: { fileOwner: string } }>();\n routes.use('*', async (c, next) => {\n c.header('cache-control', 'private, no-store');\n const userId = await identity(c.req.raw, c.env);\n if (!userId) return c.json({ error: 'Unauthorized' }, 401);\n c.set('fileOwner', encodeURIComponent(userId));\n const mutation = !['GET', 'HEAD'].includes(c.req.method);\n if (mutation && !trustedMutation(c.req.raw, c.env.BETTER_AUTH_URL)) return c.json({ error: 'Unexpected request origin' }, 403);\n await next();\n });\n routes.post('/', async (c) => {\n // Raw bytes keep upload memory bounded. Only the server creates keys.\n const bytes = await readFileBody(c.req.raw);\n if (!bytes) return c.json({ error: 'File exceeds 1 MiB' }, 413);\n if (!bytes.byteLength) return c.json({ error: 'An empty file is not allowed' }, 400);\n const id = crypto.randomUUID();\n await c.env.FILES.put(c.get('fileOwner') + '/' + id, bytes, { httpMetadata: { contentType: 'application/octet-stream' } });\n return c.json({ id, size: bytes.byteLength }, 201);\n });\n routes.use('/:id', async (c, next) => {\n if (!/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(c.req.param('id') ?? '')) return c.json({ error: 'Not found' }, 404);\n await next();\n });\n routes.get('/:id', async (c) => {\n const object = await c.env.FILES.get(c.get('fileOwner') + '/' + c.req.param('id'));\n if (!object) return c.json({ error: 'Not found' }, 404);\n return new Response(object.body, { headers: { 'content-type': 'application/octet-stream', 'content-disposition': 'attachment; filename=\"download\"', 'x-content-type-options': 'nosniff', 'cache-control': 'private, no-store' } });\n });\n routes.delete('/:id', async (c) => {\n await c.env.FILES.delete(c.get('fileOwner') + '/' + c.req.param('id'));\n return c.body(null, 204);\n });\n return routes;\n}\nexport const privateFileRoutes = createPrivateFileRoutes();\n";
@@ -0,0 +1,78 @@
1
+ /** Generated server code: the caller never selects the owner's R2 namespace. */
2
+ export const PRIVATE_FILES_SOURCE = `import { Hono } from 'hono';
3
+ import { createAuth } from '@workspace/auth';
4
+ import { createDatabase } from '@workspace/db';
5
+
6
+ const MAX_FILE_BYTES = 1024 * 1024;
7
+ type Identity = (request: Request, env: Env) => Promise<string | null>;
8
+ async function authenticate(request: Request, env: Env): Promise<string | null> {
9
+ const session = await createAuth(createDatabase(env.DB), env.BETTER_AUTH_SECRET, env.BETTER_AUTH_URL, env).api.getSession({ headers: request.headers });
10
+ return session?.user.id ?? null;
11
+ }
12
+ async function readFileBody(request: Request): Promise<Uint8Array | null> {
13
+ if (!request.body) return new Uint8Array();
14
+ return readFileStream(request.body);
15
+ }
16
+ async function readFileStream(body: ReadableStream<Uint8Array>): Promise<Uint8Array | null> {
17
+ const reader = body.getReader();
18
+ const chunks: Uint8Array[] = [];
19
+ let size = 0;
20
+ try {
21
+ while (true) {
22
+ const { done, value } = await reader.read();
23
+ if (done) break;
24
+ size += value.byteLength;
25
+ if (size > MAX_FILE_BYTES) { await reader.cancel(); return null; }
26
+ chunks.push(value);
27
+ }
28
+ } finally { reader.releaseLock(); }
29
+ return combineChunks(chunks, size);
30
+ }
31
+ function combineChunks(chunks: Uint8Array[], size: number): Uint8Array {
32
+ const result = new Uint8Array(size);
33
+ let offset = 0;
34
+ for (const chunk of chunks) { result.set(chunk, offset); offset += chunk.byteLength; }
35
+ return result;
36
+ }
37
+ function trustedMutation(request: Request, baseURL: string): boolean {
38
+ if (request.headers.get('sec-fetch-site') === 'cross-site') return false;
39
+ const origin = request.headers.get('origin');
40
+ return !origin || origin === new URL(baseURL).origin;
41
+ }
42
+ function createPrivateFileRoutes(identity: Identity = authenticate) {
43
+ const routes = new Hono<{ Bindings: Env; Variables: { fileOwner: string } }>();
44
+ routes.use('*', async (c, next) => {
45
+ c.header('cache-control', 'private, no-store');
46
+ const userId = await identity(c.req.raw, c.env);
47
+ if (!userId) return c.json({ error: 'Unauthorized' }, 401);
48
+ c.set('fileOwner', encodeURIComponent(userId));
49
+ const mutation = !['GET', 'HEAD'].includes(c.req.method);
50
+ if (mutation && !trustedMutation(c.req.raw, c.env.BETTER_AUTH_URL)) return c.json({ error: 'Unexpected request origin' }, 403);
51
+ await next();
52
+ });
53
+ routes.post('/', async (c) => {
54
+ // Raw bytes keep upload memory bounded. Only the server creates keys.
55
+ const bytes = await readFileBody(c.req.raw);
56
+ if (!bytes) return c.json({ error: 'File exceeds 1 MiB' }, 413);
57
+ if (!bytes.byteLength) return c.json({ error: 'An empty file is not allowed' }, 400);
58
+ const id = crypto.randomUUID();
59
+ await c.env.FILES.put(c.get('fileOwner') + '/' + id, bytes, { httpMetadata: { contentType: 'application/octet-stream' } });
60
+ return c.json({ id, size: bytes.byteLength }, 201);
61
+ });
62
+ routes.use('/:id', async (c, next) => {
63
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(c.req.param('id') ?? '')) return c.json({ error: 'Not found' }, 404);
64
+ await next();
65
+ });
66
+ routes.get('/:id', async (c) => {
67
+ const object = await c.env.FILES.get(c.get('fileOwner') + '/' + c.req.param('id'));
68
+ if (!object) return c.json({ error: 'Not found' }, 404);
69
+ return new Response(object.body, { headers: { 'content-type': 'application/octet-stream', 'content-disposition': 'attachment; filename="download"', 'x-content-type-options': 'nosniff', 'cache-control': 'private, no-store' } });
70
+ });
71
+ routes.delete('/:id', async (c) => {
72
+ await c.env.FILES.delete(c.get('fileOwner') + '/' + c.req.param('id'));
73
+ return c.body(null, 204);
74
+ });
75
+ return routes;
76
+ }
77
+ export const privateFileRoutes = createPrivateFileRoutes();
78
+ `;
@@ -1,3 +1,2 @@
1
1
  import type { ResolvedStackRegistry } from '../registry/resolve.js';
2
- /** Human-readable companion to the current resolved registry, refreshed by add. */
3
2
  export declare function writeStackDocumentation(root: string, registry: ResolvedStackRegistry): void;
@@ -1,52 +1,6 @@
1
- import { WORKER_DEV_PORTS } from '../dependencies.js';
2
1
  import { put } from './files.js';
3
- /** Human-readable companion to the current resolved registry, refreshed by add. */
4
2
  export function writeStackDocumentation(root, registry) {
5
- const sections = registry.items.map((item) => {
6
- const lines = [
7
- `## ${item.name}`,
8
- '',
9
- item.description + '.',
10
- '',
11
- `Targets: ${item.targets.map((target) => `\`${target}\``).join(', ')}.`,
12
- ];
13
- if (item.environment.length)
14
- lines.push(`Environment: ${item.environment.map((key) => `\`${key}\``).join(', ')}.`);
15
- if (item.bindings)
16
- lines.push('', 'Worker configuration:', '', '```json', JSON.stringify(item.bindings, null, 2), '```');
17
- if (item.setup) {
18
- for (const [label, entries] of [
19
- ['Required setup', item.setup.resources],
20
- ['Credentials', item.setup.credentials],
21
- ['Verify before delivery', item.setup.verify],
22
- ]) {
23
- if (!entries.length)
24
- continue;
25
- lines.push('', `${label}:`, '', ...entries.map((entry) => `- ${entry}`));
26
- }
27
- }
28
- return lines.join('\n');
29
- });
30
- const ports = Object.entries(WORKER_DEV_PORTS)
31
- .filter(([app]) => registry.items.some((item) => item.targets.includes(`apps/${app}`)))
32
- .map(([app, port]) => `| ${app} | ${port.http} | ${port.inspector} |`);
33
- put(root, 'docs/stack.md', [
34
- '# Selected stack',
35
- '',
36
- `Generated from the bundled Anhedral ${registry.cliVersion} registry. Project configuration lives in anhedral.json; setup and registry record the current selection and generated source, providers holds integration settings, and cloudflare/vercel hold selected hosting configuration. This document is refreshed by add. Keep product decisions in docs/architecture.md and acceptance evidence in docs/verification.md.`,
37
- '',
38
- 'These are scaffolds and integration boundaries. Provider access, migrations, authorization and live behavior require the setup and checks listed below.',
39
- ...(ports.length
40
- ? [
41
- '',
42
- '## Local Worker ports',
43
- '',
44
- '| Application | HTTP | Inspector |',
45
- '| --- | --- | --- |',
46
- ...ports,
47
- ]
48
- : []),
49
- '',
50
- ...sections.flatMap((section) => [section, '']),
51
- ].join('\n'));
3
+ const sections = registry.items.map((item) => `## ${item.name}\n\n${item.description}.\n\nTargets: ${item.targets.join(', ')}.\n\n${item.environment.length ? 'Environment: ' + item.environment.join(', ') + '.\n\n' : ''}${item.setup ? 'Setup: ' + item.setup.resources.join('; ') + '.\n\nVerify: ' + item.setup.verify.join('; ') + '.\n' : ''}`);
4
+ put(root, 'docs/stack.md', '# Application stack\n\nEvery application uses Next.js App Router/OpenNext for web, Expo for iOS/Android, Hono, Drizzle/D1 and private R2. Better Auth and shared styling are included supporting foundations. Stripe and RevenueCat are optional additions.\n\nInit generates source and configuration only. Cloud provisioning, secrets, database migrations and deployment are explicit operations.\n\n' +
5
+ sections.join('\n'));
52
6
  }
@@ -1,3 +1,3 @@
1
1
  import type { RecipeContext } from '../registry/types.js';
2
- /** Shared data and a Tailwind v3 preset for Expo/NativeWind and WXT. */
2
+ /** One shared token source for native components and DOM CSS. */
3
3
  export declare function scaffoldStyling({ root }: RecipeContext): void;
@@ -1,5 +1,7 @@
1
+ import { createRequire } from 'node:module';
2
+ import path from 'node:path';
1
3
  import { json, patchPackage, put, readJson } from './files.js';
2
- /** Shared data and a Tailwind v3 preset for Expo/NativeWind and WXT. */
4
+ /** One shared token source for native components and DOM CSS. */
3
5
  export function scaffoldStyling({ root }) {
4
6
  put(root, 'packages/styling/src/tokens.cjs', `exports.light = {
5
7
  '--background': '0 0% 100%',
@@ -46,39 +48,29 @@ exports.dark = {
46
48
  };
47
49
 
48
50
  exports.spacing = { small: 4, medium: 8, large: 16 };
49
- `);
50
- put(root, 'packages/styling/tailwind.cjs', `const { light, dark } = require('./src/tokens.cjs');
51
- const color = (name) => 'hsl(var(--' + name + '))';
52
- const surface = (name) => ({ DEFAULT: color(name), foreground: color(name + '-foreground') });
53
-
54
- module.exports = {
55
- darkMode: 'class',
56
- theme: {
57
- extend: {
58
- colors: {
59
- border: color('border'), input: color('input'), ring: color('ring'),
60
- background: color('background'), foreground: color('foreground'),
61
- primary: surface('primary'), secondary: surface('secondary'),
62
- destructive: surface('destructive'), muted: surface('muted'),
63
- accent: surface('accent'), popover: surface('popover'), card: surface('card'),
64
- },
65
- borderRadius: {
66
- lg: 'var(--radius)', md: 'calc(var(--radius) - 2px)', sm: 'calc(var(--radius) - 4px)',
67
- },
68
- },
69
- },
70
- plugins: [function themeVariables({ addBase }) {
71
- addBase({ ':root': light, '.dark:root': dark });
72
- }],
73
- };
74
51
  `);
75
52
  patchPackage(root, 'packages/styling/package.json', {
76
- exports: { '.': './src/index.ts', './tailwind': './tailwind.cjs' },
53
+ exports: {
54
+ '.': './src/index.ts',
55
+ './globals.css': './globals.css',
56
+ },
77
57
  });
58
+ const tokens = createRequire(import.meta.url)(path.join(root, 'packages/styling/src/tokens.cjs'));
59
+ const rule = (selector, values) => selector +
60
+ ' {\n' +
61
+ Object.entries(values)
62
+ .map(([key, value]) => ' ' + key + ': ' + value + ';')
63
+ .join('\n') +
64
+ '\n}\n';
65
+ put(root, 'packages/styling/globals.css', rule(':root', tokens.light) +
66
+ '@media (prefers-color-scheme: dark) {\n' +
67
+ rule(':root', tokens.dark) +
68
+ '}\n');
69
+ put(root, 'packages/styling/src/tokens.d.cts', 'export const light: Record<string, string>;\nexport const dark: Record<string, string>;\nexport const spacing: { small: number; medium: number; large: number };\n');
78
70
  const config = readJson(root, 'packages/styling/tsconfig.json');
79
71
  json(root, 'packages/styling/tsconfig.json', {
80
72
  ...config,
81
73
  compilerOptions: { ...config.compilerOptions, allowJs: true },
82
- include: ['src/**/*.ts', 'src/**/*.cjs', 'tailwind.cjs'],
74
+ include: ['src/**/*.ts', 'src/**/*.cjs'],
83
75
  });
84
76
  }
@@ -0,0 +1,2 @@
1
+ import type { RecipeContext } from '../registry/types.js';
2
+ export declare function scaffoldWebBilling({ root }: RecipeContext): void;
@@ -0,0 +1,48 @@
1
+ import { put } from './files.js';
2
+ export function scaffoldWebBilling({ root }) {
3
+ put(root, 'apps/web/components/billing.tsx', WEB_BILLING);
4
+ put(root, 'apps/web/app/account/page.tsx', `import { headers } from 'next/headers';
5
+ import { redirect } from 'next/navigation';
6
+ import { sessionSchema } from '@workspace/contracts';
7
+ import { apiRequest } from '@/lib/server-api';
8
+ import { SignOut } from '@/components/sign-out';
9
+ import { Billing } from '@/components/billing';
10
+ export default async function Account() {
11
+ const incoming = await headers();
12
+ const response = await apiRequest(new Request('https://app.internal/api/session', { headers: { cookie: incoming.get('cookie') ?? '' } }));
13
+ if (response.status === 401) redirect('/sign-in');
14
+ if (!response.ok) throw Error('Session verification is unavailable.');
15
+ const { user } = sessionSchema.parse(await response.json());
16
+ return <section className="stack"><h1>Account</h1><p>{user.email}</p><Billing key={user.id} /><SignOut /></section>;
17
+ }
18
+ `);
19
+ }
20
+ const WEB_BILLING = `'use client';
21
+ import { useEffect, useRef, useState } from 'react';
22
+ import { createBillingClient, type BillingIdentity, type BillingEntitlements } from '@workspace/contracts';
23
+ import { Button } from '@/components/ui/button';
24
+ const api = createBillingClient();
25
+ function navigate(value: string) {
26
+ const url = new URL(value);
27
+ const invalid = [url.protocol !== 'https:', !['checkout.stripe.com', 'billing.stripe.com'].includes(url.hostname), url.username, url.password];
28
+ if (invalid.some(Boolean)) throw Error('Unrecognized billing destination.');
29
+ window.location.assign(url.href);
30
+ }
31
+ export function Billing() {
32
+ const [identity, setIdentity] = useState<BillingIdentity | null>(null);
33
+ const [entitlements, setEntitlements] = useState<BillingEntitlements | null>(null);
34
+ const [pending, setPending] = useState(false); const [error, setError] = useState('');
35
+ const intents = useRef(new Map<string, string>());
36
+ useEffect(() => { let active = true; void Promise.all([api.identity(), api.entitlements()]).then(([user, access]) => { if (active) { setIdentity(user); setEntitlements(access); } }).catch(() => { if (active) setError('Unable to verify subscriptions.'); }); return () => { active = false; }; }, []);
37
+ function checkoutIntent(plan: string) { const key = intents.current.get(plan) ?? crypto.randomUUID(); intents.current.set(plan, key); return key; }
38
+ async function checkout(plan: string) {
39
+ if (pending || !identity) return;
40
+ setPending(true); setError('');
41
+ // Keep one intent through uncertain retries. The server controls customer, price and return URL.
42
+ const key = checkoutIntent(plan);
43
+ try { navigate((await api.checkout(plan, key)).url); } catch { setError('Checkout is unavailable. Retry to resume the same checkout.'); } finally { setPending(false); }
44
+ }
45
+ async function portal() { if (pending || !identity) return; setPending(true); setError(''); try { navigate((await api.portal()).url); } catch { setError('Billing management is unavailable.'); } finally { setPending(false); } }
46
+ return <section className="stack" aria-label="Subscription"><h2>Subscription</h2><p>{entitlements?.entitlements.some((grant) => grant.active) ? 'Active access' : 'No verified subscription'}</p>{identity?.providers.stripe && <>{identity.plans.map((plan) => <Button key={plan.id} disabled={pending} onClick={() => void checkout(plan.id)}>{plan.label}</Button>)}<Button disabled={pending} onClick={() => void portal()}>Manage web subscription</Button></>}<p role="status">{error}</p></section>;
47
+ }
48
+ `;