anhedral 0.12.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 (184) hide show
  1. package/README.md +35 -172
  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 -39
  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 -80
  26. package/dist/command.js +9 -11
  27. package/dist/delivery-evidence.d.ts +1 -1
  28. package/dist/delivery-evidence.js +7 -36
  29. package/dist/delivery.d.ts +2 -8
  30. package/dist/delivery.js +23 -102
  31. package/dist/dependencies.d.ts +12 -58
  32. package/dist/dependencies.js +67 -189
  33. package/dist/index.d.ts +1 -3
  34. package/dist/index.js +1 -3
  35. package/dist/inspector-model.d.ts +2 -2
  36. package/dist/integration-service-readers.d.ts +1 -2
  37. package/dist/integration-service-readers.js +3 -84
  38. package/dist/lifecycle-model.d.ts +1 -1
  39. package/dist/lifecycle-model.js +1 -1
  40. package/dist/mobile-delivery.d.ts +1 -1
  41. package/dist/mobile-delivery.js +4 -0
  42. package/dist/platforms/mobile.d.ts +1 -1
  43. package/dist/platforms/mobile.js +64 -114
  44. package/dist/platforms/web.d.ts +3 -0
  45. package/dist/platforms/web.js +299 -0
  46. package/dist/project-config.d.ts +1 -1
  47. package/dist/project-config.js +0 -1
  48. package/dist/project-inspector.js +5 -36
  49. package/dist/project-state.d.ts +1 -3
  50. package/dist/project-state.js +6 -86
  51. package/dist/provider-auth.js +3 -32
  52. package/dist/provider-readiness.d.ts +1 -1
  53. package/dist/provider-readiness.js +5 -24
  54. package/dist/providers/adapters.js +9 -178
  55. package/dist/providers/api.d.ts +1 -1
  56. package/dist/providers/api.js +3 -3
  57. package/dist/providers/config.js +2 -48
  58. package/dist/providers/definitions.d.ts +1 -204
  59. package/dist/providers/definitions.js +0 -85
  60. package/dist/providers/provision.d.ts +1 -1
  61. package/dist/providers/receipts.js +1 -11
  62. package/dist/providers/recovery-verification.js +1 -61
  63. package/dist/providers/runtime.js +15 -35
  64. package/dist/providers/state.js +1 -7
  65. package/dist/provision.d.ts +5 -13
  66. package/dist/provision.js +4 -80
  67. package/dist/readiness.d.ts +1 -1
  68. package/dist/readiness.js +3 -6
  69. package/dist/registry/add.js +11 -38
  70. package/dist/registry/bootstrap.d.ts +3 -2
  71. package/dist/registry/bootstrap.js +4 -13
  72. package/dist/registry/commands.js +8 -10
  73. package/dist/registry/context.js +0 -1
  74. package/dist/registry/options.js +8 -26
  75. package/dist/registry/resolve.d.ts +3 -2
  76. package/dist/registry/resolve.js +26 -82
  77. package/dist/registry/types.d.ts +2 -7
  78. package/dist/registry/usage.js +2 -2
  79. package/dist/runtime-policy.d.ts +0 -2
  80. package/dist/runtime-policy.js +0 -13
  81. package/dist/scaffold/api.js +10 -2
  82. package/dist/scaffold/auth.d.ts +1 -2
  83. package/dist/scaffold/auth.js +57 -116
  84. package/dist/scaffold/backend.d.ts +2 -0
  85. package/dist/scaffold/backend.js +39 -0
  86. package/dist/scaffold/billing-config.d.ts +1 -0
  87. package/dist/scaffold/billing-config.js +73 -0
  88. package/dist/scaffold/billing-contracts.d.ts +2 -0
  89. package/dist/scaffold/billing-contracts.js +48 -0
  90. package/dist/scaffold/billing-providers.d.ts +1 -0
  91. package/dist/scaffold/billing-providers.js +249 -0
  92. package/dist/scaffold/billing-schema.d.ts +1 -0
  93. package/dist/scaffold/billing-schema.js +34 -0
  94. package/dist/scaffold/billing-security.d.ts +1 -0
  95. package/dist/scaffold/billing-security.js +46 -0
  96. package/dist/scaffold/billing-server.d.ts +1 -0
  97. package/dist/scaffold/billing-server.js +139 -0
  98. package/dist/scaffold/billing-store.d.ts +1 -0
  99. package/dist/scaffold/billing-store.js +72 -0
  100. package/dist/scaffold/billing.d.ts +2 -0
  101. package/dist/scaffold/billing.js +208 -0
  102. package/dist/scaffold/bootstrap.d.ts +2 -3
  103. package/dist/scaffold/bootstrap.js +37 -43
  104. package/dist/scaffold/compose.js +2 -12
  105. package/dist/scaffold/database.d.ts +1 -1
  106. package/dist/scaffold/database.js +20 -111
  107. package/dist/scaffold/documentation.d.ts +0 -1
  108. package/dist/scaffold/documentation.js +22 -82
  109. package/dist/scaffold/expo-auth.d.ts +3 -0
  110. package/dist/scaffold/expo-auth.js +203 -0
  111. package/dist/scaffold/expo-billing.d.ts +3 -0
  112. package/dist/scaffold/expo-billing.js +257 -0
  113. package/dist/scaffold/expo-runtime.d.ts +3 -0
  114. package/dist/scaffold/expo-runtime.js +43 -0
  115. package/dist/scaffold/integrations.d.ts +1 -2
  116. package/dist/scaffold/integrations.js +9 -5
  117. package/dist/scaffold/managed-email.d.ts +3 -0
  118. package/dist/scaffold/managed-email.js +47 -0
  119. package/dist/scaffold/native-ui.d.ts +2 -0
  120. package/dist/scaffold/native-ui.js +69 -0
  121. package/dist/scaffold/password-reset.d.ts +1 -0
  122. package/dist/scaffold/password-reset.js +99 -0
  123. package/dist/scaffold/private-files.d.ts +2 -0
  124. package/dist/scaffold/private-files.js +78 -0
  125. package/dist/scaffold/stack-documentation.d.ts +0 -1
  126. package/dist/scaffold/stack-documentation.js +3 -49
  127. package/dist/scaffold/styling.d.ts +1 -1
  128. package/dist/scaffold/styling.js +20 -28
  129. package/dist/scaffold/web-billing.d.ts +2 -0
  130. package/dist/scaffold/web-billing.js +48 -0
  131. package/dist/scaffold/workspace.js +53 -189
  132. package/dist/service-deletion.js +1 -1
  133. package/dist/service-descriptor.js +5 -12
  134. package/dist/service-model.d.ts +1 -1
  135. package/dist/service-operations.js +2 -32
  136. package/dist/service-readers.js +1 -32
  137. package/dist/services-command.d.ts +1 -1
  138. package/dist/services-command.js +3 -9
  139. package/dist/ship.d.ts +3 -316
  140. package/dist/ship.js +13 -143
  141. package/dist/stack-registry.d.ts +2 -43
  142. package/dist/stack-registry.js +80 -308
  143. package/dist/standard.js +7 -14
  144. package/dist/version.d.ts +1 -1
  145. package/dist/version.js +1 -1
  146. package/docs/anhedral-stack.md +23 -0
  147. package/docs/assets/anhedral-stack-light.png +0 -0
  148. package/docs/assets/anhedral-stack.png +0 -0
  149. package/docs/software-factory.md +25 -499
  150. package/docs/stack-standard.md +48 -226
  151. package/docs/verification.md +433 -0
  152. package/package.json +22 -21
  153. package/dist/neon-service-data.d.ts +0 -8
  154. package/dist/neon-service-data.js +0 -117
  155. package/dist/platforms/desktop.d.ts +0 -2
  156. package/dist/platforms/desktop.js +0 -415
  157. package/dist/platforms/extension.d.ts +0 -2
  158. package/dist/platforms/extension.js +0 -328
  159. package/dist/scaffold/lint.d.ts +0 -4
  160. package/dist/scaffold/lint.js +0 -56
  161. package/dist/scaffold/neon-realtime.d.ts +0 -2
  162. package/dist/scaffold/neon-realtime.js +0 -97
  163. package/dist/scaffold/services.d.ts +0 -5
  164. package/dist/scaffold/services.js +0 -108
  165. package/dist/scaffold/stream.d.ts +0 -2
  166. package/dist/scaffold/stream.js +0 -114
  167. package/dist/scaffold/void.d.ts +0 -4
  168. package/dist/scaffold/void.js +0 -256
  169. package/dist/scaffold/web.d.ts +0 -2
  170. package/dist/scaffold/web.js +0 -128
  171. package/dist/vercel-project.d.ts +0 -101
  172. package/dist/vercel-project.js +0 -305
  173. package/dist/vercel.d.ts +0 -67
  174. package/dist/vercel.js +0 -581
  175. package/dist/vinext.d.ts +0 -2
  176. package/dist/vinext.js +0 -86
  177. package/dist/void-execution.d.ts +0 -10
  178. package/dist/void-execution.js +0 -94
  179. package/dist/void-migrations.d.ts +0 -6
  180. package/dist/void-migrations.js +0 -110
  181. package/dist/void-state.d.ts +0 -16
  182. package/dist/void-state.js +0 -65
  183. package/dist/void.d.ts +0 -3
  184. package/dist/void.js +0 -5
