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
@@ -1,7 +1,7 @@
1
1
  import type { StandardProduct } from '../stack-registry.js';
2
2
  import type { Json } from '../scaffold/files.js';
3
3
  export type { StandardProduct } from '../stack-registry.js';
4
- export type Hosting = 'cloudflare' | 'vercel';
4
+ export type Hosting = 'cloudflare';
5
5
  export interface StandardOptions {
6
6
  root: string;
7
7
  name: string;
@@ -27,9 +27,9 @@ export interface SetupRequirements {
27
27
  verify: readonly string[];
28
28
  }
29
29
  export interface RecipeContext {
30
+ updating?: boolean;
30
31
  root: string;
31
32
  options: StandardOptions;
32
- runtimeApp: 'api' | 'web';
33
33
  bindings: Json;
34
34
  has: (product: string) => boolean;
35
35
  }
@@ -57,9 +57,4 @@ export interface StackRegistryItem {
57
57
  export interface ItemDefinition extends Omit<StackRegistryItem, 'bindings'> {
58
58
  install?: Recipe;
59
59
  configure?: (context: RecipeContext) => Json;
60
- resolveEnvironment?: (context: RecipeContext) => string[];
61
- resolveTargets?: (context: RecipeContext) => string[];
62
- resolvePackage?: (context: RecipeContext, recipe: PackageRecipe) => PackageRecipe;
63
- resolveDependencies?: (context: RecipeContext) => string[];
64
- fallbackDependency?: string;
65
60
  }
@@ -12,7 +12,7 @@ export function commandHelp(command) {
12
12
  return undefined;
13
13
  return `${entry.description}\n\nUsage: anhedral ${entry.usage}\n\nOptions:\n${[...entry.options, ...common].map((option) => ` ${option}`).join('\n')}\n\nExamples:\n${entry.examples.map((example) => ` anhedral ${example}`).join('\n')}${entry.note ? `\n\n${entry.note}` : ''}\n`;
14
14
  }
15
- export const STANDARD_USAGE = `Anhedral\nScaffold source, authenticate your providers, and ship your selected stack.\n\nUsage: anhedral <command> [options]\n\nStart here:\n${primary.map((name) => ` ${name.padEnd(12)}${COMMAND_HELP[name].description}`).join('\n')}\n\nDelivery tools:\n${Object.entries(COMMAND_HELP)
15
+ export const STANDARD_USAGE = `Anhedral\nCreate and ship applications with one consistent core stack.\n\nUsage: anhedral <command> [options]\n\nStart here:\n${primary.map((name) => ` ${name.padEnd(12)}${COMMAND_HELP[name].description}`).join('\n')}\n\nDelivery tools:\n${Object.entries(COMMAND_HELP)
16
16
  .filter(([name]) => !primary.includes(name))
17
17
  .map(([name, entry]) => ` ${name.padEnd(12)}${entry.description}`)
18
- .join('\n')}\n\nDefault: Vinext on Cloudflare Workers, from the official shadcn pnpm/Turborepo monorepo.\nExamples:\n anhedral init client-app\n anhedral auth client-app\n anhedral ship client-app --dry-run\n\nUse anhedral <command> --help for options and examples.\nUse anhedral help <command> for the same focused help.\nGlobal options:\n${common.map((option) => ` ${option}`).join('\n')}\n -v, --version Show the CLI version.\n`;
18
+ .join('\n')}\n\nDefault: Next.js web + native Expo + Hono + Drizzle/D1 + private R2, with Better Auth and shared styling. Stripe and RevenueCat are the only optional additions.\nExamples:\n anhedral init client-app\n anhedral init client-app --stripe --revenuecat\n anhedral auth client-app\n anhedral ship client-app --dry-run\n\nUse anhedral <command> --help for options and examples.\nUse anhedral help <command> for the same focused help.\nGlobal options:\n${common.map((option) => ` ${option}`).join('\n')}\n -v, --version Show the CLI version.\n`;
@@ -1,4 +1,2 @@
1
1
  /** Runtime policy shared by generation, setup guidance, and diagnostics. */
2
2
  export declare function supportsWorkspaceRuntime(version: string): boolean;
3
- export declare function supportsVoidRuntime(version: string): boolean;
4
- export declare function usesVoidSelection(products: readonly string[], hosting: string): boolean;
@@ -6,16 +6,3 @@ export function supportsWorkspaceRuntime(version) {
6
6
  const [major, minor] = match.slice(1).map(Number);
7
7
  return (major === 22 && minor >= 13) || major >= 24;
8
8
  }
9
- export function supportsVoidRuntime(version) {
10
- const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(version);
11
- if (!match)
12
- return false;
13
- const [major, minor] = match.slice(1).map(Number);
14
- return major > 24 || (major === 24 && minor >= 21);
15
- }
16
- export function usesVoidSelection(products, hosting) {
17
- return (!(products.includes('next') && hosting === 'cloudflare') &&
18
- !products.includes('queues') &&
19
- !products.includes('basin') &&
20
- products.some((product) => ['vinext', 'hono', 'realtime', 'cron', 'workflows'].includes(product)));
21
- }
@@ -1,22 +1,29 @@
1
+ import { scaffoldContracts } from './backend.js';
1
2
  import { resourceName, jsString } from '../render.js';
2
3
  import { STACK_DEPENDENCIES } from '../dependencies.js';
3
4
  import { workerConfig, worker } from './files.js';
4
5
  export function scaffoldApi({ root, options, bindings }) {
5
- worker(root, 'api', { ...workerConfig(resourceName(options.name, 'api')), ...bindings }, `import { OpenAPIHono, createRoute, z } from '@hono/zod-openapi';
6
+ scaffoldContracts(root);
7
+ worker(root, 'api', { ...workerConfig(resourceName(options.name, 'api')), ...bindings }, `import { OpenAPIHono, createRoute } from '@hono/zod-openapi';
8
+
9
+ import { healthSchema } from '@workspace/contracts';
10
+ import { bodyLimit } from 'hono/body-limit';
6
11
 
7
12
  const app = new OpenAPIHono<{ Bindings: Env }>();
13
+ app.use('/api/*', bodyLimit({ maxSize: 1024 * 1024 }));
8
14
  const health = createRoute({
9
15
  method: 'get',
10
16
  path: '/health',
11
17
  responses: {
12
18
  200: {
13
19
  description: 'Healthy',
14
- content: { 'application/json': { schema: z.object({ ok: z.literal(true) }) } },
20
+ content: { 'application/json': { schema: healthSchema } },
15
21
  },
16
22
  },
17
23
  });
18
24
 
19
25
  app.openapi(health, (c) => c.json({ ok: true as const }, 200));
26
+ app.get('/api/health', (c) => c.json(healthSchema.parse({ ok: true })));
20
27
  app.doc('/openapi.json', {
21
28
  openapi: '3.0.0',
22
29
  info: { title: ${jsString(options.name)}, version: '1.0.0' },
@@ -24,6 +31,7 @@ app.doc('/openapi.json', {
24
31
 
25
32
  export default app;
26
33
  `, {
34
+ '@workspace/contracts': 'workspace:*',
27
35
  hono: STACK_DEPENDENCIES['hono'],
28
36
  '@hono/zod-openapi': STACK_DEPENDENCIES['@hono/zod-openapi'],
29
37
  });
@@ -1,3 +1,2 @@
1
1
  import type { RecipeContext } from '../registry/types.js';
2
- export declare function scaffoldBetterAuth({ root, options, runtimeApp, has }: RecipeContext): void;
3
- export declare function scaffoldClerk({ root, has }: RecipeContext): void;
2
+ export declare function scaffoldBetterAuth({ root, updating }: RecipeContext): void;
@@ -1,135 +1,76 @@
1
+ import { scaffoldPasswordReset } from './password-reset.js';
2
+ import { scaffoldManagedEmail } from './managed-email.js';
3
+ import { expoAuthScheme, scaffoldExpoAuth } from './expo-auth.js';
4
+ import { jsString } from '../render.js';
1
5
  import { writeEnvironmentFile } from './environment.js';
2
6
  import { STACK_DEPENDENCIES } from '../dependencies.js';
3
- import { existsSync, readFileSync } from 'node:fs';
7
+ import { readFileSync } from 'node:fs';
4
8
  import path from 'node:path';
5
9
  import { writeBetterAuthSchema } from '../auth-schema.js';
6
10
  import { put, patchPackage, sharedPackage } from './files.js';
7
- export function scaffoldBetterAuth({ root, options, runtimeApp, has }) {
8
- writeBetterAuthSchema(root, has('neon'));
9
- sharedPackage(root, 'auth', `import { betterAuth } from 'better-auth';
11
+ export function scaffoldBetterAuth({ root, updating }) {
12
+ const scheme = expoAuthScheme(root);
13
+ scaffoldManagedEmail(root);
14
+ writeBetterAuthSchema(root, false);
15
+ sharedPackage(root, 'auth', `import { createManagedEmail, type EmailEnvironment } from '@workspace/managed-email';
16
+ import { expo } from '@better-auth/expo';
17
+ import { betterAuth } from 'better-auth';
10
18
  import { drizzleAdapter } from '@better-auth/drizzle-adapter';
11
19
  import type { createDatabase } from '@workspace/db';
12
- export function createAuth(db: ReturnType<typeof createDatabase>, secret: string, baseURL: string) {
20
+ export function createAuth(db: ReturnType<typeof createDatabase>, secret: string, baseURL: string, email: EmailEnvironment = {}) {
21
+ const sendEmail = createManagedEmail(email);
13
22
  return betterAuth({
14
- database: drizzleAdapter(db, { provider: '${has('neon') ? 'pg' : 'sqlite'}', transaction: false }),
15
- secret,
16
- baseURL,
17
- emailAndPassword: { enabled: true },
23
+ database: drizzleAdapter(db, { provider: 'sqlite', transaction: false }),
24
+ secret, baseURL,
25
+ trustedOrigins: [new URL(baseURL).origin, ${jsString(scheme + '://')}],
26
+ plugins: [expo()],
27
+ emailAndPassword: {
28
+ enabled: true,
29
+ requireEmailVerification: Boolean(sendEmail),
30
+ revokeSessionsOnPasswordReset: true,
31
+ sendResetPassword: sendEmail ? async ({ user, url }) => { await sendEmail('reset-password', user.email, url); } : undefined,
32
+ },
33
+ emailVerification: sendEmail ? {
34
+ sendOnSignUp: true,
35
+ sendVerificationEmail: async ({ user, url }) => { await sendEmail('verify-email', user.email, url); },
36
+ } : undefined,
18
37
  });
19
38
  }
20
39
  `, {
21
40
  'better-auth': STACK_DEPENDENCIES['better-auth'],
41
+ '@better-auth/expo': STACK_DEPENDENCIES['@better-auth/expo'],
22
42
  '@better-auth/drizzle-adapter': STACK_DEPENDENCIES['@better-auth/drizzle-adapter'],
23
43
  '@workspace/db': 'workspace:*',
44
+ '@workspace/managed-email': 'workspace:*',
24
45
  });
25
- patchPackage(root, `apps/${runtimeApp}/package.json`, {
26
- dependencies: { '@workspace/auth': 'workspace:*', '@workspace/db': 'workspace:*' },
46
+ patchPackage(root, 'apps/api/package.json', {
47
+ dependencies: {
48
+ '@workspace/auth': 'workspace:*',
49
+ '@workspace/managed-email': 'workspace:*',
50
+ '@workspace/db': 'workspace:*',
51
+ '@workspace/contracts': 'workspace:*',
52
+ },
27
53
  });
28
- const connection = has('neon') ? 'createDatabase(env.DATABASE_URL)' : 'createDatabase(env.DB)';
29
- if (has('hono')) {
30
- const source = readFileSync(path.join(root, 'apps/api/src/index.ts'), 'utf8');
31
- put(root, 'apps/api/src/index.ts', `import { createAuth } from '@workspace/auth';\nimport { createDatabase } from '@workspace/db';\n` +
32
- source.replace('export default app;', `app.on(['GET', 'POST'], '/api/auth/*', async (c) => {\n const env = c.env;\n const database = ${connection};\n return await createAuth(database, env.BETTER_AUTH_SECRET, env.BETTER_AUTH_URL).handler(c.req.raw);\n});\nexport default app;`));
33
- }
34
- else {
35
- put(root, 'apps/web/app/api/auth/[...all]/route.ts', `${has('vinext') ? "import { env } from 'cloudflare:workers';" : options.hosting === 'cloudflare' ? "import { getCloudflareContext } from '@opennextjs/cloudflare';" : ''}
36
- import { createAuth } from '@workspace/auth';
37
- import { createDatabase } from '@workspace/db';
38
- async function handler(request: Request) {
39
- ${options.hosting === 'cloudflare' && !has('vinext') ? 'const { env } = await getCloudflareContext({ async: true });' : ''}
40
- const database = ${options.hosting === 'vercel' ? 'createDatabase(process.env.DATABASE_URL!)' : connection};
41
- return await createAuth(database, ${options.hosting === 'cloudflare' ? 'env.BETTER_AUTH_SECRET, env.BETTER_AUTH_URL' : 'process.env.BETTER_AUTH_SECRET!, process.env.BETTER_AUTH_URL!'}).handler(request);
42
- }
43
- export { handler as GET, handler as POST };
44
- `);
45
- if (options.hosting === 'cloudflare' && !has('vinext'))
46
- put(root, 'apps/web/cloudflare-env.d.ts', `interface CloudflareEnv { BETTER_AUTH_SECRET: string; BETTER_AUTH_URL: string; ${has('neon') ? 'DATABASE_URL: string;' : "DB: Parameters<typeof import('drizzle-orm/d1').drizzle>[0];"} }\n`);
47
- if (has('vinext')) {
48
- put(root, 'apps/web/secrets.d.ts', 'declare namespace Cloudflare { interface Env { BETTER_AUTH_SECRET: string; BETTER_AUTH_URL: string } }\n');
49
- }
50
- patchPackage(root, 'apps/web/package.json', {
51
- dependencies: { 'drizzle-orm': STACK_DEPENDENCIES['drizzle-orm'] },
52
- });
53
- }
54
- writeEnvironmentFile(root, `apps/${runtimeApp}/${runtimeApp === 'web' && options.hosting === 'vercel' ? '.env.example' : '.dev.vars.example'}`, {
55
- ...(has('neon') ? { DATABASE_URL: '' } : {}),
54
+ let source = readFileSync(path.join(root, 'apps/api/src/index.ts'), 'utf8');
55
+ source =
56
+ "import { createAuth } from '@workspace/auth';\nimport { sessionSchema } from '@workspace/contracts';\n" +
57
+ source;
58
+ source = source.replace('export default app;', `app.get('/api/session', async (c) => {
59
+ c.header('cache-control', 'private, no-store');
60
+ const session = await createAuth(createDatabase(c.env.DB), c.env.BETTER_AUTH_SECRET, c.env.BETTER_AUTH_URL, c.env).api.getSession({ headers: c.req.raw.headers });
61
+ if (!session) return c.json({ error: 'Unauthorized' }, 401);
62
+ return c.json(sessionSchema.parse({ user: session.user }));
63
+ });
64
+ app.on(['GET', 'POST'], '/api/auth/*', (c) => createAuth(createDatabase(c.env.DB), c.env.BETTER_AUTH_SECRET, c.env.BETTER_AUTH_URL, c.env).handler(c.req.raw));
65
+ export default app;`);
66
+ put(root, 'apps/api/src/index.ts', source);
67
+ writeEnvironmentFile(root, 'apps/api/.dev.vars.example', {
56
68
  BETTER_AUTH_SECRET: '',
57
- BETTER_AUTH_URL: `http://localhost:${runtimeApp === 'web' ? '3000' : '8787'}`,
69
+ BETTER_AUTH_URL: 'http://localhost:3000',
70
+ ANHEDRAL_EMAIL_SCOPE: '',
71
+ ANHEDRAL_EMAIL_CAPABILITY: '',
58
72
  });
59
- if (has('hono'))
60
- put(root, 'apps/api/src/secrets.d.ts', 'interface Env { BETTER_AUTH_SECRET: string; BETTER_AUTH_URL: string }\n');
61
- }
62
- export function scaffoldClerk({ root, has }) {
63
- if (has('next') || has('vinext')) {
64
- patchPackage(root, 'apps/web/package.json', {
65
- dependencies: { '@clerk/nextjs': STACK_DEPENDENCIES['@clerk/nextjs'] },
66
- });
67
- const layoutPath = path.join(root, 'apps/web/app/layout.tsx');
68
- if (existsSync(layoutPath)) {
69
- const layout = readFileSync(layoutPath, 'utf8');
70
- if (!layout.includes('ClerkProvider')) {
71
- const wrapped = layout.replace(/(<body\b[^>]*>)([\s\S]*?)(<\/body>)/, '$1<ClerkProvider>$2</ClerkProvider>$3');
72
- if (wrapped === layout)
73
- throw new Error('Cannot configure ClerkProvider: the web layout must contain a body element.');
74
- put(root, 'apps/web/app/layout.tsx', 'import { ClerkProvider } from "@clerk/nextjs";\n' + wrapped);
75
- }
76
- }
77
- put(root, 'apps/web/app/sign-in/[[...sign-in]]/page.tsx', `import { Suspense } from 'react';
78
- import { SignIn } from '@clerk/nextjs';
79
-
80
- export default function SignInPage() {
81
- return (
82
- <Suspense fallback={<p role="status">Loading sign in…</p>}>
83
- <SignIn />
84
- </Suspense>
85
- );
86
- }
87
- `);
88
- put(root, 'apps/web/app/sign-up/[[...sign-up]]/page.tsx', `import { Suspense } from 'react';
89
- import { SignUp } from '@clerk/nextjs';
90
-
91
- export default function SignUpPage() {
92
- return (
93
- <Suspense fallback={<p role="status">Loading sign up…</p>}>
94
- <SignUp />
95
- </Suspense>
96
- );
97
- }
98
- `);
99
- put(root, 'apps/web/proxy.ts', `import { clerkMiddleware } from '@clerk/nextjs/server';
100
- import type { NextMiddleware } from 'next/server';
101
-
102
- const proxy: NextMiddleware = clerkMiddleware();
103
- export default proxy;
104
- export const config = { matcher: ['/((?!_next|[^?]*\\\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico)).*)', '/(api|trpc)(.*)'] };
105
- `);
106
- // Middleware makes auth available; product routes must explicitly require identity and authorization.
107
- }
108
- if (has('hono')) {
109
- sharedPackage(root, 'auth', `import { createClerkClient } from '@clerk/backend';
110
-
111
- export async function authenticate(
112
- request: Request,
113
- secretKey: string,
114
- publishableKey: string,
115
- authorizedParties: string[],
116
- ) {
117
- if (!secretKey || !publishableKey || authorizedParties.length === 0) {
118
- throw new Error('Configure Clerk keys and explicit authorized origins before authenticating.');
119
- }
120
- return createClerkClient({ secretKey, publishableKey }).authenticateRequest(request, {
121
- authorizedParties,
122
- });
123
- }
124
- `, { '@clerk/backend': STACK_DEPENDENCIES['@clerk/backend'] });
125
- writeEnvironmentFile(root, 'apps/api/.dev.vars.example', {
126
- CLERK_SECRET_KEY: '',
127
- CLERK_PUBLISHABLE_KEY: '',
128
- });
129
- }
130
- if (has('next') || has('vinext'))
131
- writeEnvironmentFile(root, 'apps/web/.env.example', {
132
- NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY: '',
133
- CLERK_SECRET_KEY: '',
134
- });
73
+ scaffoldExpoAuth(root, scheme, !updating);
74
+ scaffoldPasswordReset(root);
75
+ put(root, 'apps/api/src/secrets.d.ts', 'import type { EmailEnvironment } from "@workspace/managed-email";\ndeclare global { interface Env extends EmailEnvironment { BETTER_AUTH_SECRET: string; BETTER_AUTH_URL: string } }\n');
135
76
  }
@@ -0,0 +1,2 @@
1
+ /** Public contracts never import a framework, database or auth server. */
2
+ export declare function scaffoldContracts(root: string): void;
@@ -0,0 +1,39 @@
1
+ import { STACK_DEPENDENCIES } from '../dependencies.js';
2
+ import { put, sharedPackage } from './files.js';
3
+ /** Public contracts never import a framework, database or auth server. */
4
+ export function scaffoldContracts(root) {
5
+ sharedPackage(root, 'contracts', `import { z } from 'zod';
6
+ import { createHttpClient, type HttpOptions } from './http';
7
+
8
+ export const healthSchema = z.object({ ok: z.literal(true) });
9
+ export const sessionSchema = z.object({ user: z.object({ id: z.string(), name: z.string(), email: z.email() }) });
10
+ export type Session = z.infer<typeof sessionSchema>;
11
+
12
+ export function createApiClient(baseURL = '/api', options: HttpOptions = {}) {
13
+ const request = createHttpClient(baseURL, options);
14
+ return {
15
+ health: (init?: RequestInit) => request('/health', healthSchema, init),
16
+ session: (init?: RequestInit) => request('/session', sessionSchema, init),
17
+ };
18
+ }
19
+ `, { zod: STACK_DEPENDENCIES.zod });
20
+ put(root, 'packages/contracts/src/http.ts', `import type { z } from 'zod';
21
+
22
+ export interface HttpOptions {
23
+ headers?: () => HeadersInit | Promise<HeadersInit>;
24
+ credentials?: 'omit' | 'same-origin' | 'include';
25
+ }
26
+ export function createHttpClient(baseURL: string, options: HttpOptions = {}) {
27
+ return async function request<T>(route: string, schema: z.ZodType<T>, init: RequestInit = {}): Promise<T> {
28
+ const headers = new Headers(await options.headers?.());
29
+ new Headers(init.headers).forEach((value, name) => headers.set(name, value));
30
+ headers.set('accept', 'application/json');
31
+ // Worker fetch types omit the browser credentials member.
32
+ const settings: RequestInit & { credentials: 'omit' | 'same-origin' | 'include' } = { ...init, credentials: options.credentials ?? 'same-origin', headers };
33
+ const response = await fetch(baseURL.replace(/\\/$/, '') + route, settings);
34
+ if (!response.ok) throw new Error('API request failed (' + response.status + ').');
35
+ return schema.parse(await response.json());
36
+ };
37
+ }
38
+ `);
39
+ }
@@ -0,0 +1 @@
1
+ export declare const BILLING_CONFIG = "import { z } from 'zod';\n\nexport interface BillingEnv {\n BILLING_ORIGIN: string;\n BILLING_ENVIRONMENT: string;\n BILLING_PLANS_JSON?: string;\n BILLING_ENTITLEMENTS_JSON: string;\n BILLING_PREMIUM_ENTITLEMENT?: string;\n STRIPE_SECRET_KEY?: string;\n STRIPE_WEBHOOK_SECRET?: string;\n REVENUECAT_SECRET_KEY?: string;\n REVENUECAT_WEBHOOK_AUTHORIZATION?: string;\n REVENUECAT_WEBHOOK_SIGNING_SECRET?: string;\n REVENUECAT_APP_IDS_JSON?: string;\n REVENUECAT_PROJECT_ID?: string;\n}\nconst key = z.string().regex(/^[a-zA-Z0-9_.-]{1,100}$/);\nconst planSchema = z.object({ label: z.string().min(1).max(100), stripePriceId: z.string().regex(/^price_[a-zA-Z0-9]+$/), entitlement: key }).strict();\nconst plansSchema = z.record(key, planSchema);\nexport type Plan = z.infer<typeof planSchema>;\nexport interface Config {\n origin: string;\n environment: 'sandbox' | 'production';\n plans: Record<string, Plan>;\n entitlements: string[];\n appIds: string[];\n projectId: string;\n demoEntitlement: string;\n}\nfunction json(value: string | undefined, fallback: string): unknown {\n return JSON.parse(value ?? fallback);\n}\nfunction protocolAllowed(url: URL, environment: 'sandbox' | 'production'): boolean {\n if (url.protocol === 'https:') return true;\n if (environment !== 'sandbox') return false;\n return url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);\n}\nfunction origin(value: string, environment: 'sandbox' | 'production'): string {\n const url = new URL(value);\n if (!protocolAllowed(url, environment)) throw new Error('Billing requires HTTPS; sandbox HTTP is loopback-only.');\n if ([url.username, url.password, url.pathname !== '/', url.search, url.hash].some(Boolean)) throw new Error('Billing requires an origin without credentials or a path.');\n return url.origin;\n}\nexport function billingConfig(env: BillingEnv): Config {\n const environment = z.enum(['sandbox', 'production']).parse(env.BILLING_ENVIRONMENT);\n const plans = plansSchema.parse(json(env.BILLING_PLANS_JSON, '{}'));\n const entitlements = z.array(key).min(1).max(100).parse(json(env.BILLING_ENTITLEMENTS_JSON, '[]'));\n if (Object.values(plans).some((plan) => !entitlements.includes(plan.entitlement))) throw new Error('Every billing plan needs an allowed entitlement.');\n return {\n origin: origin(env.BILLING_ORIGIN, environment),\n environment,\n plans, entitlements,\n appIds: z.array(z.string().regex(/^app[a-zA-Z0-9_]+$/)).max(50).parse(json(env.REVENUECAT_APP_IDS_JSON, '[]')),\n projectId: env.REVENUECAT_PROJECT_ID ?? '',\n demoEntitlement: key.parse(env.BILLING_PREMIUM_ENTITLEMENT ?? 'premium'),\n };\n}\nexport function requireValue(value: string | undefined): string {\n if (!value?.trim()) throw new Error('Billing provider configuration is incomplete.');\n return value;\n}\nexport async function digest(value: string): Promise<string> {\n const bytes = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(value));\n return Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, '0')).join('');\n}\nexport async function equalSecret(actual: string, expected: string): Promise<boolean> {\n // Fixed-length digests make comparison independent of secret length.\n const values = await Promise.all([digest(actual), digest(expected)]);\n let difference = 0;\n for (let index = 0; index < values[0].length; index++) difference |= values[0].charCodeAt(index) ^ values[1].charCodeAt(index);\n return difference === 0;\n}\n";
@@ -0,0 +1,73 @@
1
+ export const BILLING_CONFIG = `import { z } from 'zod';
2
+
3
+ export interface BillingEnv {
4
+ BILLING_ORIGIN: string;
5
+ BILLING_ENVIRONMENT: string;
6
+ BILLING_PLANS_JSON?: string;
7
+ BILLING_ENTITLEMENTS_JSON: string;
8
+ BILLING_PREMIUM_ENTITLEMENT?: string;
9
+ STRIPE_SECRET_KEY?: string;
10
+ STRIPE_WEBHOOK_SECRET?: string;
11
+ REVENUECAT_SECRET_KEY?: string;
12
+ REVENUECAT_WEBHOOK_AUTHORIZATION?: string;
13
+ REVENUECAT_WEBHOOK_SIGNING_SECRET?: string;
14
+ REVENUECAT_APP_IDS_JSON?: string;
15
+ REVENUECAT_PROJECT_ID?: string;
16
+ }
17
+ const key = z.string().regex(/^[a-zA-Z0-9_.-]{1,100}$/);
18
+ const planSchema = z.object({ label: z.string().min(1).max(100), stripePriceId: z.string().regex(/^price_[a-zA-Z0-9]+$/), entitlement: key }).strict();
19
+ const plansSchema = z.record(key, planSchema);
20
+ export type Plan = z.infer<typeof planSchema>;
21
+ export interface Config {
22
+ origin: string;
23
+ environment: 'sandbox' | 'production';
24
+ plans: Record<string, Plan>;
25
+ entitlements: string[];
26
+ appIds: string[];
27
+ projectId: string;
28
+ demoEntitlement: string;
29
+ }
30
+ function json(value: string | undefined, fallback: string): unknown {
31
+ return JSON.parse(value ?? fallback);
32
+ }
33
+ function protocolAllowed(url: URL, environment: 'sandbox' | 'production'): boolean {
34
+ if (url.protocol === 'https:') return true;
35
+ if (environment !== 'sandbox') return false;
36
+ return url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
37
+ }
38
+ function origin(value: string, environment: 'sandbox' | 'production'): string {
39
+ const url = new URL(value);
40
+ if (!protocolAllowed(url, environment)) throw new Error('Billing requires HTTPS; sandbox HTTP is loopback-only.');
41
+ if ([url.username, url.password, url.pathname !== '/', url.search, url.hash].some(Boolean)) throw new Error('Billing requires an origin without credentials or a path.');
42
+ return url.origin;
43
+ }
44
+ export function billingConfig(env: BillingEnv): Config {
45
+ const environment = z.enum(['sandbox', 'production']).parse(env.BILLING_ENVIRONMENT);
46
+ const plans = plansSchema.parse(json(env.BILLING_PLANS_JSON, '{}'));
47
+ const entitlements = z.array(key).min(1).max(100).parse(json(env.BILLING_ENTITLEMENTS_JSON, '[]'));
48
+ if (Object.values(plans).some((plan) => !entitlements.includes(plan.entitlement))) throw new Error('Every billing plan needs an allowed entitlement.');
49
+ return {
50
+ origin: origin(env.BILLING_ORIGIN, environment),
51
+ environment,
52
+ plans, entitlements,
53
+ appIds: z.array(z.string().regex(/^app[a-zA-Z0-9_]+$/)).max(50).parse(json(env.REVENUECAT_APP_IDS_JSON, '[]')),
54
+ projectId: env.REVENUECAT_PROJECT_ID ?? '',
55
+ demoEntitlement: key.parse(env.BILLING_PREMIUM_ENTITLEMENT ?? 'premium'),
56
+ };
57
+ }
58
+ export function requireValue(value: string | undefined): string {
59
+ if (!value?.trim()) throw new Error('Billing provider configuration is incomplete.');
60
+ return value;
61
+ }
62
+ export async function digest(value: string): Promise<string> {
63
+ const bytes = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(value));
64
+ return Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, '0')).join('');
65
+ }
66
+ export async function equalSecret(actual: string, expected: string): Promise<boolean> {
67
+ // Fixed-length digests make comparison independent of secret length.
68
+ const values = await Promise.all([digest(actual), digest(expected)]);
69
+ let difference = 0;
70
+ for (let index = 0; index < values[0].length; index++) difference |= values[0].charCodeAt(index) ^ values[1].charCodeAt(index);
71
+ return difference === 0;
72
+ }
73
+ `;
@@ -0,0 +1,2 @@
1
+ /** Public billing transport exposes verified identity and entitlements, never provider secrets. */
2
+ export declare function scaffoldBillingContracts(root: string): void;
@@ -0,0 +1,48 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { scaffoldContracts } from './backend.js';
3
+ import path from 'node:path';
4
+ import { put } from './files.js';
5
+ /** Public billing transport exposes verified identity and entitlements, never provider secrets. */
6
+ export function scaffoldBillingContracts(root) {
7
+ if (!existsSync(path.join(root, 'packages/contracts/src/http.ts')))
8
+ scaffoldContracts(root);
9
+ put(root, 'packages/contracts/src/billing.ts', `import { z } from 'zod';
10
+ import { createHttpClient, type HttpOptions } from './http';
11
+
12
+ export const billingIdentitySchema = z.object({
13
+ appUserId: z.string(),
14
+ providers: z.object({ stripe: z.boolean(), revenuecat: z.boolean() }),
15
+ plans: z.array(z.object({ id: z.string(), label: z.string() })),
16
+ });
17
+ export const billingEntitlementsSchema = z.object({
18
+ entitlements: z.array(z.object({ key: z.string(), active: z.boolean(), expiresAt: z.string().nullable(), sources: z.array(z.enum(['stripe', 'revenuecat'])) })),
19
+ checkedAt: z.string(),
20
+ });
21
+ export const billingUrlSchema = z.object({ url: z.url().refine((value) => new URL(value).protocol === 'https:', 'Billing navigation requires HTTPS.') });
22
+ export type BillingIdentity = z.infer<typeof billingIdentitySchema>;
23
+ export type BillingEntitlements = z.infer<typeof billingEntitlementsSchema>;
24
+ export function createBillingClient(baseURL = '/api/billing', options: HttpOptions = {}) {
25
+ const request = createHttpClient(baseURL, options);
26
+ function post<T>(route: string, schema: z.ZodType<T>, body: unknown, headers: HeadersInit = {}) {
27
+ const combined = new Headers(headers);
28
+ combined.set('content-type', 'application/json');
29
+ return request(route, schema, { method: 'POST', body: JSON.stringify(body), headers: combined });
30
+ }
31
+ return {
32
+ identity: () => request('/identity', billingIdentitySchema),
33
+ entitlements: () => request('/entitlements', billingEntitlementsSchema),
34
+ refresh: () => post('/refresh', billingEntitlementsSchema, {}),
35
+ checkout: (plan: string, idempotencyKey: string) => {
36
+ const body = z.strictObject({ plan: z.string().min(1) }).parse({ plan });
37
+ const key = z.uuid().parse(idempotencyKey);
38
+ return post('/checkout', billingUrlSchema, body, { 'idempotency-key': key });
39
+ },
40
+ portal: () => post('/portal', billingUrlSchema, {}),
41
+ };
42
+ }
43
+ `);
44
+ const file = 'packages/contracts/src/index.ts';
45
+ const source = readFileSync(path.join(root, file), 'utf8');
46
+ if (!source.includes("export * from './billing'"))
47
+ put(root, file, source + "\nexport * from './billing';\n");
48
+ }
@@ -0,0 +1 @@
1
+ export declare const BILLING_PROVIDERS = "import Stripe from 'stripe';\nimport { z } from 'zod';\nimport { digest, requireValue, type BillingEnv, type Config, type Plan } from './config';\nimport type { Account, Store } from './store';\n\nexport interface Grant { key: string; expiresAt: number | null; source: 'stripe' | 'revenuecat' }\nexport class BillingConflict extends Error {}\nconst timeout = 15_000;\nexport function stripeClient(env: BillingEnv) {\n return new Stripe(requireValue(env.STRIPE_SECRET_KEY), { httpClient: Stripe.createFetchHttpClient(), maxNetworkRetries: 1, timeout });\n}\nexport function verifyMode(livemode: boolean, config: Config): void {\n if (livemode !== (config.environment === 'production')) throw new Error('Unexpected billing environment.');\n}\nfunction objectId(value: unknown): string | undefined {\n if (typeof value === 'string') return value;\n return z.object({ id: z.string() }).safeParse(value).data?.id;\n}\nasync function verifyCustomer(stripe: Stripe, customerId: string, userId: string, config: Config) {\n const customer = await stripe.customers.retrieve(customerId);\n if (customer.deleted) throw new Error('Billing customer no longer exists.');\n verifyMode(customer.livemode, config);\n if (customer.metadata.app_user_id !== userId) throw new Error('Billing customer ownership mismatch.');\n return customer;\n}\nasync function stripeCustomer(stripe: Stripe, account: Account, store: Store, config: Config): Promise<string> {\n if (account.stripeCustomerId) {\n await verifyCustomer(stripe, account.stripeCustomerId, account.userId, config);\n return account.stripeCustomerId;\n }\n const idempotencyKey = 'anhedral-customer-' + await digest(account.userId);\n const customer = await stripe.customers.create({ metadata: { app_user_id: account.userId } }, { idempotencyKey });\n verifyMode(customer.livemode, config);\n await store.customer(account, customer.id);\n return customer.id;\n}\nfunction activeSubscription(subscription: Stripe.Subscription): boolean {\n return ['active', 'trialing'].includes(subscription.status);\n}\nfunction planForPrice(price: string, config: Config): Plan | undefined {\n return Object.values(config.plans).find((plan) => plan.stripePriceId === price);\n}\nasync function soundCharge(stripe: Stripe, payment: Stripe.InvoicePayment, customerId: string, config: Config): Promise<boolean> {\n const intentId = objectId(payment.payment.payment_intent);\n if (!intentId) return false;\n const intent = await stripe.paymentIntents.retrieve(intentId, { expand: ['latest_charge'] });\n verifyMode(intent.livemode, config);\n if (objectId(intent.customer) !== customerId) throw new Error('Payment ownership mismatch.');\n const charge = intent.latest_charge;\n if (!expandedCharge(charge)) return false;\n return validCharge(charge, customerId, config);\n}\nfunction expandedCharge(value: Stripe.Charge | string | null): value is Stripe.Charge {\n return value !== null && typeof value !== 'string';\n}\nfunction validCharge(charge: Stripe.Charge, customerId: string, config: Config): boolean {\n verifyMode(charge.livemode, config);\n if (objectId(charge.customer) !== customerId) throw new Error('Charge ownership mismatch.');\n return [charge.paid, !charge.disputed, charge.amount_refunded === 0].every(Boolean);\n}\nasync function paidInvoice(stripe: Stripe, subscription: Stripe.Subscription, customerId: string, config: Config): Promise<boolean> {\n if (subscription.status === 'trialing') return true;\n const invoiceId = objectId(subscription.latest_invoice);\n if (!invoiceId) return false;\n const invoice = await stripe.invoices.retrieve(invoiceId);\n verifyMode(invoice.livemode, config);\n if (objectId(invoice.customer) !== customerId) throw new Error('Invoice ownership mismatch.');\n return invoicePayment(stripe, invoice, customerId, config);\n}\nasync function invoicePayment(stripe: Stripe, invoice: Stripe.Invoice, customerId: string, config: Config): Promise<boolean> {\n if (invoice.status !== 'paid') return false;\n if (invoice.amount_paid === 0) return true;\n const payments = await stripe.invoicePayments.list({ invoice: invoice.id, status: 'paid', limit: 100 });\n requireCompletePayments(payments);\n if (!payments.data.length) return false;\n const sound = await Promise.all(payments.data.map((payment) => soundCharge(stripe, payment, customerId, config)));\n return sound.every(Boolean);\n}\nfunction requireCompletePayments(payments: Stripe.ApiList<Stripe.InvoicePayment>): void {\n if (payments.has_more) throw new Error('Billing payment pagination requires reconciliation.');\n}\nfunction subscriptionGrants(subscription: Stripe.Subscription, config: Config): Grant[] {\n return subscription.items.data.flatMap((item): Grant[] => {\n const plan = planForPrice(item.price.id, config);\n if (!plan || item.current_period_end * 1000 <= Date.now()) return [];\n return [{ key: plan.entitlement, expiresAt: item.current_period_end * 1000, source: 'stripe' }];\n });\n}\nasync function grantsForSubscription(stripe: Stripe, subscription: Stripe.Subscription, account: Account, config: Config): Promise<Grant[]> {\n verifyMode(subscription.livemode, config);\n if (objectId(subscription.customer) !== account.stripeCustomerId) throw new Error('Subscription ownership mismatch.');\n if (!ownedActiveSubscription(subscription, account.userId)) return [];\n if (!await paidInvoice(stripe, subscription, account.stripeCustomerId!, config)) return [];\n return subscriptionGrants(subscription, config);\n}\nfunction ownedActiveSubscription(subscription: Stripe.Subscription, userId: string): boolean {\n return subscription.metadata.app_user_id === userId && activeSubscription(subscription);\n}\nasync function customerSubscriptions(stripe: Stripe, account: Account, config: Config): Promise<Stripe.Subscription[]> {\n if (!account.stripeCustomerId) return [];\n await verifyCustomer(stripe, account.stripeCustomerId, account.userId, config);\n const subscriptions = await stripe.subscriptions.list({ customer: account.stripeCustomerId, status: 'all', limit: 100 });\n if (subscriptions.has_more) throw new Error('Billing subscription pagination requires reconciliation.');\n return subscriptions.data;\n}\nexport async function stripeGrants(stripe: Stripe, account: Account, config: Config): Promise<Grant[]> {\n const subscriptions = await customerSubscriptions(stripe, account, config);\n const values = await Promise.all(subscriptions.map((subscription) => grantsForSubscription(stripe, subscription, account, config)));\n return values.flat();\n}\nfunction configuredSubscription(subscription: Stripe.Subscription, account: Account, config: Config): boolean {\n verifyMode(subscription.livemode, config);\n if (objectId(subscription.customer) !== account.stripeCustomerId) throw new Error('Subscription ownership mismatch.');\n if (['canceled', 'incomplete_expired'].includes(subscription.status)) return false;\n // A nonterminal configured subscription still needs management when its payment\n // failed or was refunded. Absence of an access grant never authorizes another sale.\n return subscription.items.data.some((item) => Boolean(planForPrice(item.price.id, config)));\n}\nasync function requireNewSubscription(stripe: Stripe, account: Account, config: Config): Promise<void> {\n const subscriptions = await customerSubscriptions(stripe, account, config);\n if (subscriptions.some((subscription) => configuredSubscription(subscription, account, config))) throw new BillingConflict('Manage the existing subscription in its billing portal.');\n}\nfunction verifyOpenSession(session: Stripe.Checkout.Session, account: Account, config: Config): string {\n verifyMode(session.livemode, config);\n if (objectId(session.customer) !== account.stripeCustomerId) throw new Error('Checkout ownership mismatch.');\n if (session.metadata?.app_user_id !== account.userId) throw new Error('Checkout identity mismatch.');\n return configuredSessionPlan(session, config);\n}\nfunction configuredSessionPlan(session: Stripe.Checkout.Session, config: Config): string {\n verifySessionKind(session);\n const plan = sessionPlanId(session);\n if (!plan) throw new Error('Checkout plan is missing.');\n if (!Object.hasOwn(config.plans, plan)) throw new Error('Unexpected checkout plan.');\n return plan;\n}\nfunction verifySessionKind(session: Stripe.Checkout.Session): void {\n if (session.mode !== 'subscription') throw new Error('Unexpected checkout mode.');\n if (session.status !== 'open') throw new Error('Unexpected checkout state.');\n}\nfunction sessionPlanId(session: Stripe.Checkout.Session): string | undefined { return session.metadata?.plan_id; }\nasync function pendingCheckout(stripe: Stripe, account: Account, planId: string, config: Config): Promise<string | undefined> {\n const sessions = await stripe.checkout.sessions.list({ customer: account.stripeCustomerId!, status: 'open', limit: 100 });\n if (sessions.has_more) throw new Error('Checkout pagination requires reconciliation.');\n const plans = sessions.data.map((session) => verifyOpenSession(session, account, config));\n if (plans.some((plan) => plan !== planId)) throw new BillingConflict('Finish the existing checkout before choosing another plan.');\n return openSessionURL(sessions.data);\n}\nfunction openSessionURL(sessions: Stripe.Checkout.Session[]): string | undefined {\n if (!sessions.length) return undefined;\n const session = sessions[0];\n verifySessionExpiration(session);\n return providerURL(requireValue(session.url ?? undefined), 'checkout.stripe.com');\n}\nfunction verifySessionExpiration(session: Stripe.Checkout.Session): void {\n if (!Number.isSafeInteger(session.expires_at)) throw new Error('Invalid checkout expiration.');\n if (session.expires_at * 1000 <= Date.now()) throw new BillingConflict('The existing checkout is expiring. Try again shortly.');\n}\nexport async function createCheckout(stripe: Stripe, account: Account, planId: string, idempotencyKey: string, store: Store, config: Config): Promise<string> {\n const plan = config.plans[planId];\n if (!plan) throw new Error('Unknown billing plan.');\n const customer = await stripeCustomer(stripe, account, store, config);\n const owner = { ...account, stripeCustomerId: customer };\n await requireNewSubscription(stripe, owner, config);\n const pending = await pendingCheckout(stripe, owner, planId, config);\n if (pending) return pending;\n const operation = await digest(account.userId + ':' + idempotencyKey);\n const result = await stripe.checkout.sessions.create({\n mode: 'subscription', customer,\n line_items: [{ price: plan.stripePriceId, quantity: 1 }],\n client_reference_id: account.userId,\n metadata: { app_user_id: account.userId, plan_id: planId },\n subscription_data: { metadata: { app_user_id: account.userId, plan_id: planId } },\n success_url: config.origin + '/billing?result=success',\n cancel_url: config.origin + '/billing?result=cancelled',\n integration_identifier: 'anhedral_' + operation.slice(0, 8).split('').map((character) => String.fromCharCode(97 + Number.parseInt(character, 16))).join(''),\n }, { idempotencyKey: 'anhedral-checkout-' + operation });\n return providerURL(requireValue(result.url ?? undefined), 'checkout.stripe.com');\n}\nfunction providerURL(value: string, hostname: string): string {\n const url = new URL(value);\n if ([url.protocol !== 'https:', url.hostname !== hostname, url.username, url.password].some(Boolean)) throw new Error('Unexpected billing provider URL.');\n return url.href;\n}\nexport async function createPortal(stripe: Stripe, account: Account, config: Config): Promise<string> {\n if (!account.stripeCustomerId) throw new Error('No web billing subscription for this account.');\n await verifyCustomer(stripe, account.stripeCustomerId, account.userId, config);\n const portal = await stripe.billingPortal.sessions.create({ customer: account.stripeCustomerId, return_url: config.origin + '/billing' });\n return providerURL(portal.url, 'billing.stripe.com');\n}\nexport async function stripeEventCustomer(stripe: Stripe, event: Stripe.Event): Promise<string | undefined> {\n const object = event.data.object as unknown as Record<string, unknown>;\n const customer = objectId(object.customer);\n if (customer) return customer;\n const charge = objectId(object.charge);\n if (!charge) return undefined;\n return objectId((await stripe.charges.retrieve(charge)).customer);\n}\n\nconst purchase = z.object({ is_sandbox: z.boolean(), store: z.string(), expires_date: z.string().nullable().optional(), grace_period_expires_date: z.string().nullable().optional() });\nconst rcSchema = z.object({ subscriber: z.object({\n entitlements: z.record(z.string(), z.object({ product_identifier: z.string(), expires_date: z.string().nullable(), grace_period_expires_date: z.string().nullable().optional() })),\n subscriptions: z.record(z.string(), purchase),\n non_subscriptions: z.record(z.string(), z.array(purchase)).optional(),\n}) });\ntype Subscriber = z.infer<typeof rcSchema>['subscriber'];\ntype Purchase = z.infer<typeof purchase>;\nfunction matchesPurchase(value: Purchase, config: Config, stripeEnabled: boolean): boolean {\n if (value.is_sandbox !== (config.environment === 'sandbox')) return false;\n return !(stripeEnabled && value.store === 'stripe');\n}\nfunction receiptForProduct(subscriber: Subscriber, productId: string, config: Config, stripeEnabled: boolean): Purchase | undefined {\n const candidates = [subscriber.subscriptions[productId], ...(subscriber.non_subscriptions?.[productId] ?? [])].filter((value): value is Purchase => Boolean(value));\n return candidates.find((value) => matchesPurchase(value, config, stripeEnabled));\n}\nfunction expires(value: string | null | undefined): number | null {\n if (value === null) return null;\n const parsed = Date.parse(value ?? '');\n if (!Number.isFinite(parsed)) throw new Error('Invalid provider entitlement expiry.');\n return parsed;\n}\nfunction revenueCatGrant(key: string, subscriber: Subscriber, config: Config, stripeEnabled: boolean): Grant[] {\n const entitlement = subscriber.entitlements[key];\n if (!entitlement) return [];\n const receipt = receiptForProduct(subscriber, entitlement.product_identifier, config, stripeEnabled);\n if (!receipt) return [];\n const expiry = entitlementExpiry(entitlement);\n if (!validExpiry(expiry)) return [];\n return [{ key, expiresAt: expiry, source: 'revenuecat' }];\n}\nfunction entitlementExpiry(entitlement: { expires_date: string | null; grace_period_expires_date?: string | null }): number | null {\n return expires(entitlement.grace_period_expires_date ?? entitlement.expires_date);\n}\nfunction validExpiry(expiry: number | null): boolean { return expiry === null || expiry > Date.now(); }\nfunction requireRevenueCatScope(config: Config): void {\n if (!config.projectId) throw new Error('Configure the RevenueCat project.');\n if (!config.appIds.length) throw new Error('Configure the RevenueCat app allowlist.');\n}\nexport async function revenueCatGrants(userId: string, env: BillingEnv, config: Config, stripeEnabled: boolean): Promise<Grant[]> {\n requireRevenueCatScope(config);\n const response = await fetch('https://api.revenuecat.com/v1/subscribers/' + encodeURIComponent(userId), {\n headers: { authorization: 'Bearer ' + requireValue(env.REVENUECAT_SECRET_KEY), accept: 'application/json' },\n signal: AbortSignal.timeout(timeout), redirect: 'error',\n });\n if (response.status === 404) return [];\n if (!response.ok) throw new Error('RevenueCat reconciliation failed.');\n const { subscriber } = rcSchema.parse(await response.json());\n return config.entitlements.flatMap((key) => revenueCatGrant(key, subscriber, config, stripeEnabled));\n}\n";