anhedral 0.11.2 → 0.13.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.
- package/README.md +171 -18
- package/dist/bin.js +48 -493
- package/dist/capabilities.d.ts +3 -3
- package/dist/capability-contract.js +16 -1
- package/dist/cli-arguments.d.ts +8 -0
- package/dist/cli-arguments.js +32 -0
- package/dist/cli-commands.d.ts +3 -0
- package/dist/cli-commands.js +114 -0
- package/dist/cli-delivery.d.ts +3 -0
- package/dist/cli-delivery.js +172 -0
- package/dist/cli-output.js +231 -205
- package/dist/command-schema.js +8 -2
- package/dist/command.js +9 -11
- package/dist/delivery-evidence.d.ts +62 -0
- package/dist/delivery-evidence.js +186 -0
- package/dist/delivery.d.ts +3 -40
- package/dist/delivery.js +7 -182
- package/dist/dependencies.d.ts +7 -1
- package/dist/dependencies.js +15 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/mobile-delivery.d.ts +21 -44
- package/dist/mobile-delivery.js +127 -80
- package/dist/platforms/mobile.d.ts +1 -1
- package/dist/platforms/mobile.js +44 -3
- package/dist/project-state.js +4 -1
- package/dist/provider-auth.js +9 -3
- package/dist/providers/adapters.js +9 -3
- package/dist/providers/runtime.js +11 -0
- package/dist/readiness.js +4 -2
- package/dist/registry/add.js +40 -7
- package/dist/registry/options.js +12 -0
- package/dist/registry/presets.d.ts +4 -0
- package/dist/registry/presets.js +41 -0
- package/dist/registry/resolve.d.ts +3 -1
- package/dist/registry/resolve.js +40 -14
- package/dist/registry/types.d.ts +1 -0
- package/dist/registry/usage.js +1 -1
- package/dist/runtime-policy.js +4 -1
- package/dist/scaffold/api.js +10 -2
- package/dist/scaffold/auth.d.ts +1 -1
- package/dist/scaffold/auth.js +22 -6
- package/dist/scaffold/backend.d.ts +6 -0
- package/dist/scaffold/backend.js +224 -0
- package/dist/scaffold/billing-config.d.ts +1 -0
- package/dist/scaffold/billing-config.js +73 -0
- package/dist/scaffold/billing-contracts.d.ts +2 -0
- package/dist/scaffold/billing-contracts.js +48 -0
- package/dist/scaffold/billing-providers.d.ts +1 -0
- package/dist/scaffold/billing-providers.js +249 -0
- package/dist/scaffold/billing-schema.d.ts +1 -0
- package/dist/scaffold/billing-schema.js +34 -0
- package/dist/scaffold/billing-security.d.ts +1 -0
- package/dist/scaffold/billing-security.js +46 -0
- package/dist/scaffold/billing-server.d.ts +1 -0
- package/dist/scaffold/billing-server.js +139 -0
- package/dist/scaffold/billing-store.d.ts +1 -0
- package/dist/scaffold/billing-store.js +72 -0
- package/dist/scaffold/billing.d.ts +2 -0
- package/dist/scaffold/billing.js +216 -0
- package/dist/scaffold/cloudflare-services.d.ts +8 -0
- package/dist/scaffold/cloudflare-services.js +198 -0
- package/dist/scaffold/compose.js +2 -0
- package/dist/scaffold/database.js +19 -2
- package/dist/scaffold/documentation.js +11 -6
- package/dist/scaffold/expo-auth.d.ts +3 -0
- package/dist/scaffold/expo-auth.js +192 -0
- package/dist/scaffold/expo-billing.d.ts +3 -0
- package/dist/scaffold/expo-billing.js +292 -0
- package/dist/scaffold/expo-runtime.d.ts +3 -0
- package/dist/scaffold/expo-runtime.js +134 -0
- package/dist/scaffold/integrations.d.ts +2 -1
- package/dist/scaffold/integrations.js +7 -2
- package/dist/scaffold/stream.d.ts +2 -0
- package/dist/scaffold/stream.js +114 -0
- package/dist/scaffold/void.js +13 -5
- package/dist/scaffold/web.js +2 -0
- package/dist/scaffold/workspace.js +6 -1
- package/dist/service-readers.js +1 -1
- package/dist/services-command.js +8 -6
- package/dist/ship.d.ts +15 -15
- package/dist/ship.js +3 -1
- package/dist/stack-registry.d.ts +13 -2
- package/dist/stack-registry.js +152 -16
- package/dist/transaction-lock.d.ts +15 -0
- package/dist/transaction-lock.js +227 -0
- package/dist/transaction.js +2 -208
- package/dist/vercel-project.d.ts +101 -0
- package/dist/vercel-project.js +305 -0
- package/dist/vercel.d.ts +3 -36
- package/dist/vercel.js +3 -300
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/docs/anhedral-stack.md +122 -0
- package/docs/software-factory.md +402 -7
- package/docs/stack-standard.md +226 -49
- package/docs/verification.md +557 -0
- package/package.json +7 -7
- package/docs/cli-design.md +0 -67
- package/docs/plugin-ui.md +0 -102
- package/docs/provider-configuration.md +0 -116
- package/docs/void-verification.md +0 -185
|
@@ -18,11 +18,11 @@ export function writeSetupDocumentation(root, options) {
|
|
|
18
18
|
put(root, 'AGENTS.md', existingAgents +
|
|
19
19
|
`# Anhedral delivery standard
|
|
20
20
|
|
|
21
|
-
Keep accounts, source, infrastructure, billing, and recovery client-owned. Use the available developer tools and the selected platforms’ native toolchains for implementation and verification. Use provider plugins, APIs/MCP and CLIs for operations; Void owns Cloudflare provisioning and deployment for supported selections; Anhedral owns composition, customer ownership and verification.
|
|
21
|
+
Keep accounts, source, infrastructure, billing, and recovery client-owned. Use the available developer tools and the selected platforms’ native toolchains for implementation and verification. Use provider plugins, APIs/MCP and CLIs for operations; Void owns Cloudflare provisioning and deployment for supported selections; Anhedral owns composition, customer ownership and verification. New Expo workspaces, explicit OpenNext, queue/DLQ and Basin selections use Wrangler delivery.
|
|
22
22
|
|
|
23
|
-
|
|
23
|
+
Plain init creates a minimal Expo client with shadcn conventions, NativeWind and shared styling. Generate Hono, contracts, database, auth, storage and integrations only when selected or required by selected capabilities. Use --preset full-product for the complete compatible selection, not mutually exclusive alternatives. Inspect docs/stack.md and anhedral.json for this project's actual selection. New Expo static web uses Cloudflare; native uses EXPO_PUBLIC_API_URL only when an API is selected. Next.js on Vercel and Vinext on Cloudflare are explicit alternatives. Respect account, budget, audience and release scope. Initialization does not deploy or activate paid services.
|
|
24
24
|
|
|
25
|
-
Use pnpm workspaces and Turborepo with one root pnpm-lock.yaml. Add apps and shared packages only when needed. All services belong in apps/*, reusable code in packages/*. Shared styling is named styling. Keep secrets and privileged integrations out of client bundles.
|
|
25
|
+
Hono owns server identity, authorization, persistence and privileged integrations. Web routes only proxy/adapt API calls. Share framework-independent validation and HTTP clients in packages/contracts; applications never import another app’s source. Use pnpm workspaces and Turborepo with one root pnpm-lock.yaml. Add apps and shared packages only when needed. All services belong in apps/*, reusable code in packages/*. Shared styling is named styling. Keep secrets and privileged integrations out of client bundles. When accounts are selected, prefer Better Auth unless Clerk is explicitly selected; native Clerk integration remains owner implementation. Preserve selected supported identity providers in existing and explicit compatibility profiles. Protect product routes explicitly and implement resource authorization.
|
|
26
26
|
|
|
27
27
|
Use private R2 Worker bindings. KV is eventually consistent configuration/cache, never transactional authority. Neon uses Drizzle and direct serverless HTTP with a server-only DATABASE_URL. HTTP supports independent queries and batches; interactive transactions require a reviewed WebSocket or PostgreSQL adapter. Define job retries, concurrency, idempotency and failure handling. Keep database factories and schemas in packages/db/src, SQL and metadata in packages/db/drizzle, and migration configuration in packages/db/drizzle.config.ts. Only server packages import @workspace/db; clients use API contracts and endpoints. Review generated SQL before deployment. One server target owns deployment migrations; other server targets only consume the database. Manual migration tasks are uncached and never part of builds or startup. Review SQL migrations before applying them.
|
|
28
28
|
|
|
@@ -34,11 +34,13 @@ For new projects, guide GitHub sign-in and the user's Git identity. Review files
|
|
|
34
34
|
|
|
35
35
|
Keep project identity, setup, registry, provider settings and selected hosting configuration in the single root anhedral.json. Consult docs/stack.md for the current generated options, targets and setup requirements. Maintain docs/architecture.md with selected components, rationale, alternatives, data/access boundaries, and a diagram of actual connections. Maintain docs/verification.md with product acceptance criteria, exercised flows, evidence, and blockers. Generated setup is a starter, not implemented product behavior.
|
|
36
36
|
|
|
37
|
+
For maintenance, treat static-analysis findings as candidates: trace dynamic entrypoints, shared consumers and authoritative live configuration before removing code or flags. Preserve kill switches, recovery paths and access controls. Keep one cleanup rationale per change and record evidence and remaining uncertainty in docs/verification.md. Diagnose flaky tests from CI history and causal evidence; fix the cause without weakening assertions or required checks. Change agent instructions in response to demonstrated failures, keeping shared context short. The Anhedral software factory's evidence-driven maintenance section supplies the detailed workflow.
|
|
38
|
+
|
|
37
39
|
Run pnpm check. Starters contain no application tests yet: add workspace tests and a meaningful root test:live script before claiming product verification. Use pnpm exec fallow during development and pnpm exec fallow audit for changes. Fix legitimate findings; use narrow documented exceptions. Verify real UI flows with Computer Use and Control Chrome, plus relevant integrations, native apps/simulators, and deployed previews. Carry an authorized build-and-ship request through deployment and live verification; ask only for authorization that is still missing.
|
|
38
40
|
`);
|
|
39
41
|
put(root, 'README.md', `# ${markdownHeading(options.name)}
|
|
40
42
|
|
|
41
|
-
Initialized
|
|
43
|
+
Initialized with the Anhedral Application Stack & Delivery Standard and pnpm/Turborepo. Expo uses universal frontend tooling; explicit Vinext/Next.js uses the pinned shadcn monorepo foundation.
|
|
42
44
|
|
|
43
45
|
Initial selection: ${options.products.join(', ')}. Project configuration is recorded in anhedral.json: identity, setup, standard, registry, providers, and the selected cloudflare/vercel hosting sections. Current selections and additions are summarized in [docs/stack.md](docs/stack.md). ${has('vinext') ? 'Vinext App Router on Cloudflare Workers.' : has('next') ? `Next.js hosting: ${options.hosting === 'cloudflare' ? 'Cloudflare Workers + OpenNext' : 'Vercel (native Next.js default)'}.` : ''}
|
|
44
46
|
|
|
@@ -46,20 +48,23 @@ Run pnpm install, commit pnpm-lock.yaml, then pnpm dev. Run pnpm check for lint,
|
|
|
46
48
|
|
|
47
49
|
${has('next') && options.hosting === 'vercel' ? 'Native Next.js uses customer-owned Vercel. Connect with the intended scope and personal/commercial use before shipping. Default to private all-deployment protection unless public access was requested; verify protection before linking Git or uploading code. Run anhedral doctor --providers for prerequisites and recorded provider context. Configure server secrets in that project; use cache components, partial prefetching, Link navigation and Suspense deliberately. ' : ''}${voidSelected ? 'Void owns provisioning and publication in the customer account. Keep explicit resources in anhedral.cloudflare.json and configuration in void.config.ts; commit void.lock.json after provisioning and serialize initial deployment across apps. Generated .void/ and .void-wrangler.jsonc are ignored. Copy each app’s env.example to its .env for local tooling; production server secrets use void secret with values passed via stdin. Local dotenv files remain private and untracked; they are not bundled into source or client assets. Supply public VITE_* values for Vite clients through the build environment. Vinext loads the app .env for local builds and maps NEXT_PUBLIC_* values into client bundles; supply those values in the production build environment. Generate Worker types before development. ' : ''}${has('vinext') ? 'Build with pnpm build, then pnpm --dir apps/web preview to exercise the production Worker. Vinext provides a Next-compatible API surface; native Next.js is an explicit framework option. ' : ''}${has('next') && options.hosting === 'cloudflare' ? 'Use the web preview script to exercise the actual OpenNext Worker runtime. ' : ''}Initialization does not provision infrastructure or deploy.
|
|
48
50
|
|
|
51
|
+
${has('expo') ? 'apps/mobile is the universal Expo web/iOS/Android frontend. Root pnpm dev exports static web and starts its Wrangler gateway on port 3000 plus Hono on port 8787 when selected. Native Metro uses pnpm --dir apps/mobile start; native iOS/Android scripts remain available. Browser changes require pnpm --dir apps/mobile build:web to re-export initially; no HMR is implied. worker/index.ts is the asset gateway and dist holds web assets. New Expo workspaces use Wrangler for selected Cloudflare targets. Export static web for the Cloudflare asset gateway. If Hono is selected, /api/* routes through its API binding before asset fallback; native uses public EXPO_PUBLIC_API_URL. Without Hono there is no API binding or origin to configure. Server credentials remain outside client bundles. Validate browser/API routing and iOS/Android exports separately; exports are not device or store acceptance. SDK 57 stays pinned. Static dynamic routes need generateStaticParams at build time or a deliberately implemented SPA/server profile; unknown paths do not gain SSR automatically. Experimental Expo SSR is not enabled by default. ' : ''}${has('hono') ? 'Hono is the backend. packages/contracts supplies public validation and the HTTP client. API /health and /openapi.json are public diagnostics; product routes require explicit authorization. ' : ''}${has('hono') && (has('vinext') || has('next')) ? `Web /api/* proxies to Hono and forwards session cookies. Check /api/health through the web origin. ${options.hosting === 'cloudflare' ? 'The web API service binding targets the API Worker; start both with root pnpm dev.' : 'Configure server-only apps/web/.env.local API_URL for local development and the web deployment environment API_URL with the API HTTPS origin before delivery. For a Cloudflare Access-protected API, configure a scoped service-token policy and server-only API_ACCESS_CLIENT_ID/API_ACCESS_CLIENT_SECRET on Vercel.'} Web never receives database/auth-server secrets. ` : ''}${has('hono') && (has('d1') || has('neon')) ? "Hono routes use c.get('database')() for a lazy Drizzle connection. " : ''}${has('better-auth') && (has('vinext') || has('next')) ? 'Set the API BETTER_AUTH_URL to the public web origin, configure its BETTER_AUTH_SECRET, apply reviewed database migrations, then test /sign-in and protected /api/session through web. ' : ''}
|
|
52
|
+
|
|
49
53
|
Security gate: pnpm audit:deps preserves the standard pnpm audit JSON in .anhedral-audit-report.json and blocks high or critical findings except the two exact verified braces/node-forge mitigations. Resolve findings through compatible upstream dependency updates. If the lock contains braces@3.0.3, Anhedral supplies a temporary exact-version pnpm patch in patches/ and records it in pnpm-workspace.yaml. It bounds nesting to 100 and rejects cyclic AST traversal; commit the patch and updated lock. When node-forge@1.4.0 occurs, a second exact patch fixes RSA DigestAlgorithm/NULL validation in the Node source and both shipped browser bundles. Only GHSA-vfj7-8cjw-p6xm for patched braces@3.0.3 and GHSA-86w9-cpqp-85rv for patched node-forge@1.4.0 can pass after verifying the exact advisory and version, effective pnpm patch map, and patch SHA-256. Runtime regressions across the affected entrypoints run in the Anhedral CLI repository tests. Upstream findings stay visible; missing or altered patch configuration and unrelated high/critical findings block delivery.
|
|
50
54
|
|
|
51
55
|
${has('next') && options.hosting === 'cloudflare' ? 'OpenNext is configured without a provisioned incremental-cache bucket. Choose and configure a cache adapter before using ISR or cache features that require shared persistence.\n' : ''}
|
|
52
56
|
${has('neon') ? 'Configure DATABASE_URL_UNPOOLED separately in packages/db/.env for transactional migrations on the intended branch. Configure server-only DATABASE_URL for the intended Neon branch and role. Direct HTTP needs no Hyperdrive or connection cleanup. Review migrations and authorization; interactive transactions require a reviewed WebSocket or PostgreSQL adapter.\n' : ''}
|
|
53
57
|
${has('neon') || has('d1') ? 'packages/db/src owns the reusable database factory, schema and migration entry point. Generated SQL lives in packages/db/drizzle; the config resolves paths from its own directory. Run pnpm db:generate, review SQL, then pnpm db:migrate. These tasks are uncached and separate from application builds. D1 defaults to local; pass -- --remote explicitly for the selected Worker database. Browser and native interfaces use an API, never database credentials.\n' : ''}
|
|
54
|
-
${has('better-auth') ? 'Core Better Auth tables are included in the Drizzle schema. Review and apply migrations before using /api/auth. Configure BETTER_AUTH_SECRET, BETTER_AUTH_URL and trusted origins for the correct environment.\n' : ''}
|
|
58
|
+
${has('expo') && has('better-auth') ? 'Expo identity includes the server Expo plugin with the exact configured scheme, SecureStore native client/cookie adapter, separate browser client, sign-in/account screens and shared protected session contracts. Configure secrets/origins and apply reviewed migrations. Local transport checks do not replace development-build/device acceptance. ' : ''}${has('better-auth') ? 'Core Better Auth tables are included in the Drizzle schema. Review and apply migrations before using /api/auth. Configure BETTER_AUTH_SECRET, BETTER_AUTH_URL and trusted origins for the correct environment.\n' : ''}
|
|
55
59
|
${has('clerk') ? `${has('next') || has('vinext') ? 'The web starter includes ClerkProvider, middleware and sign-in/sign-up pages. Configure NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY and server-only CLERK_SECRET_KEY. ' : ''}${has('hono') ? 'packages/auth exports a Clerk request authentication helper. Configure its server secret and publishable key, supply explicit authorized origins, and wire it into product routes; the API health route remains public. ' : ''}Authentication does not establish resource authorization.\n` : ''}
|
|
56
60
|
${has('r2') ? 'FILES is a private R2 binding. Implement authentication and file-level authorization before exposing file routes. Clients never receive R2 credentials.\n' : ''}
|
|
57
61
|
${has('neon-realtime') ? 'Neon Realtime is an optional beta live SQL foundation, separate from Durable Object rooms. Read [packages/neon-realtime/README.md](packages/neon-realtime/README.md) for the server/client factories and Drizzle adapter. Manually enable the intended branch, configure exact allowed origins and set server-only NEON_REALTIME_SECRET with DATABASE_URL; NEON_REALTIME_URL is public client transport configuration. Authenticate sealing requests and scope every query to verified user/tenant access. Implement subscriptions, authorized renewal and isolation tests; RLS, automatic Realtime provisioning and a public SQL endpoint are not provided. Live behavior remains unverified.\n' : ''}
|
|
62
|
+
${has('stream') ? 'Cloudflare Stream provides optional one-to-many WHIP/WHEP live video. Follow packages/stream/README.md and import the management factory only from @workspace/stream/server. Configure server-only STREAM_API_TOKEN and STREAM_ACCOUNT_ID manually. Authorize creators and input ownership; never return secret WHIP URLs to viewers. Implement playback token issuance for private media, browser signaling/UI and session cleanup. Stream activation, live inputs and runtime credentials are not automatically provisioned; live behavior remains unverified.\n' : ''}
|
|
58
63
|
${has('realtime') ? 'Durable Object rooms support hibernating WebSockets; the public entrypoint remains disabled until room authorization and short-lived tickets are implemented.\n' : ''}
|
|
59
64
|
${has('queues') ? 'Queue processing retries unimplemented jobs and uses a dead-letter queue. Add product processing and transactional idempotency before acknowledging messages.\n' : ''}
|
|
60
65
|
${has('basin') ? 'Basin uses a Pipelines stream binding. Configure its stream, sink, R2/catalog and SQL in client-owned infrastructure; it is distinct from operational logs.\n' : ''}
|
|
61
66
|
${has('neon') ? 'Neon provisioning configures the server runtime DATABASE_URL only. Set a separate direct DATABASE_URL_UNPOOLED in ignored packages/db/.env for the intended migration database and role. Run pnpm db:generate, review SQL, then pnpm db:migrate before testing authentication or application data.\n' : ''}
|
|
62
|
-
The root pnpm test command runs workspace test tasks; no application tests or test:live script are generated. Implement them for the product before verification.\n\nProvider packages are SDK factories or integration boundaries, not finished business features. Connect only needed packages to server entrypoints.
|
|
67
|
+
The root pnpm test command runs workspace test tasks; no application tests or test:live script are generated. Implement them for the product before verification.\n\nProvider packages are SDK factories or integration boundaries, not finished business features. Connect only needed packages to server entrypoints. Selected Stripe/RevenueCat billing generates authenticated Hono APIs, provider-verified webhook inbox, scheduled reconciliation and DB-backed entitlement enforcement; read packages/billing/README.md, configure plans/keys/IDs and review/apply SQL. Independent providers share the verified auth user ID; clients never grant access. Local data needs a platform-specific SQLite/filesystem adapter. Sentry needs a platform SDK and runtime initialization. Expo + Better Auth generates native/browser session clients, exact trusted scheme and sign-in/account screens; verify native behavior on a development build/device. Selected RevenueCat generates native purchase/restore/manage wiring; real development-build/store purchase acceptance remains required.
|
|
63
68
|
|
|
64
69
|
When the product needs a domain, purchase it in the client's GoDaddy account, then add its zone to the client's Cloudflare account and configure Cloudflare nameservers. The client retains registration, renewal, billing and recovery ownership. Verify DNS records and zone activation before connecting application domains and mail. Inbound mail uses Cloudflare Email Routing. Outbound business and application mail defaults to Cloudflare Email Sending; Resend is an alternative when selected. Configure the selected mail provider before use; init does not provision domains or mail services. GitHub Actions runs PR checks and never deploys automatically. Respect existing authorization; request only missing approval for paid activation, material spending, architecture changes or release.
|
|
65
70
|
`);
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { STACK_DEPENDENCIES } from '../dependencies.js';
|
|
4
|
+
import { jsString } from '../render.js';
|
|
5
|
+
import { json, patchPackage, put, readJson } from './files.js';
|
|
6
|
+
export function expoAuthScheme(root) {
|
|
7
|
+
const config = readJson(root, 'apps/mobile/app.json');
|
|
8
|
+
const scheme = config.expo?.scheme;
|
|
9
|
+
if (typeof scheme !== 'string' || !/^[a-z][a-z0-9+.-]*$/i.test(scheme))
|
|
10
|
+
throw new Error('Expo authentication requires one explicit valid app.json URL scheme.');
|
|
11
|
+
return scheme;
|
|
12
|
+
}
|
|
13
|
+
/** Platform resolution keeps SecureStore and the native plugin out of the browser bundle. */
|
|
14
|
+
export function scaffoldExpoAuth(root, scheme, linkHome = true) {
|
|
15
|
+
const directory = 'apps/mobile';
|
|
16
|
+
patchPackage(root, `${directory}/package.json`, {
|
|
17
|
+
dependencies: {
|
|
18
|
+
'better-auth': STACK_DEPENDENCIES['better-auth'],
|
|
19
|
+
'@better-auth/expo': STACK_DEPENDENCIES['@better-auth/expo'],
|
|
20
|
+
'expo-secure-store': STACK_DEPENDENCIES['expo-secure-store'],
|
|
21
|
+
'expo-network': STACK_DEPENDENCIES['expo-network'],
|
|
22
|
+
},
|
|
23
|
+
});
|
|
24
|
+
const config = readJson(root, `${directory}/app.json`);
|
|
25
|
+
const expo = config.expo;
|
|
26
|
+
const plugins = expo.plugins ?? [];
|
|
27
|
+
if (!plugins.some((plugin) => (Array.isArray(plugin) ? plugin[0] : plugin) === 'expo-secure-store'))
|
|
28
|
+
expo.plugins = [...plugins, 'expo-secure-store'];
|
|
29
|
+
json(root, `${directory}/app.json`, config);
|
|
30
|
+
put(root, `${directory}/lib/auth-client.ts`, `import { createAuthClient } from 'better-auth/react';
|
|
31
|
+
|
|
32
|
+
let client: ReturnType<typeof createAuthClient> | undefined;
|
|
33
|
+
export function getAuthClient() { return client ??= createAuthClient(); }
|
|
34
|
+
export function authConfigurationError(): string | null { return null; }
|
|
35
|
+
`);
|
|
36
|
+
put(root, `${directory}/lib/auth-client.native.ts`, `import { createAuthClient } from 'better-auth/react';
|
|
37
|
+
import { expoClient } from '@better-auth/expo/client';
|
|
38
|
+
import * as SecureStore from 'expo-secure-store';
|
|
39
|
+
import { nativeApiOrigin } from './api-client';
|
|
40
|
+
|
|
41
|
+
export function authConfigurationError(): string | null {
|
|
42
|
+
try { nativeApiOrigin(); return null; }
|
|
43
|
+
catch (error) { return error instanceof Error ? error.message : 'Invalid product API origin.'; }
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function createNativeClient() {
|
|
47
|
+
return createAuthClient({
|
|
48
|
+
baseURL: nativeApiOrigin(),
|
|
49
|
+
plugins: [expoClient({ scheme: ${jsString(scheme)}, storagePrefix: ${jsString(scheme)}, storage: SecureStore })],
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
let client: ReturnType<typeof createNativeClient> | undefined;
|
|
53
|
+
export function getAuthClient() { return client ??= createNativeClient(); }
|
|
54
|
+
`);
|
|
55
|
+
put(root, `${directory}/lib/session-api.ts`, `import { createApplicationApiClient } from './api-client';
|
|
56
|
+
export const sessionApi = createApplicationApiClient();
|
|
57
|
+
`);
|
|
58
|
+
put(root, `${directory}/lib/session-api.native.ts`, `import { createApplicationApiClient } from './api-client';
|
|
59
|
+
import { getAuthClient } from './auth-client.native';
|
|
60
|
+
|
|
61
|
+
export const sessionApi = createApplicationApiClient({ headers: async () => {
|
|
62
|
+
const cookie = await getAuthClient().getCookie();
|
|
63
|
+
const headers = new Headers();
|
|
64
|
+
if (cookie) headers.set('cookie', cookie);
|
|
65
|
+
return headers;
|
|
66
|
+
} });
|
|
67
|
+
`);
|
|
68
|
+
put(root, `${directory}/components/auth-configuration.tsx`, `import { Text, View } from 'react-native';
|
|
69
|
+
import { authConfigurationError } from '@/lib/auth-client';
|
|
70
|
+
|
|
71
|
+
export function AuthConfiguration({ children }: { children: React.ReactNode }) {
|
|
72
|
+
const error = authConfigurationError();
|
|
73
|
+
if (error) return <View style={{ padding: 24, gap: 12 }}><Text accessibilityRole="header">Configure the product API</Text><Text selectable>{error}</Text></View>;
|
|
74
|
+
return <>{children}</>;
|
|
75
|
+
}
|
|
76
|
+
`);
|
|
77
|
+
put(root, `${directory}/app/sign-in.tsx`, `import { useState } from 'react';
|
|
78
|
+
import { router } from 'expo-router';
|
|
79
|
+
import { ScrollView, Text, TextInput } from 'react-native';
|
|
80
|
+
import { Button } from '@/components/ui/button';
|
|
81
|
+
import { AuthConfiguration } from '@/components/auth-configuration';
|
|
82
|
+
import { getAuthClient } from '@/lib/auth-client';
|
|
83
|
+
import { sessionApi } from '@/lib/session-api';
|
|
84
|
+
|
|
85
|
+
export default function SignInRoute() { return <AuthConfiguration><SignIn /></AuthConfiguration>; }
|
|
86
|
+
|
|
87
|
+
function modeLabel(create: boolean): string { return create ? 'Create account' : 'Sign in'; }
|
|
88
|
+
function submitLabel(pending: boolean, create: boolean): string { return pending ? 'Working…' : modeLabel(create); }
|
|
89
|
+
function switchLabel(create: boolean): string { return create ? 'Use an existing account' : 'Create an account'; }
|
|
90
|
+
function authenticationError(error: unknown): string {
|
|
91
|
+
return error instanceof Error ? error.message : 'Unable to verify the session. Check the connection and try again.';
|
|
92
|
+
}
|
|
93
|
+
async function authenticate(values: { create: boolean; name: string; email: string; password: string }) {
|
|
94
|
+
const auth = getAuthClient();
|
|
95
|
+
const result = values.create ? await auth.signUp.email(values) : await auth.signIn.email(values);
|
|
96
|
+
if (result.error) throw new Error(result.error.message ?? 'Authentication failed.');
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function SignIn() {
|
|
100
|
+
const [create, setCreate] = useState(false);
|
|
101
|
+
const [name, setName] = useState('');
|
|
102
|
+
const [email, setEmail] = useState('');
|
|
103
|
+
const [password, setPassword] = useState('');
|
|
104
|
+
const [pending, setPending] = useState(false);
|
|
105
|
+
const [message, setMessage] = useState('');
|
|
106
|
+
async function submit() {
|
|
107
|
+
setPending(true); setMessage('');
|
|
108
|
+
try {
|
|
109
|
+
await authenticate({ create, name, email, password });
|
|
110
|
+
await sessionApi.session();
|
|
111
|
+
setPassword('');
|
|
112
|
+
router.replace('/account');
|
|
113
|
+
} catch (error) { setMessage(authenticationError(error)); }
|
|
114
|
+
finally { setPending(false); }
|
|
115
|
+
}
|
|
116
|
+
return <ScrollView contentContainerStyle={{ padding: 24, gap: 12 }} keyboardShouldPersistTaps="handled">
|
|
117
|
+
<Text accessibilityRole="header">{modeLabel(create)}</Text>
|
|
118
|
+
{create && <TextInput accessibilityLabel="Name" placeholder="Name" value={name} onChangeText={setName} autoComplete="name" />}
|
|
119
|
+
<TextInput accessibilityLabel="Email" placeholder="Email" value={email} onChangeText={setEmail} keyboardType="email-address" autoCapitalize="none" autoComplete="email" />
|
|
120
|
+
<TextInput accessibilityLabel="Password" placeholder="Password" value={password} onChangeText={setPassword} secureTextEntry autoComplete={create ? 'new-password' : 'current-password'} />
|
|
121
|
+
<Button disabled={pending} onPress={() => void submit()}>{submitLabel(pending, create)}</Button>
|
|
122
|
+
<Text accessibilityLiveRegion="polite">{message}</Text>
|
|
123
|
+
<Button disabled={pending} onPress={() => { setCreate(!create); setMessage(''); }}>{switchLabel(create)}</Button>
|
|
124
|
+
</ScrollView>;
|
|
125
|
+
}
|
|
126
|
+
`);
|
|
127
|
+
put(root, `${directory}/app/account.tsx`, `import { useEffect, useState } from 'react';
|
|
128
|
+
import { Link, Redirect, router } from 'expo-router';
|
|
129
|
+
import { Text, View } from 'react-native';
|
|
130
|
+
import type { Session } from '@workspace/contracts';
|
|
131
|
+
import { Button } from '@/components/ui/button';
|
|
132
|
+
import { AuthConfiguration } from '@/components/auth-configuration';
|
|
133
|
+
import { getAuthClient } from '@/lib/auth-client';
|
|
134
|
+
import { sessionApi } from '@/lib/session-api';
|
|
135
|
+
|
|
136
|
+
export default function AccountRoute() { return <AuthConfiguration><Account /></AuthConfiguration>; }
|
|
137
|
+
|
|
138
|
+
function Account() {
|
|
139
|
+
const { data: session, isPending, refetch } = getAuthClient().useSession();
|
|
140
|
+
const userId = session?.user.id;
|
|
141
|
+
const [verified, setVerified] = useState<Session['user'] | null>(null);
|
|
142
|
+
const [message, setMessage] = useState('');
|
|
143
|
+
const [pending, setPending] = useState(false);
|
|
144
|
+
useEffect(() => {
|
|
145
|
+
let active = true;
|
|
146
|
+
if (userId) void sessionApi.session().then(
|
|
147
|
+
(current) => { if (active) { setVerified(current.user); setMessage(''); } },
|
|
148
|
+
() => { if (active) { setVerified(null); setMessage('The server could not verify this session. Sign in again or retry when connected.'); } },
|
|
149
|
+
);
|
|
150
|
+
return () => { active = false; };
|
|
151
|
+
}, [userId]);
|
|
152
|
+
async function signOut() {
|
|
153
|
+
setVerified(null); setPending(true); setMessage('');
|
|
154
|
+
try {
|
|
155
|
+
const result = await getAuthClient().signOut();
|
|
156
|
+
if (result.error) { setMessage(result.error.message ?? 'Sign out failed.'); return; }
|
|
157
|
+
await refetch(); router.replace('/sign-in');
|
|
158
|
+
} catch { setMessage('Unable to sign out. Check the connection and retry.'); }
|
|
159
|
+
finally { setPending(false); }
|
|
160
|
+
}
|
|
161
|
+
if (isPending) return <View style={{ padding: 24 }}><Text>Restoring session…</Text></View>;
|
|
162
|
+
if (!session) return <Redirect href="/sign-in" />;
|
|
163
|
+
return <AccountContent userId={session.user.id} verified={verified} message={message} pending={pending} signOut={signOut} />;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function accountMessage(userId: string, verified: Session['user'] | null, message: string): string {
|
|
167
|
+
if (verified?.id === userId) return verified.email;
|
|
168
|
+
return message || 'Verifying with the API…';
|
|
169
|
+
}
|
|
170
|
+
function AccountContent({ userId, verified, message, pending, signOut }: {
|
|
171
|
+
userId: string; verified: Session['user'] | null; message: string; pending: boolean; signOut: () => Promise<void>;
|
|
172
|
+
}) {
|
|
173
|
+
return <View style={{ padding: 24, gap: 12 }}>
|
|
174
|
+
<Text accessibilityRole="header">Account</Text>
|
|
175
|
+
<Text>{accountMessage(userId, verified, message)}</Text>
|
|
176
|
+
<Text accessibilityLiveRegion="polite">{message}</Text>
|
|
177
|
+
<Button disabled={pending} onPress={() => void signOut()}>{pending ? 'Signing out…' : 'Sign out'}</Button>
|
|
178
|
+
<Link href="/sign-in">Sign in again</Link>
|
|
179
|
+
<Link href="/">Home</Link>
|
|
180
|
+
</View>;
|
|
181
|
+
}
|
|
182
|
+
`);
|
|
183
|
+
// Additions expose /account and /sign-in without rewriting existing product screens.
|
|
184
|
+
if (!linkHome)
|
|
185
|
+
return;
|
|
186
|
+
const home = `${directory}/app/index.tsx`;
|
|
187
|
+
const source = readFileSync(path.join(root, home), 'utf8');
|
|
188
|
+
if (source.includes('<Link href="/account">'))
|
|
189
|
+
return;
|
|
190
|
+
put(root, home, "import { Link } from 'expo-router';\n" +
|
|
191
|
+
source.replace("<Button onPress={() => void Linking.openURL('https://docs.expo.dev')}>Learn more</Button>", '<Link href="/account">Account and sign in</Link>\n <Button onPress={() => void Linking.openURL(\'https://docs.expo.dev\')}>Learn more</Button>'));
|
|
192
|
+
}
|
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
import { writeEnvironmentFile } from './environment.js';
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { STACK_DEPENDENCIES } from '../dependencies.js';
|
|
5
|
+
import { patchPackage, put } from './files.js';
|
|
6
|
+
/** Native store purchases and web Stripe checkout share only server-verified entitlements. */
|
|
7
|
+
export function scaffoldExpoBilling({ root, has }) {
|
|
8
|
+
if (!has('expo'))
|
|
9
|
+
return;
|
|
10
|
+
const directory = 'apps/mobile';
|
|
11
|
+
if (!has('better-auth')) {
|
|
12
|
+
put(root, `${directory}/billing-integration.md`, '# Native billing integration\n\nThe selected Clerk identity needs its native session adapter before using the authenticated billing APIs. Supply verified session headers to createBillingClient from @workspace/contracts. Do not use a client-selected account ID to authorize access.\n');
|
|
13
|
+
return;
|
|
14
|
+
}
|
|
15
|
+
if (has('revenuecat')) {
|
|
16
|
+
writeEnvironmentFile(root, `${directory}/.env.example`, {
|
|
17
|
+
EXPO_PUBLIC_REVENUECAT_IOS_API_KEY: '',
|
|
18
|
+
EXPO_PUBLIC_REVENUECAT_ANDROID_API_KEY: '',
|
|
19
|
+
});
|
|
20
|
+
patchPackage(root, `${directory}/package.json`, {
|
|
21
|
+
dependencies: { 'react-native-purchases': STACK_DEPENDENCIES['react-native-purchases'] },
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
put(root, `${directory}/lib/billing-api.ts`, `import { createBillingClient } from '@workspace/contracts';
|
|
25
|
+
export const billingApi = createBillingClient();
|
|
26
|
+
`);
|
|
27
|
+
put(root, `${directory}/lib/billing-api.native.ts`, `import { createBillingClient } from '@workspace/contracts';
|
|
28
|
+
import { nativeApiOrigin } from './api-client';
|
|
29
|
+
import { getAuthClient } from './auth-client.native';
|
|
30
|
+
|
|
31
|
+
function client() {
|
|
32
|
+
return createBillingClient(nativeApiOrigin() + '/api/billing', {
|
|
33
|
+
credentials: 'omit', headers: async () => {
|
|
34
|
+
const headers = new Headers();
|
|
35
|
+
headers.set('cookie', await getAuthClient().getCookie());
|
|
36
|
+
return headers;
|
|
37
|
+
},
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
export const billingApi = {
|
|
41
|
+
identity: () => client().identity(), entitlements: () => client().entitlements(),
|
|
42
|
+
refresh: () => client().refresh(), checkout: (plan: string, key: string) => client().checkout(plan, key),
|
|
43
|
+
portal: () => client().portal(),
|
|
44
|
+
};
|
|
45
|
+
`);
|
|
46
|
+
put(root, `${directory}/lib/billing-platform.ts`, `export interface StoreOffer { id: string; label: string; price: string }
|
|
47
|
+
export const billingPlatform = 'web';
|
|
48
|
+
export async function connectStore(_userId: string): Promise<void> {}
|
|
49
|
+
export async function disconnectStore(): Promise<void> {}
|
|
50
|
+
export async function storeOffers(): Promise<StoreOffer[]> { return []; }
|
|
51
|
+
export async function purchaseStoreOffer(_id: string): Promise<void> { throw new Error('Native store purchases require a device build.'); }
|
|
52
|
+
export async function restoreStorePurchases(): Promise<void> { throw new Error('Restore purchases in the native app.'); }
|
|
53
|
+
export async function manageStorePurchases(): Promise<void> { throw new Error('Native store management requires a device build.'); }
|
|
54
|
+
export function checkoutKey(): string { return crypto.randomUUID(); }
|
|
55
|
+
export async function openBillingURL(value: string): Promise<void> {
|
|
56
|
+
const url = new URL(value);
|
|
57
|
+
if (url.protocol !== 'https:') throw new Error('Billing navigation requires HTTPS.');
|
|
58
|
+
if (!['checkout.stripe.com', 'billing.stripe.com'].includes(url.hostname)) throw new Error('Unrecognized Stripe destination.');
|
|
59
|
+
globalThis.location.assign(url.href);
|
|
60
|
+
}
|
|
61
|
+
`);
|
|
62
|
+
if (has('revenuecat'))
|
|
63
|
+
put(root, `${directory}/lib/billing-platform.native.ts`, nativeStoreSource());
|
|
64
|
+
else
|
|
65
|
+
put(root, `${directory}/lib/billing-platform.native.ts`, `export type { StoreOffer } from './billing-platform';
|
|
66
|
+
export const billingPlatform = 'native';
|
|
67
|
+
export async function connectStore(_userId: string): Promise<void> {}
|
|
68
|
+
export async function disconnectStore(): Promise<void> {}
|
|
69
|
+
export async function storeOffers(): Promise<import('./billing-platform').StoreOffer[]> { return []; }
|
|
70
|
+
export async function purchaseStoreOffer(_id: string): Promise<void> { throw new Error('RevenueCat is not selected.'); }
|
|
71
|
+
export async function restoreStorePurchases(): Promise<void> { throw new Error('RevenueCat is not selected.'); }
|
|
72
|
+
export async function manageStorePurchases(): Promise<void> { throw new Error('RevenueCat is not selected.'); }
|
|
73
|
+
export function checkoutKey(): string { throw new Error('Stripe checkout is web-only.'); }
|
|
74
|
+
export async function openBillingURL(_url: string): Promise<void> { throw new Error('Stripe checkout is web-only.'); }
|
|
75
|
+
`);
|
|
76
|
+
put(root, `${directory}/app/billing.tsx`, billingScreenSource());
|
|
77
|
+
const account = `${directory}/app/account.tsx`;
|
|
78
|
+
const source = readFileSync(path.join(root, account), 'utf8');
|
|
79
|
+
const linked = source.includes('href="/billing"')
|
|
80
|
+
? source
|
|
81
|
+
: source.replace('<Link href="/">Home</Link>', '<Link href="/billing">Subscription and entitlements</Link>\n <Link href="/">Home</Link>');
|
|
82
|
+
if (linked.includes('await disconnectStore();'))
|
|
83
|
+
return;
|
|
84
|
+
put(root, account, "import { disconnectStore } from '@/lib/billing-platform';\n" +
|
|
85
|
+
linked.replace('const result = await getAuthClient().signOut();', 'await disconnectStore();\n const result = await getAuthClient().signOut();'));
|
|
86
|
+
}
|
|
87
|
+
function nativeStoreSource() {
|
|
88
|
+
return `import Purchases from 'react-native-purchases';
|
|
89
|
+
import { Linking, Platform } from 'react-native';
|
|
90
|
+
import type { StoreOffer } from './billing-platform';
|
|
91
|
+
export const billingPlatform = 'native';
|
|
92
|
+
let generation = 0;
|
|
93
|
+
let account: string | null = null;
|
|
94
|
+
let queue: Promise<void> = Promise.resolve();
|
|
95
|
+
|
|
96
|
+
function serial<T>(action: () => Promise<T>): Promise<T> {
|
|
97
|
+
const next = queue.then(action, action);
|
|
98
|
+
queue = next.then(() => undefined, () => undefined);
|
|
99
|
+
return next;
|
|
100
|
+
}
|
|
101
|
+
function platformKey(): string {
|
|
102
|
+
const keys: Partial<Record<string, string>> = {
|
|
103
|
+
ios: process.env.EXPO_PUBLIC_REVENUECAT_IOS_API_KEY,
|
|
104
|
+
android: process.env.EXPO_PUBLIC_REVENUECAT_ANDROID_API_KEY,
|
|
105
|
+
};
|
|
106
|
+
return keys[Platform.OS] ?? '';
|
|
107
|
+
}
|
|
108
|
+
function assertIdentity(token: number): void {
|
|
109
|
+
if (token !== generation) throw new Error('The signed-in account changed. Refresh subscriptions.');
|
|
110
|
+
if (!account) throw new Error('Sign in before using purchases.');
|
|
111
|
+
}
|
|
112
|
+
async function assertStoreIdentity(token: number): Promise<void> {
|
|
113
|
+
assertIdentity(token);
|
|
114
|
+
if (await Purchases.getAppUserID() !== account) throw new Error('The store account differs from the verified application account.');
|
|
115
|
+
assertIdentity(token);
|
|
116
|
+
}
|
|
117
|
+
export async function connectStore(userId: string): Promise<void> {
|
|
118
|
+
const token = ++generation;
|
|
119
|
+
account = null;
|
|
120
|
+
await serial(async () => {
|
|
121
|
+
await configureIdentity(userId);
|
|
122
|
+
if (token === generation) account = userId;
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
async function configureIdentity(userId: string): Promise<void> {
|
|
126
|
+
const apiKey = platformKey();
|
|
127
|
+
if (!apiKey) throw new Error('Configure the platform public RevenueCat SDK key and rebuild the native app.');
|
|
128
|
+
if (await Purchases.isConfigured()) await Purchases.logIn(userId);
|
|
129
|
+
else Purchases.configure({ apiKey, appUserID: userId });
|
|
130
|
+
await verifyConfiguredIdentity(userId);
|
|
131
|
+
}
|
|
132
|
+
async function verifyConfiguredIdentity(userId: string): Promise<void> {
|
|
133
|
+
if (await Purchases.getAppUserID() !== userId) throw new Error('Store identity synchronization failed.');
|
|
134
|
+
}
|
|
135
|
+
export async function disconnectStore(): Promise<void> {
|
|
136
|
+
++generation; account = null;
|
|
137
|
+
const operation = serial(async () => {
|
|
138
|
+
if (!(await Purchases.isConfigured())) return;
|
|
139
|
+
if (!(await Purchases.isAnonymous())) await Purchases.logOut();
|
|
140
|
+
});
|
|
141
|
+
await bestEffortLogout(operation);
|
|
142
|
+
}
|
|
143
|
+
async function bestEffortLogout(operation: Promise<void>): Promise<void> {
|
|
144
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
145
|
+
try {
|
|
146
|
+
await Promise.race([operation.catch(() => undefined), new Promise<void>((resolve) => { timer = setTimeout(resolve, 5000); })]);
|
|
147
|
+
} finally { clearTimeout(timer); }
|
|
148
|
+
}
|
|
149
|
+
async function availablePackages() {
|
|
150
|
+
const offerings = await Purchases.getOfferings();
|
|
151
|
+
return offerings.current?.availablePackages ?? [];
|
|
152
|
+
}
|
|
153
|
+
export async function storeOffers(): Promise<StoreOffer[]> {
|
|
154
|
+
const token = generation;
|
|
155
|
+
return serial(async () => {
|
|
156
|
+
await assertStoreIdentity(token);
|
|
157
|
+
const items = await availablePackages();
|
|
158
|
+
await assertStoreIdentity(token);
|
|
159
|
+
return items.map((item) => ({ id: item.identifier, label: item.product.title, price: item.product.priceString }));
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
export async function purchaseStoreOffer(id: string): Promise<void> {
|
|
163
|
+
const token = generation;
|
|
164
|
+
await serial(async () => {
|
|
165
|
+
await assertStoreIdentity(token);
|
|
166
|
+
const item = (await availablePackages()).find((entry) => entry.identifier === id);
|
|
167
|
+
if (!item) throw new Error('This offering is no longer available. Refresh subscriptions.');
|
|
168
|
+
await assertStoreIdentity(token);
|
|
169
|
+
await Purchases.purchasePackage(item);
|
|
170
|
+
await assertStoreIdentity(token);
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
export async function restoreStorePurchases(): Promise<void> {
|
|
174
|
+
const token = generation;
|
|
175
|
+
await serial(async () => { await assertStoreIdentity(token); await Purchases.restorePurchases(); await assertStoreIdentity(token); });
|
|
176
|
+
}
|
|
177
|
+
export async function manageStorePurchases(): Promise<void> {
|
|
178
|
+
const token = generation;
|
|
179
|
+
await serial(async () => {
|
|
180
|
+
await assertStoreIdentity(token);
|
|
181
|
+
const info = await Purchases.getCustomerInfo();
|
|
182
|
+
await assertStoreIdentity(token);
|
|
183
|
+
if (!info.managementURL) throw new Error('No store subscription management link is available.');
|
|
184
|
+
const url = new URL(info.managementURL);
|
|
185
|
+
if (url.protocol !== 'https:') throw new Error('Store management requires HTTPS.');
|
|
186
|
+
await Linking.openURL(url.href);
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
export function checkoutKey(): string { throw new Error('Stripe checkout is web-only.'); }
|
|
190
|
+
export async function openBillingURL(_url: string): Promise<void> { throw new Error('Stripe checkout is web-only.'); }
|
|
191
|
+
`;
|
|
192
|
+
}
|
|
193
|
+
function billingScreenSource() {
|
|
194
|
+
return `import { useCallback, useEffect, useRef, useState } from 'react';
|
|
195
|
+
import { Redirect } from 'expo-router';
|
|
196
|
+
import { ScrollView, Text, View } from 'react-native';
|
|
197
|
+
import type { BillingIdentity, BillingEntitlements } from '@workspace/contracts';
|
|
198
|
+
import { AuthConfiguration } from '@/components/auth-configuration';
|
|
199
|
+
import { Button } from '@/components/ui/button';
|
|
200
|
+
import { getAuthClient } from '@/lib/auth-client';
|
|
201
|
+
import { billingApi } from '@/lib/billing-api';
|
|
202
|
+
import { billingPlatform, checkoutKey, connectStore, disconnectStore, manageStorePurchases, openBillingURL, purchaseStoreOffer, restoreStorePurchases, storeOffers, type StoreOffer } from '@/lib/billing-platform';
|
|
203
|
+
|
|
204
|
+
export default function BillingRoute() { return <AuthConfiguration><Billing /></AuthConfiguration>; }
|
|
205
|
+
type Data = { identity: BillingIdentity; state: BillingEntitlements; offers: StoreOffer[] };
|
|
206
|
+
function billingError(error: unknown): string {
|
|
207
|
+
const message = error instanceof Error ? error.message : 'Billing is unavailable. Try again later.';
|
|
208
|
+
if (message === 'API request failed (409).') return 'A checkout, subscription, or billing update already exists. Retry shortly, continue your checkout, or manage your current subscription.';
|
|
209
|
+
return message;
|
|
210
|
+
}
|
|
211
|
+
function assertAccount(identity: BillingIdentity, userId: string, isCurrent: () => boolean) {
|
|
212
|
+
if (!isCurrent()) throw new Error('The signed-in account changed.');
|
|
213
|
+
if (identity.appUserId !== userId) throw new Error('The signed-in billing account changed.');
|
|
214
|
+
}
|
|
215
|
+
async function connectIdentity(identity: BillingIdentity, userId: string, isCurrent: () => boolean) {
|
|
216
|
+
assertAccount(identity, userId, isCurrent);
|
|
217
|
+
if (identity.providers.revenuecat) await connectStore(identity.appUserId);
|
|
218
|
+
assertAccount(identity, userId, isCurrent);
|
|
219
|
+
}
|
|
220
|
+
async function loadBilling(userId: string, isCurrent: () => boolean): Promise<Data> {
|
|
221
|
+
const identity = await billingApi.identity();
|
|
222
|
+
await connectIdentity(identity, userId, isCurrent);
|
|
223
|
+
const state = await billingApi.entitlements();
|
|
224
|
+
const offers = identity.providers.revenuecat ? await storeOffers() : [];
|
|
225
|
+
return { identity, state, offers };
|
|
226
|
+
}
|
|
227
|
+
function Billing() {
|
|
228
|
+
const { data: session, isPending } = getAuthClient().useSession();
|
|
229
|
+
const userId = session?.user.id;
|
|
230
|
+
const [data, setData] = useState<Data | null>(null);
|
|
231
|
+
const [message, setMessage] = useState('');
|
|
232
|
+
const [pending, setPending] = useState(false);
|
|
233
|
+
const [reload, setReload] = useState(0);
|
|
234
|
+
const attempts = useRef<Record<string, string>>({});
|
|
235
|
+
const generation = useRef(0);
|
|
236
|
+
const invalidate = useCallback(() => { ++generation.current; void disconnectStore(); }, []);
|
|
237
|
+
useEffect(() => {
|
|
238
|
+
const token = ++generation.current;
|
|
239
|
+
if (userId) void loadBilling(userId, () => token === generation.current).then(
|
|
240
|
+
(current) => { if (token === generation.current) setData(current); },
|
|
241
|
+
(error) => { if (token === generation.current) setMessage(billingError(error)); },
|
|
242
|
+
);
|
|
243
|
+
return invalidate;
|
|
244
|
+
}, [userId, reload, invalidate]);
|
|
245
|
+
function updateCurrent(token: number, action: () => void) { if (token === generation.current) action(); }
|
|
246
|
+
async function run(action: () => Promise<void>) {
|
|
247
|
+
const token = generation.current;
|
|
248
|
+
setPending(true); setMessage('');
|
|
249
|
+
try {
|
|
250
|
+
await action();
|
|
251
|
+
const state = await billingApi.refresh();
|
|
252
|
+
updateCurrent(token, () => setData((previous) => previous && { ...previous, state }));
|
|
253
|
+
} catch (error) { updateCurrent(token, () => setMessage(billingError(error))); }
|
|
254
|
+
finally { updateCurrent(token, () => setPending(false)); }
|
|
255
|
+
}
|
|
256
|
+
async function checkout(plan: string) {
|
|
257
|
+
const key = attempts.current[plan] ??= checkoutKey();
|
|
258
|
+
const result = await billingApi.checkout(plan, key);
|
|
259
|
+
await openBillingURL(result.url);
|
|
260
|
+
}
|
|
261
|
+
if (isPending) return <Text>Restoring session…</Text>;
|
|
262
|
+
if (!session) return <Redirect href="/sign-in" />;
|
|
263
|
+
return <SessionBilling userId={session.user.id} data={data} message={message} pending={pending} run={run} checkout={checkout} retry={() => setReload((value) => value + 1)} />;
|
|
264
|
+
}
|
|
265
|
+
function SessionBilling({ userId, data, message, pending, run, checkout, retry }: Actions & { userId: string; data: Data | null; message: string; checkout: (plan: string) => Promise<void>; retry: () => void }) {
|
|
266
|
+
if (data?.identity.appUserId !== userId) return <View style={{ padding: 24, gap: 12 }}><Text>{message || 'Loading subscriptions…'}</Text><Button onPress={retry}>Retry subscriptions</Button></View>;
|
|
267
|
+
return <BillingContent data={data} message={message} pending={pending} run={run} checkout={checkout} />;
|
|
268
|
+
}
|
|
269
|
+
function Entitlements({ state }: { state: BillingEntitlements }) {
|
|
270
|
+
return <View><Text accessibilityRole="header">Last server-verified access</Text>{state.entitlements.map((item) => <Text key={item.key}>{item.key}: {item.active ? 'Active' : 'Inactive'}</Text>)}<Text>Checked: {state.checkedAt}</Text></View>;
|
|
271
|
+
}
|
|
272
|
+
type Actions = { pending: boolean; run: (action: () => Promise<void>) => Promise<void> };
|
|
273
|
+
function WebPlans({ data, pending, run, checkout }: Actions & { data: Data; checkout: (plan: string) => Promise<void> }) {
|
|
274
|
+
if (!data.identity.providers.stripe) return <Text>Web checkout is not configured for this product.</Text>;
|
|
275
|
+
return <View style={{ gap: 12 }}>{data.identity.plans.map((plan) => <Button key={plan.id} disabled={pending} onPress={() => void run(() => checkout(plan.id))}>{plan.label}</Button>)}<Button disabled={pending} onPress={() => void run(async () => openBillingURL((await billingApi.portal()).url))}>Manage web subscription</Button></View>;
|
|
276
|
+
}
|
|
277
|
+
function NativePlans({ data, pending, run }: Actions & { data: Data }) {
|
|
278
|
+
if (!data.identity.providers.revenuecat) return <Text>Native store purchases are not selected.</Text>;
|
|
279
|
+
return <View style={{ gap: 12 }}>{data.offers.map((offer) => <Button key={offer.id} disabled={pending} onPress={() => void run(() => purchaseStoreOffer(offer.id))}>{offer.label + ' — ' + offer.price}</Button>)}<Button disabled={pending} onPress={() => void run(restoreStorePurchases)}>Restore purchases</Button><Button disabled={pending} onPress={() => void run(manageStorePurchases)}>Manage store subscription</Button></View>;
|
|
280
|
+
}
|
|
281
|
+
function BillingContent({ data, message, pending, run, checkout }: Actions & { data: Data; message: string; checkout: (plan: string) => Promise<void> }) {
|
|
282
|
+
return <ScrollView contentContainerStyle={{ padding: 24, gap: 16 }}>
|
|
283
|
+
<Text accessibilityRole="header">Subscriptions</Text>
|
|
284
|
+
<Entitlements state={data.state} />
|
|
285
|
+
{billingPlatform === 'web' ? <WebPlans data={data} pending={pending} run={run} checkout={checkout} /> : <NativePlans data={data} pending={pending} run={run} />}
|
|
286
|
+
<Button disabled={pending} onPress={() => void run(async () => undefined)}>Refresh server access</Button>
|
|
287
|
+
<Text accessibilityLiveRegion="polite">{message}</Text>
|
|
288
|
+
<Text>Purchases grant access only after server verification. Store account transfers follow the configured provider policy.</Text>
|
|
289
|
+
</ScrollView>;
|
|
290
|
+
}
|
|
291
|
+
`;
|
|
292
|
+
}
|