@@ -0,0 +1,208 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { STACK_DEPENDENCIES } from '../dependencies.js';
4
+ import { scaffoldBillingContracts } from './billing-contracts.js';
5
+ import { scaffoldWebBilling } from './web-billing.js';
6
+ import { scaffoldExpoBilling } from './expo-billing.js';
7
+ import { scaffoldBillingSchema } from './billing-schema.js';
8
+ import { BILLING_CONFIG } from './billing-config.js';
9
+ import { BILLING_SECURITY } from './billing-security.js';
10
+ import { BILLING_STORE } from './billing-store.js';
11
+ import { BILLING_PROVIDERS } from './billing-providers.js';
12
+ import { BILLING_SERVER } from './billing-server.js';
13
+ import { writeEnvironmentFile } from './environment.js';
14
+ import { json, patchPackage, put, readJson, sharedPackage } from './files.js';
15
+ function applicationBilling(context) {
16
+ const { has } = context;
17
+ const database = 'env.DB';
18
+ const authenticate = `const session = await createAuth(createDatabase(env.DB), env.BETTER_AUTH_SECRET, env.BETTER_AUTH_URL, env).api.getSession({ headers: request.headers });
19
+ if (!session) throw new BillingError(401, 'Sign in to access billing.');
20
+ return session.user.id;`;
21
+ return `import { Hono, type Context } from 'hono';
22
+ import { z } from 'zod';
23
+ import { createDatabase } from '@workspace/db';
24
+ import { createAuth } from '@workspace/auth';
25
+ import { createBilling, BillingError, type Billing } from '@workspace/billing/server';
26
+
27
+ type BillingContext = Context<{ Bindings: Env }>;
28
+ function billing(env: Env): Billing {
29
+ return createBilling({ database: createDatabase(${database}), env, stripeEnabled: ${has('stripe')}, revenueCatEnabled: ${has('revenuecat')} });
30
+ }
31
+ async function subject(request: Request, env: Env): Promise<string> {
32
+ ${authenticate}
33
+ }
34
+ function originAllowed(request: Request, env: Env): void {
35
+ if (!trustedOrigin(request, env)) throw new BillingError(403, 'Unexpected billing request origin.');
36
+ if (request.headers.get('sec-fetch-site') === 'cross-site') throw new BillingError(403, 'Cross-site billing requests are denied.');
37
+ if (!jsonRequest(request)) throw new BillingError(400, 'A JSON request is required.');
38
+ }
39
+ function jsonRequest(request: Request): boolean {
40
+ const contentType = request.headers.get('content-type') ?? '';
41
+ return contentType.split(';')[0].trim() === 'application/json';
42
+ }
43
+ function trustedOrigin(request: Request, env: Env): boolean {
44
+ const origin = request.headers.get('origin');
45
+ return !origin || origin === new URL(env.BILLING_ORIGIN).origin;
46
+ }
47
+ function handle(action: (context: BillingContext) => Promise<unknown>) {
48
+ return async (context: BillingContext) => {
49
+ context.header('cache-control', 'private, no-store');
50
+ try { return context.body(JSON.stringify(await action(context)), 200, { 'content-type': 'application/json' }); }
51
+ catch (error) {
52
+ if (error instanceof BillingError) return context.json({ error: error.message }, error.status);
53
+ if (error instanceof z.ZodError) return context.json({ error: 'Invalid billing request or configuration.' }, 400);
54
+ return context.json({ error: 'Billing is temporarily unavailable.' }, 503);
55
+ }
56
+ };
57
+ }
58
+ async function signedIn(context: BillingContext) {
59
+ const userId = await subject(context.req.raw, context.env);
60
+ return { userId, service: billing(context.env) };
61
+ }
62
+ async function mutation(context: BillingContext) {
63
+ originAllowed(context.req.raw, context.env);
64
+ return signedIn(context);
65
+ }
66
+ export const billingRoutes = new Hono<{ Bindings: Env }>();
67
+ billingRoutes.get('/billing/identity', handle(async (context) => {
68
+ const { service, userId } = await signedIn(context);
69
+ return service.identity(userId);
70
+ }));
71
+ billingRoutes.get('/billing/entitlements', handle(async (context) => {
72
+ const { service, userId } = await signedIn(context);
73
+ return service.entitlements(userId);
74
+ }));
75
+ billingRoutes.post('/billing/refresh', handle(async (context) => {
76
+ const { service, userId } = await mutation(context);
77
+ z.object({}).strict().parse(await context.req.json());
78
+ return service.entitlements(userId, true);
79
+ }));
80
+ billingRoutes.post('/billing/checkout', handle(async (context) => {
81
+ const { service, userId } = await mutation(context);
82
+ const { plan } = z.object({ plan: z.string().min(1).max(100) }).strict().parse(await context.req.json());
83
+ return service.checkout(userId, plan, context.req.header('idempotency-key') ?? '');
84
+ }));
85
+ billingRoutes.post('/billing/portal', handle(async (context) => {
86
+ const { service, userId } = await mutation(context);
87
+ z.object({}).strict().parse(await context.req.json());
88
+ return service.portal(userId);
89
+ }));
90
+ billingRoutes.get('/billing/premium', handle(async (context) => {
91
+ const { service, userId } = await signedIn(context);
92
+ await service.assertEntitled(userId, service.config.demoEntitlement);
93
+ return { ok: true, entitlement: service.config.demoEntitlement };
94
+ }));
95
+ billingRoutes.post('/webhooks/stripe', handle(async (context) => {
96
+ await billing(context.env).stripeWebhook(await context.req.text(), context.req.raw.headers);
97
+ return { received: true };
98
+ }));
99
+ billingRoutes.post('/webhooks/revenuecat', handle(async (context) => {
100
+ await billing(context.env).revenueCatWebhook(await context.req.text(), context.req.raw.headers);
101
+ return { received: true };
102
+ }));
103
+ export async function drainBilling(env: Env): Promise<void> {
104
+ try { await billing(env).drainPending(); }
105
+ catch { /* Missing configuration or provider outage grants nothing; inbox stays durable. */ }
106
+ }
107
+ `;
108
+ }
109
+ function connectApi(context) {
110
+ const { root } = context;
111
+ put(root, 'apps/api/src/billing.ts', applicationBilling(context));
112
+ put(root, 'apps/api/src/billing-env.d.ts', `import type { BillingEnv } from '@workspace/billing/config';
113
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type -- Merge billing bindings with Wrangler's generated Env.
114
+ declare global { interface Env extends BillingEnv {} }
115
+ export {};
116
+ `);
117
+ patchPackage(root, 'apps/api/package.json', {
118
+ dependencies: { '@workspace/billing': 'workspace:*', zod: STACK_DEPENDENCIES.zod },
119
+ });
120
+ const file = 'apps/api/src/index.ts';
121
+ const source = readFileSync(path.join(root, file), 'utf8');
122
+ if (!source.includes('import { billingRoutes, drainBilling }'))
123
+ put(root, file, "import { billingRoutes, drainBilling } from './billing';\n" +
124
+ source.replace('export default app;', `app.route('/api', billingRoutes);
125
+ // Retry a bounded batch of durable webhook records independently of client activity.
126
+ export default {
127
+ fetch: app.fetch,
128
+ scheduled(_event: ScheduledController, env: Env, context: ExecutionContext) {
129
+ context.waitUntil(drainBilling(env));
130
+ },
131
+ };`));
132
+ const configuration = 'apps/api/wrangler.jsonc';
133
+ const config = readJson(root, configuration);
134
+ const triggers = (config.triggers ?? {});
135
+ config.triggers = {
136
+ ...triggers,
137
+ crons: [...new Set([...(triggers.crons ?? []), '*/5 * * * *'])],
138
+ };
139
+ json(root, configuration, config);
140
+ }
141
+ export function scaffoldBilling(context) {
142
+ const { root, has } = context;
143
+ if (!has('hono'))
144
+ throw new Error('Billing requires the shared Hono runtime.');
145
+ if (!has('d1'))
146
+ throw new Error('Billing requires the core D1 database.');
147
+ scaffoldBillingContracts(root);
148
+ scaffoldBillingSchema(root);
149
+ sharedPackage(root, 'billing', "export { createBilling, BillingError } from './server';\n", {
150
+ '@workspace/contracts': 'workspace:*',
151
+ '@workspace/db': 'workspace:*',
152
+ stripe: STACK_DEPENDENCIES.stripe,
153
+ zod: STACK_DEPENDENCIES.zod,
154
+ 'drizzle-orm': STACK_DEPENDENCIES['drizzle-orm'],
155
+ });
156
+ patchPackage(root, 'packages/billing/package.json', {
157
+ exports: {
158
+ '.': './src/index.ts',
159
+ './server': './src/server.ts',
160
+ './config': './src/config.ts',
161
+ },
162
+ });
163
+ for (const [name, source] of Object.entries({
164
+ config: BILLING_CONFIG,
165
+ security: BILLING_SECURITY,
166
+ store: BILLING_STORE,
167
+ providers: BILLING_PROVIDERS,
168
+ server: BILLING_SERVER,
169
+ }))
170
+ put(root, `packages/billing/src/${name}.ts`, source);
171
+ connectApi(context);
172
+ writeEnvironmentFile(root, 'apps/api/.dev.vars.example', {
173
+ BILLING_ORIGIN: '',
174
+ BILLING_ENVIRONMENT: 'sandbox',
175
+ BILLING_PLANS_JSON: '{}',
176
+ BILLING_ENTITLEMENTS_JSON: '["premium"]',
177
+ BILLING_PREMIUM_ENTITLEMENT: 'premium',
178
+ ...(has('stripe') ? { STRIPE_SECRET_KEY: '', STRIPE_WEBHOOK_SECRET: '' } : {}),
179
+ ...(has('revenuecat')
180
+ ? {
181
+ REVENUECAT_SECRET_KEY: '',
182
+ REVENUECAT_WEBHOOK_AUTHORIZATION: '',
183
+ REVENUECAT_WEBHOOK_SIGNING_SECRET: '',
184
+ REVENUECAT_APP_IDS_JSON: '[]',
185
+ REVENUECAT_PROJECT_ID: '',
186
+ }
187
+ : {}),
188
+ });
189
+ scaffoldExpoBilling(context);
190
+ scaffoldWebBilling(context);
191
+ put(root, 'packages/billing/README.md', BILLING_README);
192
+ }
193
+ const BILLING_README = `# Shared billing
194
+
195
+ Hono owns authenticated Checkout, customer portal and entitlement decisions. Clients use the public contracts and never select a user/customer ID, raw Stripe price or return URL. Stripe web subscriptions and RevenueCat native subscriptions are independent provider projections; Hono unions their allowed entitlements. When both are enabled, RevenueCat Stripe receipts do not grant access, preventing stale Stripe mirrors from restoring a revoked web grant. Web purchases are not automatically imported into RevenueCat. Native clients query Hono for unified product access.
196
+
197
+ Generate and review SQL from packages/db/src/billing-schema.ts with pnpm db:generate, then migrate the selected development database explicitly. Builds and checks never migrate configured data. Billing accounts intentionally do not foreign-key a provider-specific user table. Use the verified auth subject as RevenueCat appUserID everywhere; identify through /api/billing/identity before purchasing. Account changes must switch RevenueCat identity and clear client entitlement state. Unknown webhook users are ignored; email never links accounts.
198
+
199
+ Set BILLING_ORIGIN to the exact product origin. HTTPS is required in production; sandbox development also permits HTTP on localhost, 127.0.0.1 or [::1] only. LAN HTTP is denied; physical devices require a reachable HTTPS origin. BILLING_PLANS_JSON maps a public plan ID to {label,stripePriceId,entitlement}; BILLING_ENTITLEMENTS_JSON lists allowed entitlement keys. Example: {"monthly":{"label":"Monthly","stripePriceId":"price_example","entitlement":"premium"}}. Return paths are /billing?result=success and /billing?result=cancelled; portal returns /billing. Configure the Stripe Customer Portal and required Stripe webhook event types from src/security.ts. POST Checkout requires a UUID Idempotency-Key; preserve the same UUID for retries of one intent. Under the account lease, an existing open checkout for the same configured plan is reused even for a distinct intent UUID. Another pending configured plan returns HTTP 409: finish that checkout before choosing another plan, or have the owner expire it in Stripe. Sessions use Stripe's default expiration; no retry-dependent expires_at parameter is sent. Nonterminal configured subscriptions, including payment failures and refunded active subscriptions, must be managed in the portal and cannot start a duplicate subscription. No access is granted by the return URL. Successful active or trial subscriptions grant until the verified item period ends; past_due is denied. Paid invoices with partial/full refunds or disputes deny web access. This conservative policy excludes out-of-band positive-value invoices without verified payment-intent charges.
200
+
201
+ Select BILLING_ENVIRONMENT explicitly for the intended sandbox/production backend. Keep Stripe test/live keys and webhook signing secrets isolated. Configure a dedicated RevenueCat project and allowed app IDs using REVENUECAT_PROJECT_ID and REVENUECAT_APP_IDS_JSON. RevenueCat webhook payloads normally omit project_id: the dedicated server API key and project-scoped webhook integration establish that boundary; a present mismatching project_id is rejected. REVENUECAT_SECRET_KEY is a server API v1 key, distinct from CLI management credentials. Require the configured Authorization header and enable HMAC signing with REVENUECAT_WEBHOOK_SIGNING_SECRET when available. Production never honors sandbox receipts, even when client keys or webhook payloads claim otherwise. Use separate RevenueCat projects for staging and production.
202
+
203
+ Webhook metadata is durably inserted before processing, with a unique provider/environment/event ID. Retries reconcile canonical provider state rather than replaying entitlement deltas. Per-account leases fence stale concurrent writes. Cached access lasts at most sixty seconds and never past a grant's expiry; an outage after that window fails closed. Failed records remain pending; the API's five-minute scheduled handler retries at most ten records per invocation. Inspect pending state/attempts operationally and repair configuration/provider access before retries. Code rollback does not reverse billing events or database migrations. Prune completed event records only under a reviewed retention policy long enough for provider replay windows.
204
+
205
+ GET /api/billing/premium demonstrates server enforcement through assertEntitled. It is a product example, not a substitute for placing guards on every actual paid operation. Review cross-account restore/transfer behavior and reconcile both source/destination accounts. Public SDK CustomerInfo is display state, never a server authorization claim. Digital consumables/credit balances, metered billing, tax registrations, refunds initiation and store publication are outside this subscription foundation.
206
+
207
+ Validate signup/session isolation, purchase/restore, renewal, failed payment, refund/dispute, cancellation versus expiry, duplicate/out-of-order webhooks, concurrent refresh, cross-user denial, environment isolation, invalid signatures and provider outage recovery. Local mocks/builds do not establish store purchases, configured provider acceptance or production billing. No services or payments are activated during generation.
208
+ `;
@@ -1,5 +1,4 @@
1
1
  import type { StandardRunner } from '../registry/types.js';
