anhedral 0.13.0 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +35 -232
- package/assets/patches/audit-deps.mjs +12 -2
- package/assets/ui/LICENSE.shadcn +21 -0
- package/assets/ui/UPSTREAM.json +33 -0
- package/assets/ui/native/button.tsx +85 -0
- package/assets/ui/native/card.tsx +33 -0
- package/assets/ui/native/dialog.tsx +75 -0
- package/assets/ui/native/input.tsx +27 -0
- package/assets/ui/native/label.tsx +4 -0
- package/assets/ui/native/layout.tsx +26 -0
- package/assets/ui/native/text.tsx +20 -0
- package/assets/ui/native/theme-switcher.tsx +22 -0
- package/assets/ui/theme-storage.ts +25 -0
- package/assets/ui/theme.tsx +66 -0
- package/assets/ui/web/button.tsx +59 -0
- package/assets/ui/web/input.tsx +21 -0
- package/assets/ui/web/label.tsx +19 -0
- package/dist/capabilities.d.ts +5 -5
- package/dist/capabilities.js +3 -21
- package/dist/capability-contract.d.ts +3 -3
- package/dist/capability-contract.js +11 -50
- package/dist/cli-delivery.d.ts +1 -1
- package/dist/cli-delivery.js +5 -65
- package/dist/cli-output.js +3 -3
- package/dist/command-schema.js +35 -86
- package/dist/delivery-evidence.d.ts +1 -1
- package/dist/delivery-evidence.js +7 -36
- package/dist/delivery.d.ts +2 -8
- package/dist/delivery.js +20 -101
- package/dist/dependencies.d.ts +6 -57
- package/dist/dependencies.js +54 -188
- package/dist/index.d.ts +1 -4
- package/dist/index.js +1 -4
- package/dist/inspector-model.d.ts +2 -2
- package/dist/integration-service-readers.d.ts +1 -2
- package/dist/integration-service-readers.js +3 -84
- package/dist/lifecycle-model.d.ts +1 -1
- package/dist/lifecycle-model.js +1 -1
- package/dist/mobile-delivery.d.ts +1 -1
- package/dist/mobile-delivery.js +4 -0
- package/dist/platforms/mobile.js +30 -121
- package/dist/platforms/web.d.ts +3 -0
- package/dist/platforms/web.js +299 -0
- package/dist/project-config.d.ts +1 -1
- package/dist/project-config.js +0 -1
- package/dist/project-inspector.js +5 -36
- package/dist/project-state.d.ts +1 -3
- package/dist/project-state.js +2 -85
- package/dist/provider-auth.js +3 -38
- package/dist/provider-readiness.d.ts +1 -1
- package/dist/provider-readiness.js +5 -24
- package/dist/providers/adapters.js +0 -175
- package/dist/providers/api.d.ts +1 -1
- package/dist/providers/api.js +3 -3
- package/dist/providers/config.js +2 -48
- package/dist/providers/definitions.d.ts +1 -204
- package/dist/providers/definitions.js +0 -85
- package/dist/providers/provision.d.ts +1 -1
- package/dist/providers/receipts.js +1 -11
- package/dist/providers/recovery-verification.js +1 -61
- package/dist/providers/runtime.js +4 -35
- package/dist/providers/state.js +1 -7
- package/dist/provision.d.ts +5 -13
- package/dist/provision.js +4 -80
- package/dist/readiness.d.ts +1 -1
- package/dist/readiness.js +3 -8
- package/dist/registry/add.js +10 -70
- package/dist/registry/bootstrap.d.ts +3 -2
- package/dist/registry/bootstrap.js +4 -13
- package/dist/registry/commands.js +8 -10
- package/dist/registry/context.js +0 -1
- package/dist/registry/options.js +8 -38
- package/dist/registry/resolve.d.ts +3 -4
- package/dist/registry/resolve.js +26 -108
- package/dist/registry/types.d.ts +1 -7
- package/dist/registry/usage.js +2 -2
- package/dist/runtime-policy.d.ts +0 -2
- package/dist/runtime-policy.js +0 -16
- package/dist/scaffold/auth.d.ts +1 -2
- package/dist/scaffold/auth.js +55 -130
- package/dist/scaffold/backend.d.ts +0 -4
- package/dist/scaffold/backend.js +1 -186
- package/dist/scaffold/billing-schema.d.ts +1 -1
- package/dist/scaffold/billing-schema.js +4 -4
- package/dist/scaffold/billing.js +11 -19
- package/dist/scaffold/bootstrap.d.ts +2 -3
- package/dist/scaffold/bootstrap.js +37 -43
- package/dist/scaffold/compose.js +2 -14
- package/dist/scaffold/database.d.ts +1 -1
- package/dist/scaffold/database.js +18 -126
- package/dist/scaffold/documentation.d.ts +0 -1
- package/dist/scaffold/documentation.js +22 -86
- package/dist/scaffold/expo-auth.js +33 -22
- package/dist/scaffold/expo-billing.js +17 -52
- package/dist/scaffold/expo-runtime.d.ts +2 -2
- package/dist/scaffold/expo-runtime.js +6 -97
- package/dist/scaffold/integrations.d.ts +1 -3
- package/dist/scaffold/integrations.js +9 -10
- package/dist/scaffold/managed-email.d.ts +3 -0
- package/dist/scaffold/managed-email.js +47 -0
- package/dist/scaffold/native-ui.d.ts +2 -0
- package/dist/scaffold/native-ui.js +69 -0
- package/dist/scaffold/password-reset.d.ts +1 -0
- package/dist/scaffold/password-reset.js +99 -0
- package/dist/scaffold/private-files.d.ts +2 -0
- package/dist/scaffold/private-files.js +78 -0
- package/dist/scaffold/stack-documentation.d.ts +0 -1
- package/dist/scaffold/stack-documentation.js +3 -49
- package/dist/scaffold/styling.d.ts +1 -1
- package/dist/scaffold/styling.js +20 -28
- package/dist/scaffold/web-billing.d.ts +2 -0
- package/dist/scaffold/web-billing.js +48 -0
- package/dist/scaffold/workspace.js +53 -194
- package/dist/service-deletion.js +1 -1
- package/dist/service-descriptor.js +5 -12
- package/dist/service-model.d.ts +1 -1
- package/dist/service-operations.js +2 -32
- package/dist/service-readers.js +1 -32
- package/dist/services-command.d.ts +1 -1
- package/dist/services-command.js +3 -9
- package/dist/ship.d.ts +3 -316
- package/dist/ship.js +10 -142
- package/dist/stack-registry.d.ts +2 -52
- package/dist/stack-registry.js +55 -403
- package/dist/standard.js +7 -14
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/docs/anhedral-stack.md +23 -122
- package/docs/assets/anhedral-stack-light.png +0 -0
- package/docs/assets/anhedral-stack.png +0 -0
- package/docs/software-factory.md +24 -557
- package/docs/stack-standard.md +47 -294
- package/docs/verification.md +320 -0
- package/package.json +20 -22
- package/dist/neon-service-data.d.ts +0 -8
- package/dist/neon-service-data.js +0 -117
- package/dist/platforms/desktop.d.ts +0 -2
- package/dist/platforms/desktop.js +0 -415
- package/dist/platforms/extension.d.ts +0 -2
- package/dist/platforms/extension.js +0 -328
- package/dist/registry/presets.d.ts +0 -4
- package/dist/registry/presets.js +0 -41
- package/dist/scaffold/cloudflare-services.d.ts +0 -8
- package/dist/scaffold/cloudflare-services.js +0 -198
- package/dist/scaffold/lint.d.ts +0 -4
- package/dist/scaffold/lint.js +0 -56
- package/dist/scaffold/neon-realtime.d.ts +0 -2
- package/dist/scaffold/neon-realtime.js +0 -97
- package/dist/scaffold/services.d.ts +0 -5
- package/dist/scaffold/services.js +0 -108
- package/dist/scaffold/stream.d.ts +0 -2
- package/dist/scaffold/stream.js +0 -114
- package/dist/scaffold/void.d.ts +0 -4
- package/dist/scaffold/void.js +0 -264
- package/dist/scaffold/web.d.ts +0 -2
- package/dist/scaffold/web.js +0 -130
- package/dist/vercel-project.d.ts +0 -101
- package/dist/vercel-project.js +0 -305
- package/dist/vercel.d.ts +0 -67
- package/dist/vercel.js +0 -581
- package/dist/vinext.d.ts +0 -2
- package/dist/vinext.js +0 -86
- package/dist/void-execution.d.ts +0 -10
- package/dist/void-execution.js +0 -94
- package/dist/void-migrations.d.ts +0 -6
- package/dist/void-migrations.js +0 -110
- package/dist/void-state.d.ts +0 -16
- package/dist/void-state.js +0 -65
- package/dist/void.d.ts +0 -3
- package/dist/void.js +0 -5
package/dist/registry/resolve.js
CHANGED
|
@@ -1,128 +1,46 @@
|
|
|
1
1
|
import { dependencyOrder } from '../dependency-order.js';
|
|
2
2
|
import { STANDARD_PRODUCTS, STACK_REGISTRY, getStackDefinition, getStackItem, } from '../stack-registry.js';
|
|
3
3
|
import { createResolutionContext } from './context.js';
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
if (
|
|
16
|
-
|
|
17
|
-
if (!selected.has('neon') && !selected.has('d1'))
|
|
18
|
-
selected.add(selected.has('neon-realtime') ? 'neon' : 'd1');
|
|
19
|
-
}
|
|
20
|
-
function validateProducts(selected, hosting) {
|
|
21
|
-
if (!['cloudflare', 'vercel'].includes(hosting))
|
|
22
|
-
throw new Error('hosting must be cloudflare or vercel.');
|
|
23
|
-
for (const id of selected) {
|
|
24
|
-
if (!STANDARD_PRODUCTS.includes(id))
|
|
25
|
-
throw new Error(`Unknown stack product: ${id}.`);
|
|
26
|
-
const { conflicts = [], requiresAny = [], requiresAll = [] } = getStackDefinition(id).selection;
|
|
27
|
-
const conflict = conflicts.find((other) => selected.has(other));
|
|
28
|
-
if (conflict)
|
|
29
|
-
throw new Error(`Choose one of ${id} / ${conflict}.`);
|
|
30
|
-
if (requiresAny.length && !requiresAny.some((other) => selected.has(other)))
|
|
31
|
-
throw new Error(`${id} requires an explicitly selected ${requiresAny.join(' or ')} capability.`);
|
|
32
|
-
const missing = requiresAll.filter((other) => !selected.has(other));
|
|
33
|
-
if (missing.length)
|
|
34
|
-
throw new Error(`${id} requires ${missing.join(', ')}; select it explicitly.`);
|
|
35
|
-
}
|
|
36
|
-
if (selected.has('vinext') && hosting !== 'cloudflare')
|
|
37
|
-
throw new Error('Vinext requires Cloudflare hosting; select --next for Vercel.');
|
|
38
|
-
}
|
|
39
|
-
/** Apply default selections once. All callers then use the same strict graph resolver. */
|
|
40
|
-
export function resolveStandardProducts(selected, hosting, hostingSpecified, initializing = true) {
|
|
4
|
+
export const CORE_PRODUCTS = [
|
|
5
|
+
'next',
|
|
6
|
+
'expo',
|
|
7
|
+
'hono',
|
|
8
|
+
'd1',
|
|
9
|
+
'r2',
|
|
10
|
+
'better-auth',
|
|
11
|
+
'styling',
|
|
12
|
+
];
|
|
13
|
+
/** Every initialization uses one foundation; only payment additions are optional. */
|
|
14
|
+
export function resolveStandardProducts(selected, hosting) {
|
|
15
|
+
if (hosting !== 'cloudflare')
|
|
16
|
+
throw new Error('Anhedral applications use Cloudflare Workers.');
|
|
41
17
|
for (const id of selected)
|
|
42
18
|
getStackDefinition(id);
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
selected.add(hosting === 'vercel' ? 'next' : 'expo');
|
|
46
|
-
// Resolve to a fixed point: an addition may introduce another dependency.
|
|
47
|
-
// Readiness/add callers preserve an existing web-owned backend; new profiles
|
|
48
|
-
// use Hono whenever privileged server behavior is selected.
|
|
49
|
-
let changed = true;
|
|
50
|
-
while (changed) {
|
|
51
|
-
const before = selected.size;
|
|
52
|
-
if (selected.has('stripe') || selected.has('revenuecat'))
|
|
53
|
-
resolveBillingProducts(selected);
|
|
54
|
-
const defaults = [...selected].sort((left, right) => (getStackDefinition(left).selection.requiresAny?.length ?? 0) -
|
|
55
|
-
(getStackDefinition(right).selection.requiresAny?.length ?? 0) ||
|
|
56
|
-
left.localeCompare(right));
|
|
57
|
-
for (const id of defaults) {
|
|
58
|
-
const definition = getStackDefinition(id);
|
|
59
|
-
const alternatives = definition.selection.requiresAny ?? [];
|
|
60
|
-
if (definition.fallbackDependency &&
|
|
61
|
-
!alternatives.some((other) => selected.has(other)))
|
|
62
|
-
selected.add(definition.fallbackDependency);
|
|
63
|
-
for (const dependency of definition.selection.requiresAll ?? [])
|
|
64
|
-
selected.add(dependency);
|
|
65
|
-
const serverCapability = Boolean(definition.runtime);
|
|
66
|
-
if (serverCapability &&
|
|
67
|
-
(initializing || !hasServer(createResolutionContext({ products: [...selected], hosting }))))
|
|
68
|
-
selected.add('hono');
|
|
69
|
-
}
|
|
70
|
-
changed = selected.size !== before;
|
|
71
|
-
}
|
|
72
|
-
const context = createResolutionContext({ products: [...selected], hosting });
|
|
73
|
-
if (context.has('next') &&
|
|
74
|
-
hosting === 'vercel' &&
|
|
75
|
-
[...selected].some((id) => needsWorker(id, context)))
|
|
76
|
-
selected.add('hono');
|
|
77
|
-
if (selected.has('expo') && hosting === 'vercel' && !selected.has('next'))
|
|
78
|
-
throw new Error('Expo web uses Cloudflare hosting; select --next for a Vercel web application.');
|
|
79
|
-
if (hostingSpecified && !selected.has('next') && !selected.has('vinext') && !selected.has('expo'))
|
|
80
|
-
throw new Error('--hosting applies to the web application.');
|
|
19
|
+
for (const product of CORE_PRODUCTS)
|
|
20
|
+
selected.add(product);
|
|
81
21
|
resolveStackRegistry({ products: [...selected], hosting });
|
|
82
22
|
}
|
|
83
|
-
function itemDependencies(name, context) {
|
|
84
|
-
const definition = getStackDefinition(name);
|
|
85
|
-
const dependencies = new Set(definition.registryDependencies);
|
|
86
|
-
if (definition.runtime) {
|
|
87
|
-
if (!hasServer(context) && definition.runtime !== 'optional-worker')
|
|
88
|
-
throw new Error(`${name} requires a server runtime.`);
|
|
89
|
-
if (needsWorker(name, context) &&
|
|
90
|
-
!context.has('hono') &&
|
|
91
|
-
!(context.options.hosting === 'cloudflare' && (context.has('vinext') || context.has('next'))))
|
|
92
|
-
throw new Error(`${name} requires a Cloudflare runtime.`);
|
|
93
|
-
if (hasServer(context))
|
|
94
|
-
dependencies.add(context.has('hono') ? 'hono' : context.has('vinext') ? 'vinext' : 'next');
|
|
95
|
-
}
|
|
96
|
-
for (const dependency of definition.resolveDependencies?.(context) ?? [])
|
|
97
|
-
dependencies.add(dependency);
|
|
98
|
-
return dependencies;
|
|
99
|
-
}
|
|
100
23
|
export function resolveStackRegistry(options) {
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
24
|
+
if (options.hosting !== 'cloudflare')
|
|
25
|
+
throw new Error('Anhedral applications use Cloudflare Workers.');
|
|
26
|
+
for (const id of options.products)
|
|
27
|
+
if (!STANDARD_PRODUCTS.includes(id))
|
|
28
|
+
throw new Error(`Unknown stack product: ${id}.`);
|
|
29
|
+
const products = [...new Set([...CORE_PRODUCTS, ...options.products])];
|
|
30
|
+
const context = createResolutionContext({ ...options, products });
|
|
106
31
|
const resolved = new Map();
|
|
107
|
-
|
|
32
|
+
function collect(name) {
|
|
108
33
|
if (resolved.has(name))
|
|
109
34
|
return;
|
|
110
35
|
const definition = getStackDefinition(name);
|
|
111
36
|
const metadata = getStackItem(name);
|
|
112
|
-
const dependencies = itemDependencies(name, context);
|
|
113
|
-
metadata.registryDependencies = [...dependencies];
|
|
114
|
-
metadata.environment = definition.resolveEnvironment?.(context) ?? metadata.environment;
|
|
115
|
-
metadata.targets = definition.resolveTargets?.(context) ?? metadata.targets;
|
|
116
37
|
if (definition.configure)
|
|
117
38
|
metadata.bindings = definition.configure(context);
|
|
118
|
-
if (definition.package)
|
|
119
|
-
metadata.package =
|
|
120
|
-
definition.resolvePackage?.(context, definition.package) ?? definition.package;
|
|
121
39
|
resolved.set(name, metadata);
|
|
122
|
-
for (const dependency of
|
|
40
|
+
for (const dependency of metadata.registryDependencies)
|
|
123
41
|
collect(dependency);
|
|
124
|
-
}
|
|
125
|
-
for (const name of ['workspace', 'typescript', 'eslint', ...
|
|
42
|
+
}
|
|
43
|
+
for (const name of ['workspace', 'typescript', 'eslint', ...products.sort()])
|
|
126
44
|
collect(name);
|
|
127
45
|
const graph = new Map([...resolved].map(([name, item]) => [name, item.registryDependencies]));
|
|
128
46
|
return {
|
package/dist/registry/types.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { StandardProduct } from '../stack-registry.js';
|
|
2
2
|
import type { Json } from '../scaffold/files.js';
|
|
3
3
|
export type { StandardProduct } from '../stack-registry.js';
|
|
4
|
-
export type Hosting = 'cloudflare'
|
|
4
|
+
export type Hosting = 'cloudflare';
|
|
5
5
|
export interface StandardOptions {
|
|
6
6
|
root: string;
|
|
7
7
|
name: string;
|
|
@@ -30,7 +30,6 @@ export interface RecipeContext {
|
|
|
30
30
|
updating?: boolean;
|
|
31
31
|
root: string;
|
|
32
32
|
options: StandardOptions;
|
|
33
|
-
runtimeApp: 'api' | 'web';
|
|
34
33
|
bindings: Json;
|
|
35
34
|
has: (product: string) => boolean;
|
|
36
35
|
}
|
|
@@ -58,9 +57,4 @@ export interface StackRegistryItem {
|
|
|
58
57
|
export interface ItemDefinition extends Omit<StackRegistryItem, 'bindings'> {
|
|
59
58
|
install?: Recipe;
|
|
60
59
|
configure?: (context: RecipeContext) => Json;
|
|
61
|
-
resolveEnvironment?: (context: RecipeContext) => string[];
|
|
62
|
-
resolveTargets?: (context: RecipeContext) => string[];
|
|
63
|
-
resolvePackage?: (context: RecipeContext, recipe: PackageRecipe) => PackageRecipe;
|
|
64
|
-
resolveDependencies?: (context: RecipeContext) => string[];
|
|
65
|
-
fallbackDependency?: string;
|
|
66
60
|
}
|
package/dist/registry/usage.js
CHANGED
|
@@ -12,7 +12,7 @@ export function commandHelp(command) {
|
|
|
12
12
|
return undefined;
|
|
13
13
|
return `${entry.description}\n\nUsage: anhedral ${entry.usage}\n\nOptions:\n${[...entry.options, ...common].map((option) => ` ${option}`).join('\n')}\n\nExamples:\n${entry.examples.map((example) => ` anhedral ${example}`).join('\n')}${entry.note ? `\n\n${entry.note}` : ''}\n`;
|
|
14
14
|
}
|
|
15
|
-
export const STANDARD_USAGE = `Anhedral\
|
|
15
|
+
export const STANDARD_USAGE = `Anhedral\nCreate and ship applications with one consistent core stack.\n\nUsage: anhedral <command> [options]\n\nStart here:\n${primary.map((name) => ` ${name.padEnd(12)}${COMMAND_HELP[name].description}`).join('\n')}\n\nDelivery tools:\n${Object.entries(COMMAND_HELP)
|
|
16
16
|
.filter(([name]) => !primary.includes(name))
|
|
17
17
|
.map(([name, entry]) => ` ${name.padEnd(12)}${entry.description}`)
|
|
18
|
-
.join('\n')}\n\nDefault:
|
|
18
|
+
.join('\n')}\n\nDefault: Next.js web + native Expo + Hono + Drizzle/D1 + private R2, with Better Auth and shared styling. Stripe and RevenueCat are the only optional additions.\nExamples:\n anhedral init client-app\n anhedral init client-app --stripe --revenuecat\n anhedral auth client-app\n anhedral ship client-app --dry-run\n\nUse anhedral <command> --help for options and examples.\nUse anhedral help <command> for the same focused help.\nGlobal options:\n${common.map((option) => ` ${option}`).join('\n')}\n -v, --version Show the CLI version.\n`;
|
package/dist/runtime-policy.d.ts
CHANGED
|
@@ -1,4 +1,2 @@
|
|
|
1
1
|
/** Runtime policy shared by generation, setup guidance, and diagnostics. */
|
|
2
2
|
export declare function supportsWorkspaceRuntime(version: string): boolean;
|
|
3
|
-
export declare function supportsVoidRuntime(version: string): boolean;
|
|
4
|
-
export declare function usesVoidSelection(products: readonly string[], hosting: string): boolean;
|
package/dist/runtime-policy.js
CHANGED
|
@@ -6,19 +6,3 @@ export function supportsWorkspaceRuntime(version) {
|
|
|
6
6
|
const [major, minor] = match.slice(1).map(Number);
|
|
7
7
|
return (major === 22 && minor >= 13) || major >= 24;
|
|
8
8
|
}
|
|
9
|
-
export function supportsVoidRuntime(version) {
|
|
10
|
-
const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(version);
|
|
11
|
-
if (!match)
|
|
12
|
-
return false;
|
|
13
|
-
const [major, minor] = match.slice(1).map(Number);
|
|
14
|
-
return major > 24 || (major === 24 && minor >= 21);
|
|
15
|
-
}
|
|
16
|
-
export function usesVoidSelection(products, hosting) {
|
|
17
|
-
return (!products.includes('expo') &&
|
|
18
|
-
!(products.includes('next') && hosting === 'cloudflare') &&
|
|
19
|
-
!products.includes('queues') &&
|
|
20
|
-
!products.includes('basin') &&
|
|
21
|
-
!products.includes('images') &&
|
|
22
|
-
!products.includes('analytics-engine') &&
|
|
23
|
-
products.some((product) => ['vinext', 'hono', 'realtime', 'cron', 'workflows'].includes(product)));
|
|
24
|
-
}
|
package/dist/scaffold/auth.d.ts
CHANGED
|
@@ -1,3 +1,2 @@
|
|
|
1
1
|
import type { RecipeContext } from '../registry/types.js';
|
|
2
|
-
export declare function scaffoldBetterAuth({ root,
|
|
3
|
-
export declare function scaffoldClerk({ root, has }: RecipeContext): void;
|
|
2
|
+
export declare function scaffoldBetterAuth({ root, updating }: RecipeContext): void;
|
package/dist/scaffold/auth.js
CHANGED
|
@@ -1,151 +1,76 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { scaffoldPasswordReset } from './password-reset.js';
|
|
2
|
+
import { scaffoldManagedEmail } from './managed-email.js';
|
|
2
3
|
import { expoAuthScheme, scaffoldExpoAuth } from './expo-auth.js';
|
|
3
4
|
import { jsString } from '../render.js';
|
|
4
5
|
import { writeEnvironmentFile } from './environment.js';
|
|
5
6
|
import { STACK_DEPENDENCIES } from '../dependencies.js';
|
|
6
|
-
import {
|
|
7
|
+
import { readFileSync } from 'node:fs';
|
|
7
8
|
import path from 'node:path';
|
|
8
9
|
import { writeBetterAuthSchema } from '../auth-schema.js';
|
|
9
10
|
import { put, patchPackage, sharedPackage } from './files.js';
|
|
10
|
-
export function scaffoldBetterAuth({ root,
|
|
11
|
-
const scheme =
|
|
12
|
-
|
|
13
|
-
|
|
11
|
+
export function scaffoldBetterAuth({ root, updating }) {
|
|
12
|
+
const scheme = expoAuthScheme(root);
|
|
13
|
+
scaffoldManagedEmail(root);
|
|
14
|
+
writeBetterAuthSchema(root, false);
|
|
15
|
+
sharedPackage(root, 'auth', `import { createManagedEmail, type EmailEnvironment } from '@workspace/managed-email';
|
|
16
|
+
import { expo } from '@better-auth/expo';
|
|
17
|
+
import { betterAuth } from 'better-auth';
|
|
14
18
|
import { drizzleAdapter } from '@better-auth/drizzle-adapter';
|
|
15
19
|
import type { createDatabase } from '@workspace/db';
|
|
16
|
-
export function createAuth(db: ReturnType<typeof createDatabase>, secret: string, baseURL: string,
|
|
20
|
+
export function createAuth(db: ReturnType<typeof createDatabase>, secret: string, baseURL: string, email: EmailEnvironment = {}) {
|
|
21
|
+
const sendEmail = createManagedEmail(email);
|
|
17
22
|
return betterAuth({
|
|
18
|
-
database: drizzleAdapter(db, { provider: '
|
|
19
|
-
secret,
|
|
20
|
-
baseURL,
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
23
|
+
database: drizzleAdapter(db, { provider: 'sqlite', transaction: false }),
|
|
24
|
+
secret, baseURL,
|
|
25
|
+
trustedOrigins: [new URL(baseURL).origin, ${jsString(scheme + '://')}],
|
|
26
|
+
plugins: [expo()],
|
|
27
|
+
emailAndPassword: {
|
|
28
|
+
enabled: true,
|
|
29
|
+
requireEmailVerification: Boolean(sendEmail),
|
|
30
|
+
revokeSessionsOnPasswordReset: true,
|
|
31
|
+
sendResetPassword: sendEmail ? async ({ user, url }) => { await sendEmail('reset-password', user.email, url); } : undefined,
|
|
32
|
+
},
|
|
33
|
+
emailVerification: sendEmail ? {
|
|
34
|
+
sendOnSignUp: true,
|
|
35
|
+
sendVerificationEmail: async ({ user, url }) => { await sendEmail('verify-email', user.email, url); },
|
|
36
|
+
} : undefined,
|
|
24
37
|
});
|
|
25
38
|
}
|
|
26
39
|
`, {
|
|
27
40
|
'better-auth': STACK_DEPENDENCIES['better-auth'],
|
|
28
|
-
|
|
41
|
+
'@better-auth/expo': STACK_DEPENDENCIES['@better-auth/expo'],
|
|
29
42
|
'@better-auth/drizzle-adapter': STACK_DEPENDENCIES['@better-auth/drizzle-adapter'],
|
|
30
43
|
'@workspace/db': 'workspace:*',
|
|
44
|
+
'@workspace/managed-email': 'workspace:*',
|
|
31
45
|
});
|
|
32
|
-
patchPackage(root,
|
|
33
|
-
dependencies: {
|
|
46
|
+
patchPackage(root, 'apps/api/package.json', {
|
|
47
|
+
dependencies: {
|
|
48
|
+
'@workspace/auth': 'workspace:*',
|
|
49
|
+
'@workspace/managed-email': 'workspace:*',
|
|
50
|
+
'@workspace/db': 'workspace:*',
|
|
51
|
+
'@workspace/contracts': 'workspace:*',
|
|
52
|
+
},
|
|
34
53
|
});
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
import { createDatabase } from '@workspace/db';
|
|
50
|
-
async function handler(request: Request) {
|
|
51
|
-
${options.hosting === 'cloudflare' && !has('vinext') ? 'const { env } = await getCloudflareContext({ async: true });' : ''}
|
|
52
|
-
const database = ${options.hosting === 'vercel' ? 'createDatabase(process.env.DATABASE_URL!)' : connection};
|
|
53
|
-
return await createAuth(database, ${options.hosting === 'cloudflare' ? 'env.BETTER_AUTH_SECRET, env.BETTER_AUTH_URL' : 'process.env.BETTER_AUTH_SECRET!, process.env.BETTER_AUTH_URL!'}).handler(request);
|
|
54
|
-
}
|
|
55
|
-
export { handler as GET, handler as POST };
|
|
56
|
-
`);
|
|
57
|
-
if (options.hosting === 'cloudflare' && !has('vinext'))
|
|
58
|
-
put(root, 'apps/web/cloudflare-env.d.ts', `interface CloudflareEnv { BETTER_AUTH_SECRET: string; BETTER_AUTH_URL: string; ${has('neon') ? 'DATABASE_URL: string;' : "DB: Parameters<typeof import('drizzle-orm/d1').drizzle>[0];"} }\n`);
|
|
59
|
-
if (has('vinext')) {
|
|
60
|
-
put(root, 'apps/web/secrets.d.ts', 'declare namespace Cloudflare { interface Env { BETTER_AUTH_SECRET: string; BETTER_AUTH_URL: string } }\n');
|
|
61
|
-
}
|
|
62
|
-
patchPackage(root, 'apps/web/package.json', {
|
|
63
|
-
dependencies: { 'drizzle-orm': STACK_DEPENDENCIES['drizzle-orm'] },
|
|
64
|
-
});
|
|
65
|
-
}
|
|
66
|
-
writeEnvironmentFile(root, `apps/${runtimeApp}/${runtimeApp === 'web' && options.hosting === 'vercel' ? '.env.example' : '.dev.vars.example'}`, {
|
|
67
|
-
...(has('neon') ? { DATABASE_URL: '' } : {}),
|
|
54
|
+
let source = readFileSync(path.join(root, 'apps/api/src/index.ts'), 'utf8');
|
|
55
|
+
source =
|
|
56
|
+
"import { createAuth } from '@workspace/auth';\nimport { sessionSchema } from '@workspace/contracts';\n" +
|
|
57
|
+
source;
|
|
58
|
+
source = source.replace('export default app;', `app.get('/api/session', async (c) => {
|
|
59
|
+
c.header('cache-control', 'private, no-store');
|
|
60
|
+
const session = await createAuth(createDatabase(c.env.DB), c.env.BETTER_AUTH_SECRET, c.env.BETTER_AUTH_URL, c.env).api.getSession({ headers: c.req.raw.headers });
|
|
61
|
+
if (!session) return c.json({ error: 'Unauthorized' }, 401);
|
|
62
|
+
return c.json(sessionSchema.parse({ user: session.user }));
|
|
63
|
+
});
|
|
64
|
+
app.on(['GET', 'POST'], '/api/auth/*', (c) => createAuth(createDatabase(c.env.DB), c.env.BETTER_AUTH_SECRET, c.env.BETTER_AUTH_URL, c.env).handler(c.req.raw));
|
|
65
|
+
export default app;`);
|
|
66
|
+
put(root, 'apps/api/src/index.ts', source);
|
|
67
|
+
writeEnvironmentFile(root, 'apps/api/.dev.vars.example', {
|
|
68
68
|
BETTER_AUTH_SECRET: '',
|
|
69
|
-
BETTER_AUTH_URL:
|
|
69
|
+
BETTER_AUTH_URL: 'http://localhost:3000',
|
|
70
|
+
ANHEDRAL_EMAIL_SCOPE: '',
|
|
71
|
+
ANHEDRAL_EMAIL_CAPABILITY: '',
|
|
70
72
|
});
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
scaffoldExpoAuth(root, scheme, !updating);
|
|
75
|
-
if (has('hono'))
|
|
76
|
-
put(root, 'apps/api/src/secrets.d.ts', 'interface Env { BETTER_AUTH_SECRET: string; BETTER_AUTH_URL: string }\n');
|
|
77
|
-
}
|
|
78
|
-
export function scaffoldClerk({ root, has }) {
|
|
79
|
-
if (has('next') || has('vinext')) {
|
|
80
|
-
patchPackage(root, 'apps/web/package.json', {
|
|
81
|
-
dependencies: { '@clerk/nextjs': STACK_DEPENDENCIES['@clerk/nextjs'] },
|
|
82
|
-
});
|
|
83
|
-
const layoutPath = path.join(root, 'apps/web/app/layout.tsx');
|
|
84
|
-
if (existsSync(layoutPath)) {
|
|
85
|
-
const layout = readFileSync(layoutPath, 'utf8');
|
|
86
|
-
if (!layout.includes('ClerkProvider')) {
|
|
87
|
-
const wrapped = layout.replace(/(<body\b[^>]*>)([\s\S]*?)(<\/body>)/, '$1<ClerkProvider>$2</ClerkProvider>$3');
|
|
88
|
-
if (wrapped === layout)
|
|
89
|
-
throw new Error('Cannot configure ClerkProvider: the web layout must contain a body element.');
|
|
90
|
-
put(root, 'apps/web/app/layout.tsx', 'import { ClerkProvider } from "@clerk/nextjs";\n' + wrapped);
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
put(root, 'apps/web/app/sign-in/[[...sign-in]]/page.tsx', `import { Suspense } from 'react';
|
|
94
|
-
import { SignIn } from '@clerk/nextjs';
|
|
95
|
-
|
|
96
|
-
export default function SignInPage() {
|
|
97
|
-
return (
|
|
98
|
-
<Suspense fallback={<p role="status">Loading sign in…</p>}>
|
|
99
|
-
<SignIn />
|
|
100
|
-
</Suspense>
|
|
101
|
-
);
|
|
102
|
-
}
|
|
103
|
-
`);
|
|
104
|
-
put(root, 'apps/web/app/sign-up/[[...sign-up]]/page.tsx', `import { Suspense } from 'react';
|
|
105
|
-
import { SignUp } from '@clerk/nextjs';
|
|
106
|
-
|
|
107
|
-
export default function SignUpPage() {
|
|
108
|
-
return (
|
|
109
|
-
<Suspense fallback={<p role="status">Loading sign up…</p>}>
|
|
110
|
-
<SignUp />
|
|
111
|
-
</Suspense>
|
|
112
|
-
);
|
|
113
|
-
}
|
|
114
|
-
`);
|
|
115
|
-
put(root, 'apps/web/proxy.ts', `import { clerkMiddleware } from '@clerk/nextjs/server';
|
|
116
|
-
import type { NextMiddleware } from 'next/server';
|
|
117
|
-
|
|
118
|
-
const proxy: NextMiddleware = clerkMiddleware();
|
|
119
|
-
export default proxy;
|
|
120
|
-
export const config = { matcher: ['/((?!_next|[^?]*\\\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico)).*)', '/(api|trpc)(.*)'] };
|
|
121
|
-
`);
|
|
122
|
-
// Middleware makes auth available; product routes must explicitly require identity and authorization.
|
|
123
|
-
}
|
|
124
|
-
if (has('hono')) {
|
|
125
|
-
sharedPackage(root, 'auth', `import { createClerkClient } from '@clerk/backend';
|
|
126
|
-
|
|
127
|
-
export async function authenticate(
|
|
128
|
-
request: Request,
|
|
129
|
-
secretKey: string,
|
|
130
|
-
publishableKey: string,
|
|
131
|
-
authorizedParties: string[],
|
|
132
|
-
) {
|
|
133
|
-
if (!secretKey || !publishableKey || authorizedParties.length === 0) {
|
|
134
|
-
throw new Error('Configure Clerk keys and explicit authorized origins before authenticating.');
|
|
135
|
-
}
|
|
136
|
-
return createClerkClient({ secretKey, publishableKey }).authenticateRequest(request, {
|
|
137
|
-
authorizedParties,
|
|
138
|
-
});
|
|
139
|
-
}
|
|
140
|
-
`, { '@clerk/backend': STACK_DEPENDENCIES['@clerk/backend'] });
|
|
141
|
-
writeEnvironmentFile(root, 'apps/api/.dev.vars.example', {
|
|
142
|
-
CLERK_SECRET_KEY: '',
|
|
143
|
-
CLERK_PUBLISHABLE_KEY: '',
|
|
144
|
-
});
|
|
145
|
-
}
|
|
146
|
-
if (has('next') || has('vinext'))
|
|
147
|
-
writeEnvironmentFile(root, 'apps/web/.env.example', {
|
|
148
|
-
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY: '',
|
|
149
|
-
CLERK_SECRET_KEY: '',
|
|
150
|
-
});
|
|
73
|
+
scaffoldExpoAuth(root, scheme, !updating);
|
|
74
|
+
scaffoldPasswordReset(root);
|
|
75
|
+
put(root, 'apps/api/src/secrets.d.ts', 'import type { EmailEnvironment } from "@workspace/managed-email";\ndeclare global { interface Env extends EmailEnvironment { BETTER_AUTH_SECRET: string; BETTER_AUTH_URL: string } }\n');
|
|
151
76
|
}
|
|
@@ -1,6 +1,2 @@
|
|
|
1
|
-
import type { RecipeContext } from '../registry/types.js';
|
|
2
1
|
/** Public contracts never import a framework, database or auth server. */
|
|
3
2
|
export declare function scaffoldContracts(root: string): void;
|
|
4
|
-
/** A single trusted upstream; never forward provider/edge identity headers from browsers. */
|
|
5
|
-
export declare function scaffoldWebBackend({ root, options, has }: RecipeContext): void;
|
|
6
|
-
export declare function scaffoldWebAuth(root: string): void;
|
package/dist/scaffold/backend.js
CHANGED
|
@@ -1,9 +1,5 @@
|
|
|
1
|
-
import { existsSync } from 'node:fs';
|
|
2
|
-
import path from 'node:path';
|
|
3
|
-
import { resourceName } from '../render.js';
|
|
4
1
|
import { STACK_DEPENDENCIES } from '../dependencies.js';
|
|
5
|
-
import {
|
|
6
|
-
import { writeEnvironmentFile } from './environment.js';
|
|
2
|
+
import { put, sharedPackage } from './files.js';
|
|
7
3
|
/** Public contracts never import a framework, database or auth server. */
|
|
8
4
|
export function scaffoldContracts(root) {
|
|
9
5
|
sharedPackage(root, 'contracts', `import { z } from 'zod';
|
|
@@ -41,184 +37,3 @@ export function createHttpClient(baseURL: string, options: HttpOptions = {}) {
|
|
|
41
37
|
}
|
|
42
38
|
`);
|
|
43
39
|
}
|
|
44
|
-
/** A single trusted upstream; never forward provider/edge identity headers from browsers. */
|
|
45
|
-
export function scaffoldWebBackend({ root, options, has }) {
|
|
46
|
-
if (!has('hono'))
|
|
47
|
-
return;
|
|
48
|
-
if (has('better-auth')) {
|
|
49
|
-
patchPackage(root, 'apps/web/package.json', {
|
|
50
|
-
dependencies: { '@workspace/contracts': 'workspace:*' },
|
|
51
|
-
});
|
|
52
|
-
put(root, 'apps/web/lib/api-client.ts', `import { createApiClient } from '@workspace/contracts';
|
|
53
|
-
export const api = createApiClient();
|
|
54
|
-
`);
|
|
55
|
-
}
|
|
56
|
-
put(root, 'apps/web/lib/api-proxy.ts', `type Transport = (request: Request) => Promise<Response>;
|
|
57
|
-
const forwardedHeaders = ['accept', 'content-type', 'cookie', 'origin', 'authorization', 'expo-origin', 'sec-fetch-site', 'idempotency-key'];
|
|
58
|
-
const removedHeaders = ['connection', 'transfer-encoding', 'access-control-allow-origin', 'access-control-allow-credentials'];
|
|
59
|
-
function isLocal(url: URL) {
|
|
60
|
-
return url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
|
|
61
|
-
}
|
|
62
|
-
function trustedOrigin(origin: string) {
|
|
63
|
-
const url = new URL(origin);
|
|
64
|
-
if (url.protocol !== 'https:' && !isLocal(url)) throw new Error('Configure a trusted HTTPS API origin (HTTP is local-only).');
|
|
65
|
-
if ([url.username, url.password, url.pathname.replace('/', ''), url.search, url.hash].some(Boolean)) {
|
|
66
|
-
throw new Error('Configure a trusted HTTPS API origin without credentials or a path.');
|
|
67
|
-
}
|
|
68
|
-
return url;
|
|
69
|
-
}
|
|
70
|
-
function requestHeaders(request: Request) {
|
|
71
|
-
const headers = new Headers();
|
|
72
|
-
for (const name of forwardedHeaders) {
|
|
73
|
-
const value = request.headers.get(name);
|
|
74
|
-
if (value) headers.set(name, value);
|
|
75
|
-
}
|
|
76
|
-
return headers;
|
|
77
|
-
}
|
|
78
|
-
function privateResponse(response: Response) {
|
|
79
|
-
const headers = new Headers(response.headers);
|
|
80
|
-
for (const name of removedHeaders) headers.delete(name);
|
|
81
|
-
headers.set('cache-control', 'private, no-store');
|
|
82
|
-
return new Response(response.body, { status: response.status, headers });
|
|
83
|
-
}
|
|
84
|
-
export function createApiProxy(send: Transport, origin: string) {
|
|
85
|
-
const upstream = trustedOrigin(origin);
|
|
86
|
-
return async function proxy(request: Request): Promise<Response> {
|
|
87
|
-
const path = new URL(request.url);
|
|
88
|
-
if (!path.pathname.startsWith('/api/')) return new Response(null, { status: 404 });
|
|
89
|
-
const target = new URL(upstream);
|
|
90
|
-
target.pathname = path.pathname;
|
|
91
|
-
target.search = path.search;
|
|
92
|
-
try {
|
|
93
|
-
const forwarded = new Request(new Request(target, request), {
|
|
94
|
-
headers: requestHeaders(request), redirect: 'manual',
|
|
95
|
-
signal: AbortSignal.any([request.signal, AbortSignal.timeout(15000)]),
|
|
96
|
-
});
|
|
97
|
-
return privateResponse(await send(forwarded));
|
|
98
|
-
} catch {
|
|
99
|
-
return Response.json({ error: 'API unavailable' }, { status: 503, headers: { 'cache-control': 'private, no-store' } });
|
|
100
|
-
}
|
|
101
|
-
};
|
|
102
|
-
}
|
|
103
|
-
`);
|
|
104
|
-
const cloudflare = options.hosting === 'cloudflare';
|
|
105
|
-
const binding = has('vinext')
|
|
106
|
-
? "import { env } from 'cloudflare:workers';"
|
|
107
|
-
: "import { getCloudflareContext } from '@opennextjs/cloudflare';";
|
|
108
|
-
const transport = cloudflare
|
|
109
|
-
? `${binding}
|
|
110
|
-
import { createApiProxy } from '@/lib/api-proxy';
|
|
111
|
-
async function handler(request: Request) {
|
|
112
|
-
const bindings = ${has('vinext') ? 'env' : '(await getCloudflareContext({ async: true })).env'} as unknown as { API: { fetch(request: Request): Promise<Response> } };
|
|
113
|
-
return createApiProxy((upstream) => bindings.API.fetch(upstream), 'https://localhost')(request);
|
|
114
|
-
}`
|
|
115
|
-
: `import { apiTransport } from '@/lib/api-transport';
|
|
116
|
-
import { createApiProxy } from '@/lib/api-proxy';
|
|
117
|
-
async function handler(request: Request) {
|
|
118
|
-
const origin = process.env.API_URL;
|
|
119
|
-
if (!origin) return Response.json({ error: 'Configure API_URL' }, { status: 503 });
|
|
120
|
-
return createApiProxy(apiTransport, origin)(request);
|
|
121
|
-
}`;
|
|
122
|
-
put(root, 'apps/web/app/api/[...path]/route.ts', `${transport}
|
|
123
|
-
export { handler as GET, handler as POST, handler as PUT, handler as PATCH, handler as DELETE, handler as OPTIONS, handler as HEAD };
|
|
124
|
-
`);
|
|
125
|
-
if (cloudflare) {
|
|
126
|
-
const configFile = existsSync(path.join(root, 'apps/web/wrangler.jsonc'))
|
|
127
|
-
? 'apps/web/wrangler.jsonc'
|
|
128
|
-
: 'apps/web/anhedral.cloudflare.json';
|
|
129
|
-
const config = readJson(root, configFile);
|
|
130
|
-
const services = (config.services ?? []);
|
|
131
|
-
json(root, configFile, {
|
|
132
|
-
...config,
|
|
133
|
-
services: [
|
|
134
|
-
...services.filter((service) => service.binding !== 'API'),
|
|
135
|
-
{ binding: 'API', service: resourceName(options.name, 'api') },
|
|
136
|
-
],
|
|
137
|
-
});
|
|
138
|
-
}
|
|
139
|
-
else {
|
|
140
|
-
put(root, 'apps/web/lib/api-transport.ts', `// Service credentials are server-only; never forward browser-supplied Access identity.
|
|
141
|
-
export function apiTransport(request: Request) {
|
|
142
|
-
const id = process.env.API_ACCESS_CLIENT_ID;
|
|
143
|
-
const secret = process.env.API_ACCESS_CLIENT_SECRET;
|
|
144
|
-
if (Boolean(id) !== Boolean(secret)) throw new Error('Configure both API Access credentials.');
|
|
145
|
-
const headers = new Headers(request.headers);
|
|
146
|
-
if (id && secret) {
|
|
147
|
-
headers.set('CF-Access-Client-Id', id);
|
|
148
|
-
headers.set('CF-Access-Client-Secret', secret);
|
|
149
|
-
}
|
|
150
|
-
return fetch(request, { headers, redirect: 'manual' });
|
|
151
|
-
}
|
|
152
|
-
`);
|
|
153
|
-
writeEnvironmentFile(root, 'apps/web/.env.example', {
|
|
154
|
-
API_URL: 'http://127.0.0.1:8787',
|
|
155
|
-
API_ACCESS_CLIENT_ID: '',
|
|
156
|
-
API_ACCESS_CLIENT_SECRET: '',
|
|
157
|
-
});
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
export function scaffoldWebAuth(root) {
|
|
161
|
-
patchPackage(root, 'apps/web/package.json', {
|
|
162
|
-
dependencies: { 'better-auth': STACK_DEPENDENCIES['better-auth'] },
|
|
163
|
-
});
|
|
164
|
-
put(root, 'apps/web/lib/auth-client.ts', `import { createAuthClient } from 'better-auth/react';
|
|
165
|
-
export const authClient = createAuthClient();
|
|
166
|
-
`);
|
|
167
|
-
put(root, 'apps/web/app/sign-in/page.tsx', `'use client';
|
|
168
|
-
|
|
169
|
-
import { useState } from 'react';
|
|
170
|
-
import { Button } from '@workspace/ui/components/button';
|
|
171
|
-
import { api } from '@/lib/api-client';
|
|
172
|
-
import { authClient } from '@/lib/auth-client';
|
|
173
|
-
|
|
174
|
-
const modes = {
|
|
175
|
-
signIn: { title: 'Sign in', password: 'current-password', name: false, next: 'signUp', toggle: 'Create an account' },
|
|
176
|
-
signUp: { title: 'Create account', password: 'new-password', name: true, next: 'signIn', toggle: 'Use an existing account' },
|
|
177
|
-
} as const;
|
|
178
|
-
type Mode = keyof typeof modes;
|
|
179
|
-
function authenticate(mode: Mode, form: FormData) {
|
|
180
|
-
const credentials = { email: String(form.get('email')), password: String(form.get('password')) };
|
|
181
|
-
if (mode === 'signUp') return authClient.signUp.email({ ...credentials, name: String(form.get('name')) });
|
|
182
|
-
return authClient.signIn.email(credentials);
|
|
183
|
-
}
|
|
184
|
-
function AuthForm({ refresh }: { refresh: () => Promise<unknown> }) {
|
|
185
|
-
const [mode, setMode] = useState<Mode>('signIn');
|
|
186
|
-
const [pending, setPending] = useState(false);
|
|
187
|
-
const [message, setMessage] = useState('');
|
|
188
|
-
const fields = modes[mode];
|
|
189
|
-
async function submit(event: React.SyntheticEvent<HTMLFormElement>) {
|
|
190
|
-
event.preventDefault();
|
|
191
|
-
const form = new FormData(event.currentTarget);
|
|
192
|
-
setPending(true);
|
|
193
|
-
setMessage('');
|
|
194
|
-
try {
|
|
195
|
-
const result = await authenticate(mode, form);
|
|
196
|
-
if (result.error) { setMessage(result.error.message ?? 'Sign in failed.'); return; }
|
|
197
|
-
await api.session();
|
|
198
|
-
await refresh();
|
|
199
|
-
} catch { setMessage('Unable to reach the API.'); }
|
|
200
|
-
finally { setPending(false); }
|
|
201
|
-
}
|
|
202
|
-
return <main className="mx-auto grid max-w-sm gap-4 p-6">
|
|
203
|
-
<h1 className="text-xl font-medium">{fields.title}</h1>
|
|
204
|
-
<form onSubmit={submit} className="grid gap-3">
|
|
205
|
-
{fields.name && <label>Name<input className="block w-full rounded border p-2" name="name" autoComplete="name" required /></label>}
|
|
206
|
-
<label>Email<input className="block w-full rounded border p-2" type="email" name="email" autoComplete="email" required /></label>
|
|
207
|
-
<label>Password<input className="block w-full rounded border p-2" type="password" name="password" autoComplete={fields.password} minLength={8} required /></label>
|
|
208
|
-
<Button type="submit" disabled={pending}>{pending ? 'Working…' : fields.title}</Button>
|
|
209
|
-
</form>
|
|
210
|
-
<p role="status">{message}</p>
|
|
211
|
-
<Button variant="ghost" disabled={pending} onClick={() => { setMode(fields.next); setMessage(''); }}>{fields.toggle}</Button>
|
|
212
|
-
</main>;
|
|
213
|
-
}
|
|
214
|
-
export default function SignInPage() {
|
|
215
|
-
const { data: session, refetch } = authClient.useSession();
|
|
216
|
-
if (!session) return <AuthForm refresh={refetch} />;
|
|
217
|
-
return <main className="mx-auto grid max-w-sm gap-4 p-6">
|
|
218
|
-
<h1 className="text-xl font-medium">Account</h1>
|
|
219
|
-
<p>{session.user.email}</p>
|
|
220
|
-
<Button onClick={async () => { await authClient.signOut(); await refetch(); }}>Sign out</Button>
|
|
221
|
-
</main>;
|
|
222
|
-
}
|
|
223
|
-
`);
|
|
224
|
-
}
|