anhedral 0.12.0 → 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 +99 -39
- package/dist/capabilities.d.ts +3 -3
- package/dist/capability-contract.js +12 -1
- package/dist/command-schema.js +8 -2
- package/dist/command.js +9 -11
- package/dist/delivery.js +3 -1
- package/dist/dependencies.d.ts +6 -1
- package/dist/dependencies.js +13 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- 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 +6 -0
- 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 +10 -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/void.js +13 -5
- package/dist/scaffold/web.js +2 -0
- package/dist/scaffold/workspace.js +6 -1
- package/dist/ship.js +3 -1
- package/dist/stack-registry.d.ts +11 -2
- package/dist/stack-registry.js +136 -16
- 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 +67 -8
- package/docs/stack-standard.md +126 -57
- package/docs/verification.md +113 -0
- package/package.json +7 -4
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { writeEnvironmentFile } from './environment.js';
|
|
2
|
+
import { STACK_DEPENDENCIES } from '../dependencies.js';
|
|
3
|
+
import { resourceName } from '../render.js';
|
|
4
|
+
import { json, patchPackage, put, workerConfig } from './files.js';
|
|
5
|
+
/** Expo remains a static universal client. Its Worker owns only assets and API transport. */
|
|
6
|
+
export function scaffoldExpoRuntime({ root, options, has }) {
|
|
7
|
+
const directory = 'apps/mobile';
|
|
8
|
+
const api = has('hono');
|
|
9
|
+
const webPort = has('vinext') || has('next') ? 3001 : 3000;
|
|
10
|
+
json(root, `${directory}/wrangler.jsonc`, {
|
|
11
|
+
...workerConfig(resourceName(options.name, 'mobile')),
|
|
12
|
+
main: 'worker/index.ts',
|
|
13
|
+
assets: {
|
|
14
|
+
directory: './dist',
|
|
15
|
+
binding: 'ASSETS',
|
|
16
|
+
run_worker_first: ['/api', '/api/*'],
|
|
17
|
+
html_handling: 'auto-trailing-slash',
|
|
18
|
+
not_found_handling: '404-page',
|
|
19
|
+
},
|
|
20
|
+
...(api ? { services: [{ binding: 'API', service: resourceName(options.name, 'api') }] } : {}),
|
|
21
|
+
});
|
|
22
|
+
patchPackage(root, `${directory}/package.json`, {
|
|
23
|
+
scripts: {
|
|
24
|
+
dev: `pnpm build:web && wrangler dev --port ${webPort} --inspector-port 9230`,
|
|
25
|
+
start: 'expo start -c',
|
|
26
|
+
web: 'pnpm dev',
|
|
27
|
+
build: 'pnpm typecheck && pnpm build:web && pnpm build:worker',
|
|
28
|
+
'build:worker': 'wrangler deploy --dry-run --outdir .output/worker',
|
|
29
|
+
preview: `pnpm build:web && wrangler dev --port ${webPort} --inspector-port 9230`,
|
|
30
|
+
deploy: 'pnpm build:web && wrangler deploy',
|
|
31
|
+
typecheck: 'tsc --noEmit && pnpm typecheck:worker',
|
|
32
|
+
'typecheck:worker': 'tsc --project tsconfig.worker.json --noEmit',
|
|
33
|
+
lint: 'eslint app components lib worker --max-warnings 0',
|
|
34
|
+
},
|
|
35
|
+
...(api ? { dependencies: { '@workspace/contracts': 'workspace:*' } } : {}),
|
|
36
|
+
devDependencies: { wrangler: STACK_DEPENDENCIES.wrangler },
|
|
37
|
+
});
|
|
38
|
+
json(root, `${directory}/tsconfig.worker.json`, {
|
|
39
|
+
compilerOptions: {
|
|
40
|
+
target: 'ES2022',
|
|
41
|
+
lib: ['ES2022', 'DOM', 'DOM.Iterable'],
|
|
42
|
+
module: 'ESNext',
|
|
43
|
+
moduleResolution: 'Bundler',
|
|
44
|
+
strict: true,
|
|
45
|
+
skipLibCheck: true,
|
|
46
|
+
noEmit: true,
|
|
47
|
+
types: [],
|
|
48
|
+
},
|
|
49
|
+
include: ['worker/**/*.ts'],
|
|
50
|
+
});
|
|
51
|
+
put(root, `${directory}/worker/index.ts`, `interface Binding { fetch(request: Request): Promise<Response> }
|
|
52
|
+
interface Env { ASSETS: Binding; ${api ? 'API: Binding;' : ''} }
|
|
53
|
+
|
|
54
|
+
${api
|
|
55
|
+
? `// Browser-supplied edge identity headers never cross the API boundary.
|
|
56
|
+
function forwardedHeaders(request: Request): Headers {
|
|
57
|
+
const headers = new Headers();
|
|
58
|
+
for (const name of ['accept', 'content-type', 'cookie', 'origin', 'authorization', 'sec-fetch-site', 'expo-origin', 'idempotency-key']) {
|
|
59
|
+
const value = request.headers.get(name);
|
|
60
|
+
if (value) headers.set(name, value);
|
|
61
|
+
}
|
|
62
|
+
return headers;
|
|
63
|
+
}
|
|
64
|
+
function privateResponse(response: Response): Response {
|
|
65
|
+
const headers = new Headers(response.headers);
|
|
66
|
+
for (const name of ['connection', 'transfer-encoding', 'access-control-allow-origin', 'access-control-allow-credentials']) headers.delete(name);
|
|
67
|
+
headers.set('cache-control', 'private, no-store');
|
|
68
|
+
return new Response(response.body, { status: response.status, headers });
|
|
69
|
+
}
|
|
70
|
+
async function proxyApi(request: Request, env: Env): Promise<Response> {
|
|
71
|
+
const url = new URL(request.url);
|
|
72
|
+
const target = new URL('https://api.internal');
|
|
73
|
+
target.pathname = url.pathname;
|
|
74
|
+
target.search = url.search;
|
|
75
|
+
try {
|
|
76
|
+
const upstream = new Request(new Request(target, request), {
|
|
77
|
+
headers: forwardedHeaders(request), redirect: 'manual',
|
|
78
|
+
signal: AbortSignal.any([request.signal, AbortSignal.timeout(15000)]),
|
|
79
|
+
});
|
|
80
|
+
return privateResponse(await env.API.fetch(upstream));
|
|
81
|
+
} catch {
|
|
82
|
+
return Response.json({ error: 'API unavailable' }, { status: 503, headers: { 'cache-control': 'private, no-store' } });
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
`
|
|
86
|
+
: ''}
|
|
87
|
+
export default {
|
|
88
|
+
async fetch(request: Request, env: Env): Promise<Response> {
|
|
89
|
+
const pathname = new URL(request.url).pathname;
|
|
90
|
+
const apiPath = pathname === '/api' || pathname.startsWith('/api/');
|
|
91
|
+
if (!apiPath) return env.ASSETS.fetch(request);
|
|
92
|
+
${api ? 'return proxyApi(request, env);' : "return Response.json({ error: 'API not configured' }, { status: 404, headers: { 'cache-control': 'private, no-store' } });"}
|
|
93
|
+
},
|
|
94
|
+
};
|
|
95
|
+
`);
|
|
96
|
+
if (!api)
|
|
97
|
+
return;
|
|
98
|
+
put(root, `${directory}/lib/api-client.ts`, `import { Platform } from 'react-native';
|
|
99
|
+
import { createApiClient } from '@workspace/contracts';
|
|
100
|
+
|
|
101
|
+
type Options = NonNullable<Parameters<typeof createApiClient>[1]>;
|
|
102
|
+
|
|
103
|
+
function validProtocol(url: URL): boolean {
|
|
104
|
+
return url.protocol === 'https:' || (__DEV__ && url.protocol === 'http:');
|
|
105
|
+
}
|
|
106
|
+
export function nativeApiOrigin(): string {
|
|
107
|
+
const configured = process.env.EXPO_PUBLIC_API_URL;
|
|
108
|
+
if (!configured) throw new Error('Configure EXPO_PUBLIC_API_URL with the product origin reachable from this device.');
|
|
109
|
+
const origin = new URL(configured);
|
|
110
|
+
if (!validProtocol(origin)) throw new Error('EXPO_PUBLIC_API_URL requires HTTPS outside development.');
|
|
111
|
+
if ([origin.username, origin.password, origin.pathname !== '/', origin.search, origin.hash].some(Boolean))
|
|
112
|
+
throw new Error('EXPO_PUBLIC_API_URL must be an origin without credentials, path, query or fragment.');
|
|
113
|
+
return origin.origin;
|
|
114
|
+
}
|
|
115
|
+
function apiBaseURL(): string {
|
|
116
|
+
if (Platform.OS === 'web') return '/api';
|
|
117
|
+
return nativeApiOrigin() + '/api';
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// A native auth adapter can provide its own session headers. No server secret belongs here.
|
|
121
|
+
export function createApplicationApiClient(options: Options = {}) {
|
|
122
|
+
const client = () => createApiClient(apiBaseURL(), {
|
|
123
|
+
...options, credentials: Platform.OS === 'web' ? 'same-origin' : 'omit',
|
|
124
|
+
});
|
|
125
|
+
return {
|
|
126
|
+
health: (init?: RequestInit) => client().health(init),
|
|
127
|
+
session: (init?: RequestInit) => client().session(init),
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export const api = createApplicationApiClient();
|
|
132
|
+
`);
|
|
133
|
+
writeEnvironmentFile(root, `${directory}/.env.example`, { EXPO_PUBLIC_API_URL: '' });
|
|
134
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
1
|
import type { RecipeContext } from '../registry/types.js';
|
|
2
2
|
export declare function scaffoldPrivateFiles({ root, runtimeApp }: RecipeContext): void;
|
|
3
|
-
export declare function
|
|
3
|
+
export declare function scaffoldStripe(context: RecipeContext): void;
|
|
4
|
+
export declare function scaffoldRevenueCat(context: RecipeContext): void;
|
|
@@ -1,7 +1,12 @@
|
|
|
1
1
|
import { put } from './files.js';
|
|
2
|
+
import { scaffoldBilling } from './billing.js';
|
|
2
3
|
export function scaffoldPrivateFiles({ root, runtimeApp }) {
|
|
3
4
|
put(root, `apps/${runtimeApp}/private-files.md`, '# Private files\n\nFILES is a private R2 Worker binding. Authenticate the request and enforce file-level product authorization before calling get/put/delete. No public buckets, R2 keys, generic download endpoints, or client credentials are generated. Use the binding directly in Hono or import env from cloudflare:workers in Vinext; explicit OpenNext uses getCloudflareContext.\n');
|
|
4
5
|
}
|
|
5
|
-
export function
|
|
6
|
-
|
|
6
|
+
export function scaffoldStripe(context) {
|
|
7
|
+
scaffoldBilling(context);
|
|
8
|
+
}
|
|
9
|
+
export function scaffoldRevenueCat(context) {
|
|
10
|
+
scaffoldBilling(context);
|
|
11
|
+
put(context.root, 'packages/billing/revenuecat.md', '# RevenueCat + Stripe\n\nConfigure web/App Store/Play Store products and offerings in client-owned accounts. Add the platform SDK to each selected app. Verify signed provider webhooks, reconcile entitlement authority, and keep transactional idempotent credits/quotas separate from subscription status. No payment activation occurs during init.\n');
|
|
7
12
|
}
|
package/dist/scaffold/void.js
CHANGED
|
@@ -20,14 +20,15 @@ function pinVoidCloudflareAdapter(root) {
|
|
|
20
20
|
}
|
|
21
21
|
/** Fresh-workspace conversion only. Existing applications keep their delivery engine. */
|
|
22
22
|
export function configureVoidDelivery(root) {
|
|
23
|
-
if (existsSync(path.join(root, 'apps/web/open-next.config.ts'))
|
|
23
|
+
if (existsSync(path.join(root, 'apps/web/open-next.config.ts')) ||
|
|
24
|
+
existsSync(path.join(root, 'apps/mobile/worker/index.ts')))
|
|
24
25
|
return false;
|
|
25
26
|
for (const app of readdirSync(path.join(root, 'apps'))) {
|
|
26
27
|
const file = path.join(root, 'apps', app, 'wrangler.jsonc');
|
|
27
28
|
if (!existsSync(file))
|
|
28
29
|
continue;
|
|
29
30
|
const config = readJson(root, `apps/${app}/wrangler.jsonc`);
|
|
30
|
-
if (config.queues || config.pipelines)
|
|
31
|
+
if (config.queues || config.pipelines || config.images || config.analytics_engine_datasets)
|
|
31
32
|
return false;
|
|
32
33
|
}
|
|
33
34
|
let configured = false;
|
|
@@ -45,7 +46,9 @@ export function configureVoidDelivery(root) {
|
|
|
45
46
|
}
|
|
46
47
|
json(root, `${directory}/anhedral.cloudflare.json`, cloudflare);
|
|
47
48
|
rmSync(source);
|
|
48
|
-
put(root, `${directory}/void.config.ts`,
|
|
49
|
+
put(root, `${directory}/void.config.ts`, `// Platform tooling requires this per-app declaration; resource bindings remain app-specific.
|
|
50
|
+
// fallow-ignore-file code-duplication
|
|
51
|
+
import { defineConfig } from 'void/config';
|
|
49
52
|
import declared from './anhedral.cloudflare.json';
|
|
50
53
|
|
|
51
54
|
// Unassigned placeholders are not provider identities. Void records real IDs
|
|
@@ -85,7 +88,9 @@ export default defineConfig({
|
|
|
85
88
|
put(root, `${directory}/env.example`, '# Copy env.example to .env in this app directory. Void reads one local file per deployable app.\n# Production server values use void secret; VITE_* values must be supplied by the build environment.\n' +
|
|
86
89
|
[...envKeys].map(([key, value]) => `${key}=${value}`).join('\n') +
|
|
87
90
|
'\n');
|
|
88
|
-
const serverKeys = [...envKeys.keys()].filter((key) => !key.startsWith('NEXT_PUBLIC_') &&
|
|
91
|
+
const serverKeys = [...envKeys.keys()].filter((key) => !key.startsWith('NEXT_PUBLIC_') &&
|
|
92
|
+
!key.startsWith('VITE_') &&
|
|
93
|
+
!key.startsWith('EXPO_PUBLIC_'));
|
|
89
94
|
if (app !== 'web' && serverKeys.length) {
|
|
90
95
|
cloudflare.secrets = { required: serverKeys };
|
|
91
96
|
json(root, `${directory}/anhedral.cloudflare.json`, cloudflare);
|
|
@@ -227,11 +232,14 @@ export function refreshVoidEnvironment(root) {
|
|
|
227
232
|
const keys = [...example.matchAll(/^([A-Z][A-Z0-9_]*)=/gm)].map((match) => match[1]);
|
|
228
233
|
const missing = [...new Set(keys)].filter((key) => !key.startsWith('NEXT_PUBLIC_') &&
|
|
229
234
|
!key.startsWith('VITE_') &&
|
|
235
|
+
!key.startsWith('EXPO_PUBLIC_') &&
|
|
230
236
|
!new RegExp(String.raw `\b${key}\s*:`).test(schema));
|
|
231
237
|
if (app !== 'web' && existsSync(path.join(root, directory, 'anhedral.cloudflare.json'))) {
|
|
232
238
|
const configFile = `${directory}/anhedral.cloudflare.json`;
|
|
233
239
|
const config = readJson(root, configFile);
|
|
234
|
-
const serverKeys = [...new Set(keys)].filter((key) => !key.startsWith('NEXT_PUBLIC_') &&
|
|
240
|
+
const serverKeys = [...new Set(keys)].filter((key) => !key.startsWith('NEXT_PUBLIC_') &&
|
|
241
|
+
!key.startsWith('VITE_') &&
|
|
242
|
+
!key.startsWith('EXPO_PUBLIC_'));
|
|
235
243
|
const secrets = (config.secrets ?? {});
|
|
236
244
|
config.secrets = {
|
|
237
245
|
...secrets,
|
package/dist/scaffold/web.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { scaffoldWebBackend } from './backend.js';
|
|
1
2
|
import { resourceName } from '../render.js';
|
|
2
3
|
import { writeEnvironmentFile } from './environment.js';
|
|
3
4
|
import { STACK_DEPENDENCIES, NEXT_VERCEL_VERSION, NEXT_OPENNEXT_VERSION } from '../dependencies.js';
|
|
@@ -125,4 +126,5 @@ export function scaffoldWeb({ root, options, bindings, runtimeApp, has }) {
|
|
|
125
126
|
rmSync(path.join(root, 'apps/web', file), { force: true });
|
|
126
127
|
json(root, 'apps/web/vercel.json', { framework: 'nextjs' });
|
|
127
128
|
}
|
|
129
|
+
scaffoldWebBackend({ root, options, bindings, runtimeApp, has });
|
|
128
130
|
}
|
|
@@ -73,6 +73,11 @@ function writeTurboConfiguration(root, registry) {
|
|
|
73
73
|
...new Set([
|
|
74
74
|
...(turbo.globalEnv ?? []),
|
|
75
75
|
'VOID_CLOUDFLARE_DEPLOY_BUILD',
|
|
76
|
+
...(registry.items.some(({ name }) => name === 'expo') ? ['EXPO_PUBLIC_API_URL'] : []),
|
|
77
|
+
...(registry.items.some(({ name }) => name === 'next') &&
|
|
78
|
+
registry.items.some(({ name }) => name === 'hono')
|
|
79
|
+
? ['API_URL', 'API_ACCESS_CLIENT_ID', 'API_ACCESS_CLIENT_SECRET']
|
|
80
|
+
: []),
|
|
76
81
|
'npm_execpath',
|
|
77
82
|
...registry.items.flatMap((item) => item.environment),
|
|
78
83
|
]),
|
|
@@ -244,7 +249,7 @@ process.exitCode = result.status ?? 1;
|
|
|
244
249
|
schemaVersion: 1,
|
|
245
250
|
standard: 'anhedral-application-stack',
|
|
246
251
|
products: options.products,
|
|
247
|
-
hosting: has('next') || has('vinext') ? options.hosting : null,
|
|
252
|
+
hosting: has('next') || has('vinext') || has('expo') ? options.hosting : null,
|
|
248
253
|
bootstrap: updating
|
|
249
254
|
? readProjectSection(root, 'standard').bootstrap
|
|
250
255
|
: {
|
package/dist/ship.js
CHANGED
|
@@ -61,7 +61,9 @@ async function executeCloudflareApplication(root, dryRun = false, run = defaultR
|
|
|
61
61
|
const environments = mergeRuntimeTargets(runtimeTargets(root, runtime), application);
|
|
62
62
|
const buildRunner = async (command, args, cwd, env) => {
|
|
63
63
|
const relative = path.relative(root, cwd).split(path.sep).join('/');
|
|
64
|
-
const values = environments[`${relative}/.env`] ??
|
|
64
|
+
const values = environments[`${relative}/.env`] ??
|
|
65
|
+
environments[`${relative}/.dev.vars`] ??
|
|
66
|
+
environments[`${relative}/.env.local`];
|
|
65
67
|
const environment = runtimeEnvironment(env, values);
|
|
66
68
|
if (deployment.project.deliveryEngine === 'void' &&
|
|
67
69
|
command === 'pnpm' &&
|
package/dist/stack-registry.d.ts
CHANGED
|
@@ -20,6 +20,10 @@ declare const PRODUCT_ITEMS: {
|
|
|
20
20
|
queues: ItemDefinition;
|
|
21
21
|
cron: ItemDefinition;
|
|
22
22
|
workflows: ItemDefinition;
|
|
23
|
+
'analytics-engine': ItemDefinition;
|
|
24
|
+
images: ItemDefinition;
|
|
25
|
+
realtimekit: ItemDefinition;
|
|
26
|
+
video: ItemDefinition;
|
|
23
27
|
openai: ItemDefinition;
|
|
24
28
|
'ai-sdk': ItemDefinition;
|
|
25
29
|
'workers-ai': ItemDefinition;
|
|
@@ -32,7 +36,7 @@ declare const PRODUCT_ITEMS: {
|
|
|
32
36
|
styling: ItemDefinition;
|
|
33
37
|
};
|
|
34
38
|
export type StandardProduct = keyof typeof PRODUCT_ITEMS;
|
|
35
|
-
export declare const STANDARD_PRODUCTS: readonly ("next" | "
|
|
39
|
+
export declare const STANDARD_PRODUCTS: readonly ("next" | "electron" | "wxt" | "expo" | "vinext" | "realtime" | "workflows" | "styling" | "hono" | "neon" | "d1" | "neon-realtime" | "local-data" | "clerk" | "better-auth" | "r2" | "kv" | "stream" | "queues" | "cron" | "analytics-engine" | "images" | "realtimekit" | "video" | "openai" | "ai-sdk" | "workers-ai" | "resend" | "stripe" | "revenuecat" | "sentry" | "basin" | "posthog")[];
|
|
36
40
|
declare const DEFINITIONS: {
|
|
37
41
|
vinext: ItemDefinition;
|
|
38
42
|
next: ItemDefinition;
|
|
@@ -53,6 +57,10 @@ declare const DEFINITIONS: {
|
|
|
53
57
|
queues: ItemDefinition;
|
|
54
58
|
cron: ItemDefinition;
|
|
55
59
|
workflows: ItemDefinition;
|
|
60
|
+
'analytics-engine': ItemDefinition;
|
|
61
|
+
images: ItemDefinition;
|
|
62
|
+
realtimekit: ItemDefinition;
|
|
63
|
+
video: ItemDefinition;
|
|
56
64
|
openai: ItemDefinition;
|
|
57
65
|
'ai-sdk': ItemDefinition;
|
|
58
66
|
'workers-ai': ItemDefinition;
|
|
@@ -66,12 +74,13 @@ declare const DEFINITIONS: {
|
|
|
66
74
|
workspace: ItemDefinition;
|
|
67
75
|
typescript: ItemDefinition;
|
|
68
76
|
eslint: ItemDefinition;
|
|
77
|
+
'cloudflare-api': ItemDefinition;
|
|
69
78
|
ui: ItemDefinition;
|
|
70
79
|
};
|
|
71
80
|
export type StackItemId = keyof typeof DEFINITIONS;
|
|
72
81
|
export declare function getStackDefinition(name: string): ItemDefinition;
|
|
73
82
|
export declare function getStackItem(name: string): StackRegistryItem;
|
|
74
|
-
export declare const STACK_ITEMS: Record<"next" | "
|
|
83
|
+
export declare const STACK_ITEMS: Record<"next" | "electron" | "eslint" | "typescript" | "wxt" | "expo" | "vinext" | "realtime" | "workflows" | "ui" | "workspace" | "styling" | "hono" | "neon" | "d1" | "neon-realtime" | "local-data" | "clerk" | "better-auth" | "r2" | "kv" | "stream" | "queues" | "cron" | "analytics-engine" | "images" | "realtimekit" | "cloudflare-api" | "video" | "openai" | "ai-sdk" | "workers-ai" | "resend" | "stripe" | "revenuecat" | "sentry" | "basin" | "posthog", StackRegistryItem>;
|
|
75
84
|
export declare const STACK_REGISTRY: {
|
|
76
85
|
schemaVersion: number;
|
|
77
86
|
name: string;
|