2
- export declare function assertBootstrapPlatform(run: StandardRunner, platform?: NodeJS.Platform): void;
3
- /** Planning and diagnostics support older Node releases; generated dependencies do not. */
4
2
  export declare function assertWorkspaceRuntime(run: StandardRunner, version?: string): void;
5
- export declare function bootstrapWorkspace(root: string, name: string, run: StandardRunner, webOnly?: boolean): void;
3
+ /** No downloaded template, disposable Next app or initialization-time cloud operation. */
4
+ export declare function bootstrapWorkspace(root: string, name: string, run: StandardRunner): void;
@@ -1,48 +1,42 @@
1
- import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync } from 'node:fs';
2
- import path from 'node:path';
3
- import { execFile, appendGitignore } from '../util.js';
4
- import { bootstrapArguments } from '../registry/bootstrap.js';
5
1
  import { supportsWorkspaceRuntime } from '../runtime-policy.js';
6
- export function assertBootstrapPlatform(run, platform = process.platform) {
7
- if (platform === 'win32' && run === execFile)
8
- throw new Error('Native Windows initialization is blocked because the upstream shadcn monorepo bootstrap writes component files outside the project. Run Anhedral inside WSL. Planning and doctor remain available on Windows.');
9
- }
10
- /** Planning and diagnostics support older Node releases; generated dependencies do not. */
2
+ import { execFile } from '../util.js';
3
+ import { STACK_DEPENDENCIES } from '../dependencies.js';
4
+ import { json, put } from './files.js';
11
5
  export function assertWorkspaceRuntime(run, version = process.versions.node) {
12
- if (run !== execFile)
13
- return;
14
- if (!supportsWorkspaceRuntime(version))
15
- throw new Error('Generated workspaces require Node.js 22.13+ on the 22.x line or Node.js 24+. Planning and doctor remain available on older CLI-supported versions.');
6
+ if (run === execFile && !supportsWorkspaceRuntime(version))
7
+ throw new Error('Generated workspaces require Node.js 22.13+ on the 22.x line or Node.js 24+.');
16
8
  }
17
- export function bootstrapWorkspace(root, name, run, webOnly = false) {
18
- assertBootstrapPlatform(run);
9
+ /** No downloaded template, disposable Next app or initialization-time cloud operation. */
10
+ export function bootstrapWorkspace(root, name, run) {
19
11
  assertWorkspaceRuntime(run);
20
- const temporary = path.join(root, '.bootstrap');
21
- mkdirSync(temporary);
22
- try {
23
- run('pnpm', bootstrapArguments(name, temporary), root);
24
- const generated = path.join(temporary, name);
25
- if (!existsSync(path.join(generated, 'pnpm-workspace.yaml')) ||
26
- !existsSync(path.join(generated, 'apps/web/package.json')))
27
- throw new Error('Official shadcn bootstrap did not produce the expected monorepo.');
28
- const ignored = ['.git', 'node_modules', '.next', '.turbo'];
29
- const seed = !webOnly && existsSync(path.join(root, '.gitignore'))
30
- ? readFileSync(path.join(root, '.gitignore'), 'utf8')
31
- : '';
32
- for (const entry of webOnly ? ['apps/web', 'packages/ui'] : readdirSync(generated)) {
33
- if (ignored.includes(entry))
34
- continue;
35
- if (webOnly && existsSync(path.join(root, entry)))
36
- throw new Error(`Web foundation target already exists: ${entry}.`);
37
- cpSync(path.join(generated, entry), path.join(root, entry), {
38
- recursive: true,
39
- filter: (source) => !ignored.includes(path.basename(source)),
40
- });
41
- }
42
- if (seed)
43
- appendGitignore(root, seed.split(/\r?\n/));
44
- }
45
- finally {
46
- rmSync(temporary, { recursive: true, force: true });
47
- }
12
+ json(root, 'package.json', { name, private: true });
13
+ put(root, 'pnpm-workspace.yaml', 'packages:\n - apps/*\n - packages/*\n');
14
+ json(root, 'packages/typescript-config/package.json', {
15
+ name: '@workspace/typescript-config',
16
+ private: true,
17
+ exports: { './base.json': './base.json' },
18
+ });
19
+ json(root, 'packages/typescript-config/base.json', {
20
+ compilerOptions: {
21
+ strict: true,
22
+ skipLibCheck: true,
23
+ target: 'ES2022',
24
+ module: 'ESNext',
25
+ moduleResolution: 'Bundler',
26
+ },
27
+ });
28
+ json(root, 'packages/eslint-config/package.json', {
29
+ name: '@workspace/eslint-config',
30
+ private: true,
31
+ type: 'module',
32
+ exports: { './base': './base.js', './react-internal': './react-internal.js' },
33
+ dependencies: {
34
+ typescript: STACK_DEPENDENCIES.typescript,
35
+ eslint: STACK_DEPENDENCIES.eslint,
36
+ '@typescript-eslint/parser': STACK_DEPENDENCIES['@typescript-eslint/parser'],
37
+ '@typescript-eslint/eslint-plugin': STACK_DEPENDENCIES['@typescript-eslint/eslint-plugin'],
38
+ },
39
+ });
40
+ put(root, 'packages/eslint-config/base.js', "import parser from '@typescript-eslint/parser';\nimport plugin from '@typescript-eslint/eslint-plugin';\nexport const config = [{ ignores: ['dist/**', '.output/**', '.wrangler/**', 'worker-configuration.d.ts'] }, { files: ['**/*.{ts,tsx,cts,mts}'], languageOptions: { parser, parserOptions: { ecmaFeatures: { jsx: true } } }, plugins: { '@typescript-eslint': plugin }, rules: { ...plugin.configs.recommended.rules, 'no-undef': 'off', 'no-unused-vars': 'off', '@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }] } }];\n");
41
+ put(root, 'packages/eslint-config/react-internal.js', "export { config } from './base.js';\n");
48
42
  }
@@ -1,33 +1,23 @@
1
1
  import { writeProjectSection } from '../project-config.js';
2
- import { existsSync, rmSync } from 'node:fs';
2
+ import { existsSync } from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { installStackItem } from '../stack-registry.js';
5
5
  import { createRecipeContext } from '../registry/context.js';
6
6
  import { inspectWorkspaceGraph } from '../workspace-graph.js';
7
7
  import { writeStandardRoot } from './workspace.js';
8
- import { normalizeSharedLint } from './lint.js';
9
- import { configureVoidDelivery } from './void.js';
10
8
  /** Only used in a fresh staged workspace. Existing applications are never overlaid. */
11
9
  export async function composeStack(root, options, registry) {
12
10
  const context = createRecipeContext(root, options);
13
- if (!context.has('next') && !context.has('vinext')) {
14
- for (const directory of ['apps/web', 'packages/ui'])
15
- rmSync(path.join(root, directory), { recursive: true, force: true });
16
- }
17
11
  for (const item of registry.items)
18
12
  Object.assign(context.bindings, item.bindings);
19
13
  for (const item of registry.items) {
20
14
  if (item.installer === 'recipe')
21
15
  await installStackItem(item, context);
22
16
  }
23
- normalizeSharedLint(root);
24
17
  writeStandardRoot(root, options, registry);
25
- configureVoidDelivery(root);
26
18
  for (const item of registry.items) {
27
19
  for (const target of item.targets) {
28
- if (!existsSync(path.join(root, target)) &&
29
- !(target.endsWith('/wrangler.jsonc') &&
30
- existsSync(path.join(root, target.replace('/wrangler.jsonc', '/anhedral.cloudflare.json')))))
20
+ if (!existsSync(path.join(root, target)))
31
21
  throw new Error(`Registry target missing: ${item.name} -> ${target}.`);
32
22
  }
33
23
  }
@@ -1,2 +1,2 @@
1
1
  import type { RecipeContext } from '../registry/types.js';
2
- export declare function scaffoldDatabase({ root, options, runtimeApp, has }: RecipeContext): void;
2
+ export declare function scaffoldDatabase({ root }: RecipeContext): void;
@@ -1,131 +1,40 @@
1
- import { writeEnvironmentFile } from './environment.js';
1
+ import { readFileSync } from 'node:fs';
2
+ import path from 'node:path';
2
3
  import { STACK_DEPENDENCIES } from '../dependencies.js';
3
- import { put, patchPackage, readJson, json, sharedPackage } from './files.js';
4
- export function scaffoldDatabase({ root, options, runtimeApp, has }) {
5
- const app = `apps/${runtimeApp}`;
6
- const postgres = has('neon');
7
- const directory = 'packages/db';
8
- sharedPackage(root, 'db', postgres
9
- ? `import { drizzle } from 'drizzle-orm/neon-http';
10
- import { neon } from '@neondatabase/serverless';
11
- import * as schema from './schema';
12
- export function createDatabase(connectionString: string) {
13
- // HTTP supports independent queries and batches; migrations use a separate transactional connection.
14
- return drizzle(neon(connectionString), { schema });
15
- }
16
- `
17
- : `import { drizzle } from 'drizzle-orm/d1';
4
+ import { put, patchPackage, sharedPackage } from './files.js';
5
+ export function scaffoldDatabase({ root }) {
6
+ sharedPackage(root, 'db', `import { drizzle } from 'drizzle-orm/d1';
18
7
  import * as schema from './schema';
19
8
  export function createDatabase(binding: Parameters<typeof drizzle>[0]) { return drizzle(binding, { schema }); }
20
- `, {
21
- 'drizzle-orm': STACK_DEPENDENCIES['drizzle-orm'],
22
- ...(postgres
23
- ? { '@neondatabase/serverless': STACK_DEPENDENCIES['@neondatabase/serverless'] }
24
- : {}),
25
- });
26
- put(root, `${directory}/src/schema.ts`, '// Define product tables here; generate and review SQL before migration.\nexport {};\n');
27
- put(root, `${directory}/drizzle/.gitkeep`, '');
28
- if (postgres)
29
- put(root, `${directory}/migration-environment.ts`, `import { existsSync } from 'node:fs';
30
- import { loadEnvFile } from 'node:process';
31
- import { fileURLToPath } from 'node:url';
32
- const root = new URL('./', import.meta.url);
33
- export function migrationEnvironment() {
34
- // Existing process values win; local overrides precede shared defaults.
35
- for (const name of ['.env.local', '.env']) {
36
- const file = fileURLToPath(new URL(name, root));
37
- if (existsSync(file)) loadEnvFile(file);
38
- }
39
- return { root, connectionString: process.env.DATABASE_URL_UNPOOLED };
40
- }
41
- `);
42
- put(root, `${directory}/drizzle.config.ts`, postgres
43
- ? `import { relative } from 'node:path';
44
- import { fileURLToPath } from 'node:url';
45
- import { defineConfig } from 'drizzle-kit';
46
- import { migrationEnvironment } from './migration-environment';
47
- const { root, connectionString: url } = migrationEnvironment();
48
- export default defineConfig({
49
- dialect: 'postgresql',
50
- schema: fileURLToPath(new URL('./src/schema.ts', root)),
51
- out: relative(process.cwd(), fileURLToPath(new URL('./drizzle/', root))),
52
- ...(url ? { dbCredentials: { url } } : {}),
53
- });
54
- `
55
- : `import { fileURLToPath } from 'node:url';
9
+ `, { 'drizzle-orm': STACK_DEPENDENCIES['drizzle-orm'] });
10
+ put(root, 'packages/db/src/schema.ts', '// Add application tables here. Generate and review SQL before migration.\nexport {};\n');
11
+ put(root, 'packages/db/drizzle/.gitkeep', '');
12
+ put(root, 'packages/db/drizzle.config.ts', `import { fileURLToPath } from 'node:url';
56
13
  import { relative } from 'node:path';
57
14
  import { defineConfig } from 'drizzle-kit';
58
- export default defineConfig({
59
- dialect: 'sqlite',
60
- schema: fileURLToPath(new URL('./src/schema.ts', import.meta.url)),
61
- out: relative(process.cwd(), fileURLToPath(new URL('./drizzle/', import.meta.url))),
62
- });
15
+ export default defineConfig({ dialect: 'sqlite', schema: fileURLToPath(new URL('./src/schema.ts', import.meta.url)), out: relative(process.cwd(), fileURLToPath(new URL('./drizzle/', import.meta.url))) });
63
16
  `);
64
- put(root, `${directory}/src/migrate.ts`, postgres
65
- ? `import { fileURLToPath } from 'node:url';
66
- import { Pool, neonConfig } from '@neondatabase/serverless';
67
- import { drizzle } from 'drizzle-orm/neon-serverless';
68
- import { migrate } from 'drizzle-orm/neon-serverless/migrator';
69
- import { migrationEnvironment } from '../migration-environment';
70
- const { root, connectionString } = migrationEnvironment();
71
- if (!connectionString) throw new Error('Configure DATABASE_URL_UNPOOLED for the intended migration branch and role.');
72
- let url: URL;
73
- try { url = new URL(connectionString); } catch { throw new Error('Configure a valid direct PostgreSQL migration URL.'); }
74
- if (!['postgres:', 'postgresql:'].includes(url.protocol) || url.hostname.includes('-pooler.'))
75
- throw new Error('Migrations require a direct PostgreSQL connection.');
76
- neonConfig.webSocketConstructor = WebSocket;
77
- const pool = new Pool({ connectionString });
78
- try {
79
- await migrate(drizzle(pool), { migrationsFolder: fileURLToPath(new URL('drizzle/', root)) });
80
- } catch {
81
- throw new Error('Database migration failed. Inspect the selected branch and migration history before retrying.');
82
- } finally {
83
- await pool.end();
84
- }
85
- `
86
- : `import { spawnSync } from 'node:child_process';
17
+ put(root, 'packages/db/src/migrate.ts', `import { spawnSync } from 'node:child_process';
87
18
  import { fileURLToPath } from 'node:url';
88
19
  const args = process.argv.slice(2);
89
- if (args.length > 1 || args.some((arg) => !['--local', '--remote'].includes(arg)))
90
- throw new Error('Usage: pnpm db:migrate [--local|--remote] (defaults to local).');
20
+ if (args.length > 1 || args.some((arg) => !['--local', '--remote'].includes(arg))) throw new Error('Usage: pnpm db:migrate [--local|--remote] (defaults to local).');
91
21
  const pnpm = process.env.npm_execpath;
92
22
  if (!pnpm) throw new Error('Run migrations through pnpm db:migrate.');
93
- const root = fileURLToPath(new URL('../../../apps/${runtimeApp}/', import.meta.url));
94
- const result = spawnSync(process.execPath, [pnpm, 'exec', 'wrangler', 'd1', 'migrations', 'apply', 'DB',
95
- args[0] ?? '--local', '--config', fileURLToPath(new URL('../../../apps/${runtimeApp}/wrangler.jsonc', import.meta.url)),
96
- ], { cwd: root, stdio: 'inherit', shell: false });
23
+ const root = fileURLToPath(new URL('../../../apps/api/', import.meta.url));
24
+ const result = spawnSync(process.execPath, [pnpm, 'exec', 'wrangler', 'd1', 'migrations', 'apply', 'DB', args[0] ?? '--local', '--config', fileURLToPath(new URL('../../../apps/api/wrangler.jsonc', import.meta.url))], { cwd: root, stdio: 'inherit', shell: false });
97
25
  if (result.error) throw result.error;
98
26
  process.exitCode = result.status ?? 1;
99
27
  `);
100
- patchPackage(root, `${directory}/package.json`, {
28
+ patchPackage(root, 'packages/db/package.json', {
101
29
  exports: { '.': './src/index.ts', './schema': './src/schema.ts' },
102
- dependencies: {
103
- 'drizzle-orm': STACK_DEPENDENCIES['drizzle-orm'],
104
- ...(postgres
105
- ? { '@neondatabase/serverless': STACK_DEPENDENCIES['@neondatabase/serverless'] }
106
- : {}),
107
- },
108
30
  devDependencies: {
109
31
  'drizzle-kit': STACK_DEPENDENCIES['drizzle-kit'],
110
- tsx: STACK_DEPENDENCIES['tsx'],
111
- ...(!postgres ? { wrangler: STACK_DEPENDENCIES['wrangler'] } : {}),
32
+ tsx: STACK_DEPENDENCIES.tsx,
33
+ wrangler: STACK_DEPENDENCIES.wrangler,
112
34
  },
113
35
  scripts: { 'db:generate': 'drizzle-kit generate', 'db:migrate': 'tsx src/migrate.ts' },
114
36
  });
115
- const tsconfig = readJson(root, `${directory}/tsconfig.json`);
116
- tsconfig.include = [...new Set([...(tsconfig.include ?? []), 'drizzle.config.ts'])];
117
- json(root, `${directory}/tsconfig.json`, tsconfig);
118
- // Consumers such as Better Auth add their direct workspace dependency when
119
- // they generate imports. Selecting a database alone creates reusable tooling.
120
- if (postgres) {
121
- const native = runtimeApp === 'web' && options.hosting === 'vercel';
122
- writeEnvironmentFile(root, `${app}/${native ? '.env.example' : '.dev.vars.example'}`, {
123
- DATABASE_URL: '',
124
- });
125
- writeEnvironmentFile(root, `${directory}/.env.example`, { DATABASE_URL_UNPOOLED: '' });
126
- if (!native)
127
- put(root, `${app}/${runtimeApp === 'api' ? 'src/' : ''}database-secrets.d.ts`, runtimeApp === 'api'
128
- ? 'interface Env { DATABASE_URL: string }\n'
129
- : 'declare namespace Cloudflare { interface Env { DATABASE_URL: string } }\n');
130
- }
37
+ patchPackage(root, 'apps/api/package.json', { dependencies: { '@workspace/db': 'workspace:*' } });
38
+ const source = readFileSync(path.join(root, 'apps/api/src/index.ts'), 'utf8');
39
+ put(root, 'apps/api/src/index.ts', "import { createDatabase } from '@workspace/db';\n" + source);
131
40
  }
@@ -1,3 +1,2 @@
1
1
  import type { StandardOptions } from '../registry/types.js';
2
- export declare function workerBuildSuffix(options: StandardOptions): string;
3
2
  export declare function writeSetupDocumentation(root: string, options: StandardOptions): void;