anhedral 0.1.9 → 0.3.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/CHANGELOG.md +97 -0
- package/CONTRIBUTING.md +70 -0
- package/LICENSE +21 -17
- package/README.md +151 -152
- package/SECURITY.md +35 -0
- package/SKILL.md +177 -0
- package/bin/anhedral.js +1 -1
- package/dist/architecture/contributions.d.ts +28 -0
- package/dist/architecture/contributions.js +118 -0
- package/dist/architecture/index.d.ts +12 -0
- package/dist/architecture/index.js +6 -0
- package/dist/architecture/manifest.d.ts +53 -0
- package/dist/architecture/manifest.js +283 -0
- package/dist/architecture/modules.d.ts +37 -0
- package/dist/architecture/modules.js +176 -0
- package/dist/architecture/plan.d.ts +58 -0
- package/dist/architecture/plan.js +145 -0
- package/dist/architecture/templates.d.ts +10 -0
- package/dist/architecture/templates.js +23 -0
- package/dist/bin.d.ts +2 -0
- package/dist/bin.js +167 -0
- package/dist/cli.d.ts +24 -2
- package/dist/cli.js +186 -21
- package/dist/composers/root.d.ts +6 -0
- package/dist/composers/root.js +34 -0
- package/dist/dependencies.d.ts +29 -9
- package/dist/dependencies.js +220 -60
- package/dist/index.d.ts +8 -2
- package/dist/index.js +5 -31
- package/dist/print.js +15 -0
- package/dist/prompts.d.ts +5 -0
- package/dist/prompts.js +19 -0
- package/dist/render.d.ts +11 -0
- package/dist/render.js +74 -0
- package/dist/scaffold.d.ts +56 -12
- package/dist/scaffold.js +1466 -1158
- package/dist/template-source.d.ts +20 -0
- package/dist/template-source.js +180 -0
- package/dist/templates/api.d.ts +2 -0
- package/dist/templates/api.js +3114 -0
- package/dist/templates/assets-private-proxy.d.ts +3 -0
- package/dist/templates/assets-private-proxy.js +277 -0
- package/dist/templates/desktop.d.ts +2 -0
- package/dist/templates/desktop.js +572 -0
- package/dist/templates/extension.d.ts +1 -1
- package/dist/templates/extension.js +322 -248
- package/dist/templates/mobile.d.ts +2 -0
- package/dist/templates/mobile.js +720 -0
- package/dist/templates/shared.d.ts +2 -0
- package/dist/templates/shared.js +503 -0
- package/dist/templates/web.d.ts +2 -0
- package/dist/templates/web.js +412 -0
- package/dist/toolchain.d.ts +0 -8
- package/dist/toolchain.js +0 -21
- package/dist/transaction.d.ts +22 -0
- package/dist/transaction.js +822 -0
- package/dist/ui.d.ts +33 -0
- package/dist/ui.js +199 -0
- package/dist/util.d.ts +1 -5
- package/dist/util.js +70 -159
- package/dist/version.d.ts +2 -0
- package/dist/version.js +2 -0
- package/dist/workspace-config.d.ts +11 -0
- package/dist/workspace-config.js +372 -0
- package/docs/conventions.md +89 -0
- package/docs/output-tree-contract.md +442 -0
- package/package.json +56 -13
- package/references/manual-scaffolding.md +386 -0
- package/templates/api-fastify/apps/api/tsconfig.json +20 -0
- package/templates/catalog.json +23 -0
- package/templates/db-drizzle/packages/db/tsconfig.json +14 -0
- package/templates/desktop-electron/apps/desktop/tsconfig.json +37 -0
- package/templates/extension-wxt/apps/extension/tsconfig.json +41 -0
- package/templates/mobile-expo/apps/mobile/expo-env.d.ts +1 -0
- package/templates/web-next/apps/web/next-env.d.ts +6 -0
- package/dist/branding.d.ts +0 -5
- package/dist/branding.js +0 -17
- package/dist/commands.d.ts +0 -7
- package/dist/commands.js +0 -24
- package/dist/templates/backend.d.ts +0 -2
- package/dist/templates/backend.js +0 -2115
- package/dist/templates/frontend.d.ts +0 -2
- package/dist/templates/frontend.js +0 -1268
package/dist/scaffold.js
CHANGED
|
@@ -1,1305 +1,1613 @@
|
|
|
1
|
-
import { readdirSync } from 'node:fs';
|
|
1
|
+
import { lstatSync, mkdirSync, readFileSync, readdirSync, rmdirSync, rmSync } from 'node:fs';
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { env } from 'node:process';
|
|
4
4
|
import { anhedralPrint } from './print.js';
|
|
5
|
-
import { appendGitignore, writeFile } from './util.js';
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
5
|
+
import { appendGitignore, execFile, writeFile } from './util.js';
|
|
6
|
+
import { MOBILE_NODE_ENGINE, NODE_ENGINE, PACKAGE_MANAGER, ROOT_DEPENDENCIES, TOOLCHAIN_DEPENDENCIES } from './dependencies.js';
|
|
7
|
+
import { resolveToolchainChannel } from './toolchain.js';
|
|
8
|
+
import { scaffoldApi } from './templates/api.js';
|
|
9
|
+
import { r2BucketName, scaffoldAssetsPrivateProxy } from './templates/assets-private-proxy.js';
|
|
10
|
+
import { scaffoldDesktop } from './templates/desktop.js';
|
|
10
11
|
import { scaffoldExtension } from './templates/extension.js';
|
|
11
|
-
import {
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
];
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
12
|
+
import { scaffoldMobile } from './templates/mobile.js';
|
|
13
|
+
import { scaffoldSharedPackages } from './templates/shared.js';
|
|
14
|
+
import { scaffoldWeb } from './templates/web.js';
|
|
15
|
+
import { assertPackageName, markdownHeading } from './render.js';
|
|
16
|
+
import { runStagedTransaction } from './transaction.js';
|
|
17
|
+
import { buildGenerationPlan, createManifest, hashContent, readManifest, resolveModules, serializeManifest, } from './architecture/index.js';
|
|
18
|
+
import { GENERATOR_VERSION } from './version.js';
|
|
19
|
+
import { collectModuleContributions } from './architecture/contributions.js';
|
|
20
|
+
import { composeRootEnvironment, composeVercelCrons } from './composers/root.js';
|
|
21
|
+
import { assertTemplateProvenance, materializeTemplates, } from './template-source.js';
|
|
22
|
+
import { desiredWorkspacePolicy, mergeWorkspaceFile, } from './workspace-config.js';
|
|
23
|
+
import { UI_TARGETS, installUiComponents, mergeUiInstalls, resolveUiInstalls, uiInstallKey, } from './ui.js';
|
|
24
|
+
export function supportsMobileInstallNode(version) {
|
|
25
|
+
const match = /^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(version);
|
|
26
|
+
if (!match)
|
|
27
|
+
return false;
|
|
28
|
+
const major = Number(match[1]);
|
|
29
|
+
const minor = Number(match[2]);
|
|
30
|
+
if (major === 22)
|
|
31
|
+
return minor >= 13;
|
|
32
|
+
if (major === 24)
|
|
33
|
+
return minor >= 3;
|
|
34
|
+
return major >= 25;
|
|
35
|
+
}
|
|
36
|
+
function assertInstallNodeCompatibility(options) {
|
|
37
|
+
if (options.apps.mobile
|
|
38
|
+
&& !options.skipInstall
|
|
39
|
+
&& !options.dryRun
|
|
40
|
+
&& !supportsMobileInstallNode(process.versions.node)) {
|
|
41
|
+
throw new Error(`Installing an Expo mobile workspace requires Node ${MOBILE_NODE_ENGINE}; current Node is ${process.versions.node}. `
|
|
42
|
+
+ 'Switch Node versions or rerun with --skip-install.');
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
const ACTIONS = {
|
|
46
|
+
checkout: 'actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10',
|
|
47
|
+
pnpm: 'pnpm/action-setup@0ebf47130e4866e96fce0953f49152a61190b271',
|
|
48
|
+
node: 'actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38',
|
|
49
|
+
};
|
|
50
|
+
const ROOT_MERGEABLE_FILES = new Set([
|
|
51
|
+
'.env.example',
|
|
52
|
+
'.gitignore',
|
|
53
|
+
'.vercelignore',
|
|
54
|
+
'package.json',
|
|
55
|
+
'pnpm-workspace.yaml',
|
|
56
|
+
'turbo.json',
|
|
57
|
+
'vercel.json',
|
|
58
|
+
]);
|
|
59
|
+
const GENERATED_CACHE_NAMES = new Set([
|
|
60
|
+
'.git', '.next', '.output', '.turbo', '.wxt', 'dist', 'node_modules', 'release',
|
|
61
|
+
]);
|
|
62
|
+
function lstatIfPresent(target) {
|
|
63
|
+
try {
|
|
64
|
+
return lstatSync(target);
|
|
65
|
+
}
|
|
66
|
+
catch (error) {
|
|
67
|
+
if (error.code === 'ENOENT')
|
|
68
|
+
return null;
|
|
69
|
+
throw error;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
function pathEntryExists(target) {
|
|
73
|
+
return lstatIfPresent(target) !== null;
|
|
74
|
+
}
|
|
75
|
+
function normalizedFileMode(mode) {
|
|
76
|
+
// Windows exposes a synthetic subset of stat mode bits that cannot represent
|
|
77
|
+
// Unix permissions reliably. Keep the manifest portable by treating those
|
|
78
|
+
// permissions as unknown and disabling ownership checks on that platform.
|
|
79
|
+
return process.platform === 'win32' ? null : Number(mode) & 0o777;
|
|
80
|
+
}
|
|
81
|
+
function displayFileMode(mode) {
|
|
82
|
+
return `0o${mode.toString(8).padStart(3, '0')}`;
|
|
83
|
+
}
|
|
84
|
+
function assertManagedFileMode(relativePath, record, actualStat) {
|
|
85
|
+
if (record.ownership !== 'managed' || record.mode === null)
|
|
86
|
+
return;
|
|
87
|
+
const actualMode = normalizedFileMode(actualStat.mode);
|
|
88
|
+
if (actualMode === null || actualMode === record.mode)
|
|
89
|
+
return;
|
|
90
|
+
throw new Error(`Managed file mode has user modifications: ${relativePath} `
|
|
91
|
+
+ `(expected ${displayFileMode(record.mode)}, found ${displayFileMode(actualMode)}).`);
|
|
92
|
+
}
|
|
93
|
+
function assertManagedFileModes(root, manifest) {
|
|
94
|
+
for (const [relativePath, record] of Object.entries(manifest.files)) {
|
|
95
|
+
if (record.ownership !== 'managed' || record.mode === null)
|
|
96
|
+
continue;
|
|
97
|
+
const actualStat = lstatIfPresent(path.join(root, relativePath));
|
|
98
|
+
if (!actualStat || !actualStat.isFile() || actualStat.isSymbolicLink())
|
|
99
|
+
continue;
|
|
100
|
+
assertManagedFileMode(relativePath, record, actualStat);
|
|
39
101
|
}
|
|
40
|
-
console.log('');
|
|
41
102
|
}
|
|
42
|
-
function
|
|
103
|
+
function isTransactionMetadata(relativePath) {
|
|
104
|
+
if (relativePath.includes('/'))
|
|
105
|
+
return false;
|
|
106
|
+
return relativePath === '.anhedral-txn'
|
|
107
|
+
|| relativePath === '.anhedral.lock'
|
|
108
|
+
|| relativePath === '.anhedral.lock.reclaim'
|
|
109
|
+
|| /^\.anhedral\.lock\..+\.tmp$/.test(relativePath)
|
|
110
|
+
|| relativePath === '.anhedral-journal.json'
|
|
111
|
+
|| /^\.anhedral-journal\.json\.tmp-.+$/.test(relativePath);
|
|
112
|
+
}
|
|
113
|
+
function projectOptions(options) {
|
|
43
114
|
return {
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
115
|
+
projectName: options.projectName,
|
|
116
|
+
displayName: options.displayName,
|
|
117
|
+
apps: options.apps,
|
|
118
|
+
features: options.features,
|
|
119
|
+
skipInstall: options.skipInstall || options.dryRun,
|
|
120
|
+
nativeStyling: options.nativeStyling,
|
|
48
121
|
};
|
|
49
122
|
}
|
|
50
|
-
function
|
|
51
|
-
const
|
|
123
|
+
function selectionsFromModules(modules) {
|
|
124
|
+
const selected = new Set(modules);
|
|
52
125
|
return {
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
monorepo: true,
|
|
67
|
-
package_manager: 'pnpm',
|
|
68
|
-
dependency_manifest: dependencyManifest(),
|
|
69
|
-
toolchain_channel: options.toolchainChannel,
|
|
70
|
-
toolchain: getUsedToolchain(options, toolchain),
|
|
71
|
-
generated_paths: generatedPaths,
|
|
126
|
+
apps: {
|
|
127
|
+
web: selected.has('web'),
|
|
128
|
+
mobile: selected.has('mobile'),
|
|
129
|
+
api: selected.has('api'),
|
|
130
|
+
desktop: selected.has('desktop'),
|
|
131
|
+
extension: selected.has('extension'),
|
|
132
|
+
},
|
|
133
|
+
features: {
|
|
134
|
+
database: selected.has('db'),
|
|
135
|
+
auth: selected.has('auth'),
|
|
136
|
+
billing: selected.has('billing'),
|
|
137
|
+
storage: selected.has('storage'),
|
|
138
|
+
nativeSubscriptions: selected.has('native-subscriptions'),
|
|
72
139
|
},
|
|
73
140
|
};
|
|
74
141
|
}
|
|
75
|
-
function
|
|
76
|
-
|
|
142
|
+
function canonicalInitOptions(options) {
|
|
143
|
+
assertPackageName(options.projectName);
|
|
144
|
+
const resolution = resolveModules(options.modules);
|
|
145
|
+
return {
|
|
146
|
+
...options,
|
|
147
|
+
uiComponents: options.uiComponents ?? [],
|
|
148
|
+
nativeStyling: options.nativeStyling ?? 'nativewind',
|
|
149
|
+
modules: [...resolution.requestedModules],
|
|
150
|
+
...selectionsFromModules(resolution.resolvedModules),
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
function optionsFromManifest(manifest, addOptions, modules) {
|
|
154
|
+
const resolution = resolveModules(modules);
|
|
155
|
+
return {
|
|
156
|
+
projectName: manifest.project.name,
|
|
157
|
+
displayName: manifest.project.displayName,
|
|
158
|
+
modules: [...resolution.requestedModules],
|
|
159
|
+
...selectionsFromModules(resolution.resolvedModules),
|
|
160
|
+
skipInstall: addOptions.skipInstall,
|
|
161
|
+
dryRun: addOptions.dryRun,
|
|
162
|
+
json: addOptions.json,
|
|
163
|
+
toolchainChannel: addOptions.toolchainChannel ?? toolchainChannelFromManifest(manifest),
|
|
164
|
+
uiComponents: [],
|
|
165
|
+
nativeStyling: manifest.ui.nativeStyling,
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
function toolchainChannelFromManifest(manifest) {
|
|
169
|
+
return resolveToolchainChannel(manifest.toolchain);
|
|
77
170
|
}
|
|
78
171
|
function ensureScaffoldRoot(root) {
|
|
79
|
-
const
|
|
80
|
-
|
|
172
|
+
const rootStat = lstatIfPresent(root);
|
|
173
|
+
if (!rootStat)
|
|
174
|
+
throw new Error(`Scaffold destination is not a directory: ${root}`);
|
|
175
|
+
if (rootStat.isSymbolicLink())
|
|
176
|
+
throw new Error(`Refusing scaffold destination that is a symbolic link: ${root}`);
|
|
177
|
+
if (!rootStat.isDirectory())
|
|
178
|
+
throw new Error(`Scaffold destination is not a directory: ${root}`);
|
|
179
|
+
const allowed = new Set(['.git', '.gitignore', '.DS_Store', '.anhedral.lock']);
|
|
180
|
+
const unexpected = readdirSync(root).filter((entry) => !allowed.has(entry));
|
|
81
181
|
if (unexpected.length > 0) {
|
|
82
|
-
throw new Error(`Current directory is not empty.
|
|
182
|
+
throw new Error(`Current directory is not empty. Found: ${unexpected.join(', ')}`);
|
|
83
183
|
}
|
|
84
184
|
}
|
|
85
|
-
function
|
|
86
|
-
|
|
87
|
-
|
|
185
|
+
function selectedAppFilters(apps) {
|
|
186
|
+
return Object.entries(apps)
|
|
187
|
+
.filter(([, enabled]) => enabled)
|
|
188
|
+
.map(([name]) => `./apps/${name}`);
|
|
189
|
+
}
|
|
190
|
+
function rootScripts(options) {
|
|
191
|
+
const filters = selectedAppFilters(options.apps);
|
|
192
|
+
const scripts = {
|
|
193
|
+
dev: filters.length ? `turbo dev --parallel ${filters.map((entry) => `--filter=${entry}`).join(' ')}` : 'echo "No app surfaces selected."',
|
|
194
|
+
build: 'turbo build',
|
|
195
|
+
typecheck: 'turbo typecheck',
|
|
196
|
+
};
|
|
197
|
+
const verify = [];
|
|
198
|
+
if (options.apps.web) {
|
|
199
|
+
scripts['dev:web'] = 'pnpm --filter ./apps/web dev';
|
|
200
|
+
scripts['verify:web'] = 'pnpm --filter ./apps/web typecheck && pnpm --filter ./apps/web build';
|
|
201
|
+
verify.push('pnpm verify:web');
|
|
202
|
+
}
|
|
203
|
+
if (options.apps.web || options.apps.api) {
|
|
204
|
+
scripts['deploy:vercel:link'] = `pnpm dlx vercel@${TOOLCHAIN_DEPENDENCIES.vercel} link`;
|
|
205
|
+
scripts['deploy:vercel:preview'] = `pnpm dlx vercel@${TOOLCHAIN_DEPENDENCIES.vercel} deploy`;
|
|
206
|
+
scripts['deploy:vercel:production'] = `pnpm dlx vercel@${TOOLCHAIN_DEPENDENCIES.vercel} deploy --prod`;
|
|
207
|
+
scripts['deploy:vercel:inspect'] = `pnpm dlx vercel@${TOOLCHAIN_DEPENDENCIES.vercel} inspect`;
|
|
208
|
+
scripts['deploy:vercel:domain:inspect'] = `pnpm dlx vercel@${TOOLCHAIN_DEPENDENCIES.vercel} domains inspect`;
|
|
209
|
+
}
|
|
210
|
+
if (options.apps.mobile) {
|
|
211
|
+
scripts['dev:mobile'] = 'pnpm --filter ./apps/mobile dev';
|
|
212
|
+
scripts['verify:mobile'] = 'pnpm --filter ./apps/mobile typecheck && pnpm --filter ./apps/mobile build:web';
|
|
213
|
+
verify.push('pnpm verify:mobile');
|
|
214
|
+
const eas = `pnpm --dir apps/mobile dlx eas-cli@${TOOLCHAIN_DEPENDENCIES['eas-cli']}`;
|
|
215
|
+
scripts['mobile:eas:login'] = `${eas} login`;
|
|
216
|
+
scripts['mobile:eas:init'] = `${eas} init`;
|
|
217
|
+
scripts['mobile:build:internal:ios'] = `${eas} build --platform ios --profile preview`;
|
|
218
|
+
scripts['mobile:build:internal:android'] = `${eas} build --platform android --profile preview`;
|
|
219
|
+
scripts['mobile:build:production:ios'] = `${eas} build --platform ios --profile production`;
|
|
220
|
+
scripts['mobile:build:production:android'] = `${eas} build --platform android --profile production`;
|
|
221
|
+
scripts['mobile:submit:ios'] = `${eas} submit --platform ios --profile production --latest`;
|
|
222
|
+
scripts['mobile:submit:android'] = `${eas} submit --platform android --profile production --latest`;
|
|
223
|
+
}
|
|
224
|
+
if (options.apps.api) {
|
|
225
|
+
scripts['dev:api'] = 'pnpm --filter ./apps/api dev';
|
|
226
|
+
scripts['verify:api'] = 'pnpm --filter ./apps/api test:coverage && pnpm --filter ./apps/api build';
|
|
227
|
+
verify.push('pnpm verify:api');
|
|
228
|
+
}
|
|
229
|
+
if (options.apps.desktop) {
|
|
230
|
+
scripts['dev:desktop'] = 'pnpm --filter ./apps/desktop dev';
|
|
231
|
+
scripts['desktop:build'] = 'pnpm --filter ./apps/desktop package';
|
|
232
|
+
scripts['verify:desktop'] = 'pnpm --filter ./apps/desktop typecheck && pnpm --filter ./apps/desktop build';
|
|
233
|
+
verify.push('pnpm verify:desktop');
|
|
234
|
+
}
|
|
235
|
+
if (options.apps.extension) {
|
|
236
|
+
scripts['dev:extension'] = 'pnpm --filter ./apps/extension dev';
|
|
237
|
+
scripts['extension:zip'] = 'pnpm --filter ./apps/extension zip';
|
|
238
|
+
scripts['verify:extension'] = 'pnpm --filter ./apps/extension typecheck && pnpm --filter ./apps/extension zip';
|
|
239
|
+
verify.push('pnpm verify:extension');
|
|
240
|
+
}
|
|
241
|
+
if (options.features.database) {
|
|
242
|
+
scripts['neon:login'] = `pnpm dlx neonctl@${TOOLCHAIN_DEPENDENCIES.neonctl} auth`;
|
|
243
|
+
scripts['neon:project:create'] = `pnpm dlx neonctl@${TOOLCHAIN_DEPENDENCIES.neonctl} projects create`;
|
|
244
|
+
scripts['db:generate'] = 'pnpm --filter @shared/db db:generate';
|
|
245
|
+
scripts['db:migrate'] = 'pnpm --filter @shared/db db:migrate';
|
|
246
|
+
scripts['db:check'] = 'pnpm --filter @shared/db db:check';
|
|
247
|
+
scripts['db:studio'] = 'pnpm --filter @shared/db db:studio';
|
|
248
|
+
scripts['verify:db'] = 'node scripts/verify-db-migrations.mjs && pnpm db:check';
|
|
249
|
+
verify.push('pnpm verify:db');
|
|
250
|
+
}
|
|
251
|
+
if (options.features.storage) {
|
|
252
|
+
const bucketName = r2BucketName(options.projectName);
|
|
253
|
+
scripts['r2:login'] = `pnpm dlx wrangler@${TOOLCHAIN_DEPENDENCIES.wrangler} login`;
|
|
254
|
+
scripts['r2:bucket:create'] = `pnpm dlx wrangler@${TOOLCHAIN_DEPENDENCIES.wrangler} r2 bucket create ${bucketName}`;
|
|
255
|
+
scripts['r2:cors:list'] = `pnpm dlx wrangler@${TOOLCHAIN_DEPENDENCIES.wrangler} r2 bucket cors list ${bucketName}`;
|
|
256
|
+
scripts['r2:cors:set'] = `pnpm dlx wrangler@${TOOLCHAIN_DEPENDENCIES.wrangler} r2 bucket cors set ${bucketName} --file cloudflare/r2-cors.template.json`;
|
|
257
|
+
scripts['assets:proxy:check'] = 'pnpm --filter ./apps/assets-private-proxy check';
|
|
258
|
+
scripts['assets:proxy:dev'] = 'pnpm --filter ./apps/assets-private-proxy dev';
|
|
259
|
+
scripts['assets:proxy:deploy'] = 'pnpm --filter ./apps/assets-private-proxy deploy';
|
|
260
|
+
scripts['verify:assets-proxy'] = 'pnpm assets:proxy:check';
|
|
261
|
+
verify.push('pnpm verify:assets-proxy');
|
|
262
|
+
}
|
|
263
|
+
if (!Object.values(options.apps).some(Boolean))
|
|
264
|
+
verify.unshift('pnpm typecheck');
|
|
265
|
+
scripts.verify = verify.join(' && ');
|
|
266
|
+
return scripts;
|
|
267
|
+
}
|
|
268
|
+
function desiredRootPackage(options) {
|
|
269
|
+
const workspaces = [
|
|
270
|
+
Object.values(options.apps).some(Boolean) ? 'apps/*' : null,
|
|
271
|
+
options.apps.api || options.features.database ? 'packages/*' : null,
|
|
272
|
+
].filter((value) => value !== null);
|
|
273
|
+
return {
|
|
274
|
+
name: options.projectName,
|
|
88
275
|
private: true,
|
|
89
276
|
version: '0.1.0',
|
|
90
277
|
packageManager: PACKAGE_MANAGER,
|
|
91
|
-
|
|
92
|
-
|
|
278
|
+
engines: { node: options.apps.mobile ? MOBILE_NODE_ENGINE : NODE_ENGINE },
|
|
279
|
+
scripts: rootScripts(options),
|
|
280
|
+
workspaces,
|
|
281
|
+
devDependencies: ROOT_DEPENDENCIES.devDependencies,
|
|
93
282
|
};
|
|
94
|
-
|
|
95
|
-
|
|
283
|
+
}
|
|
284
|
+
function sameJson(left, right) {
|
|
285
|
+
if (Object.is(left, right))
|
|
286
|
+
return true;
|
|
287
|
+
if (Array.isArray(left) || Array.isArray(right)) {
|
|
288
|
+
return Array.isArray(left)
|
|
289
|
+
&& Array.isArray(right)
|
|
290
|
+
&& left.length === right.length
|
|
291
|
+
&& left.every((entry, index) => sameJson(entry, right[index]));
|
|
96
292
|
}
|
|
97
|
-
|
|
293
|
+
if (!isJsonRecord(left) || !isJsonRecord(right))
|
|
294
|
+
return false;
|
|
295
|
+
const leftKeys = Object.keys(left).sort();
|
|
296
|
+
const rightKeys = Object.keys(right).sort();
|
|
297
|
+
return leftKeys.length === rightKeys.length
|
|
298
|
+
&& leftKeys.every((key, index) => key === rightKeys[index] && sameJson(left[key], right[key]));
|
|
98
299
|
}
|
|
99
|
-
function
|
|
100
|
-
|
|
101
|
-
writeFile(path.join(root, 'pnpm-workspace.yaml'), `packages:\n${serializedPackages}\n`);
|
|
300
|
+
function isJsonRecord(value) {
|
|
301
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
102
302
|
}
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
# Manual skill installation guide for this project.
|
|
107
|
-
#
|
|
108
|
-
# Run the commands below after setup. The skills CLI will prompt you to:
|
|
109
|
-
# - choose which agents to install to
|
|
110
|
-
# - choose whether the install should be project-scoped or global
|
|
111
|
-
#
|
|
112
|
-
# If you want the skill files tracked with this project, choose the project scope.
|
|
113
|
-
# Run each command one at a time if you want to review each prompt separately.
|
|
114
|
-
|
|
115
|
-
${commandBlock}`);
|
|
303
|
+
const MISSING_JSON_VALUE = Symbol('missing-json-value');
|
|
304
|
+
function includesJson(values, candidate) {
|
|
305
|
+
return values.some((value) => sameJson(value, candidate));
|
|
116
306
|
}
|
|
117
|
-
function
|
|
118
|
-
const
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
307
|
+
function mergeChangedArrays(current, desired, previous) {
|
|
308
|
+
const merged = [];
|
|
309
|
+
for (const entry of desired) {
|
|
310
|
+
if ((!includesJson(previous, entry) || includesJson(current, entry)) && !includesJson(merged, entry)) {
|
|
311
|
+
merged.push(entry);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
for (const entry of current) {
|
|
315
|
+
if (!includesJson(previous, entry) && !includesJson(merged, entry))
|
|
316
|
+
merged.push(entry);
|
|
317
|
+
}
|
|
318
|
+
return merged;
|
|
319
|
+
}
|
|
320
|
+
function mergeGeneratedThreeWay(current, desired, previous, fieldPath) {
|
|
321
|
+
if (current === MISSING_JSON_VALUE) {
|
|
322
|
+
if (desired === MISSING_JSON_VALUE)
|
|
323
|
+
return MISSING_JSON_VALUE;
|
|
324
|
+
if (previous === MISSING_JSON_VALUE)
|
|
325
|
+
return desired;
|
|
326
|
+
if (sameJson(desired, previous))
|
|
327
|
+
return MISSING_JSON_VALUE;
|
|
328
|
+
throw new Error(`Conflict in ${fieldPath}: a generated value changed after the user removed it.`);
|
|
329
|
+
}
|
|
330
|
+
if (desired === MISSING_JSON_VALUE) {
|
|
331
|
+
if (previous === MISSING_JSON_VALUE)
|
|
332
|
+
return current;
|
|
333
|
+
if (sameJson(current, previous))
|
|
334
|
+
return MISSING_JSON_VALUE;
|
|
335
|
+
return current;
|
|
336
|
+
}
|
|
337
|
+
if (previous === MISSING_JSON_VALUE) {
|
|
338
|
+
if (sameJson(current, desired))
|
|
339
|
+
return desired;
|
|
340
|
+
if (isJsonRecord(current) && isJsonRecord(desired)) {
|
|
341
|
+
return mergeGeneratedRecords(current, desired, {}, fieldPath, true);
|
|
342
|
+
}
|
|
343
|
+
if (Array.isArray(current) && Array.isArray(desired)) {
|
|
344
|
+
return [...desired, ...current.filter((entry) => !includesJson(desired, entry))];
|
|
345
|
+
}
|
|
346
|
+
throw new Error(`Conflict in ${fieldPath}: a newly generated value collides with a user-defined value.`);
|
|
347
|
+
}
|
|
348
|
+
if (sameJson(current, desired))
|
|
349
|
+
return current;
|
|
350
|
+
if (sameJson(current, previous))
|
|
351
|
+
return desired;
|
|
352
|
+
if (sameJson(desired, previous))
|
|
353
|
+
return current;
|
|
354
|
+
if (isJsonRecord(current) && isJsonRecord(desired) && isJsonRecord(previous)) {
|
|
355
|
+
return mergeGeneratedRecords(current, desired, previous, fieldPath, true);
|
|
356
|
+
}
|
|
357
|
+
if (Array.isArray(current) && Array.isArray(desired) && Array.isArray(previous)) {
|
|
358
|
+
return mergeChangedArrays(current, desired, previous);
|
|
359
|
+
}
|
|
360
|
+
throw new Error(`Conflict in ${fieldPath}: both the generator and the user changed the value.`);
|
|
361
|
+
}
|
|
362
|
+
function mergeGeneratedOwned(current, desired, fieldPath) {
|
|
363
|
+
if (desired === MISSING_JSON_VALUE)
|
|
364
|
+
return current;
|
|
365
|
+
if (current === MISSING_JSON_VALUE)
|
|
366
|
+
return desired;
|
|
367
|
+
if (isJsonRecord(current) && isJsonRecord(desired)) {
|
|
368
|
+
return mergeGeneratedRecords(current, desired, {}, fieldPath, false);
|
|
369
|
+
}
|
|
370
|
+
if (Array.isArray(current) && Array.isArray(desired)) {
|
|
371
|
+
return [...desired, ...current.filter((entry) => !includesJson(desired, entry))];
|
|
372
|
+
}
|
|
373
|
+
if (isJsonRecord(current)
|
|
374
|
+
|| isJsonRecord(desired)
|
|
375
|
+
|| Array.isArray(current)
|
|
376
|
+
|| Array.isArray(desired)) {
|
|
377
|
+
throw new Error(`Conflict in ${fieldPath}: the generator version changed and the value shape is ambiguous.`);
|
|
378
|
+
}
|
|
379
|
+
// Without a trustworthy previous-generator snapshot, an existing scalar may
|
|
380
|
+
// be user-authored. Preserve it instead of silently resetting it to today's
|
|
381
|
+
// default. Newly introduced keys still take the desired value above.
|
|
382
|
+
return current;
|
|
383
|
+
}
|
|
384
|
+
function mergeGeneratedRecords(current, desired, previous, fieldPath, trustPrevious) {
|
|
385
|
+
const keys = [...new Set([...Object.keys(desired), ...Object.keys(current), ...Object.keys(previous)])];
|
|
386
|
+
const entries = [];
|
|
387
|
+
for (const key of keys) {
|
|
388
|
+
const currentValue = Object.hasOwn(current, key) ? current[key] : MISSING_JSON_VALUE;
|
|
389
|
+
const desiredValue = Object.hasOwn(desired, key) ? desired[key] : MISSING_JSON_VALUE;
|
|
390
|
+
const previousValue = Object.hasOwn(previous, key) ? previous[key] : MISSING_JSON_VALUE;
|
|
391
|
+
const value = trustPrevious
|
|
392
|
+
? mergeGeneratedThreeWay(currentValue, desiredValue, previousValue, `${fieldPath}.${key}`)
|
|
393
|
+
: mergeGeneratedOwned(currentValue, desiredValue, `${fieldPath}.${key}`);
|
|
394
|
+
if (value !== MISSING_JSON_VALUE)
|
|
395
|
+
entries.push([key, value]);
|
|
396
|
+
}
|
|
397
|
+
return Object.fromEntries(entries);
|
|
398
|
+
}
|
|
399
|
+
function mergeGeneratedStructure(current, desired, previous, fieldPath, trustPrevious) {
|
|
400
|
+
if (isJsonRecord(current) && isJsonRecord(desired)) {
|
|
401
|
+
return mergeGeneratedRecords(current, desired, isJsonRecord(previous) ? previous : {}, fieldPath, trustPrevious);
|
|
402
|
+
}
|
|
403
|
+
return trustPrevious
|
|
404
|
+
? mergeGeneratedThreeWay(current, desired, previous, fieldPath)
|
|
405
|
+
: mergeGeneratedOwned(current, desired, fieldPath);
|
|
406
|
+
}
|
|
407
|
+
function mergeStringMap(current, desired, previousGenerated, filePath, allowGeneratedUpdates) {
|
|
408
|
+
const existing = current && typeof current === 'object' ? current : {};
|
|
409
|
+
const generated = desired && typeof desired === 'object' ? desired : {};
|
|
410
|
+
const previous = previousGenerated && typeof previousGenerated === 'object'
|
|
411
|
+
? previousGenerated
|
|
412
|
+
: {};
|
|
413
|
+
const merged = { ...existing };
|
|
414
|
+
for (const [key, value] of Object.entries(generated)) {
|
|
415
|
+
if (merged[key] === undefined || merged[key] === value || allowGeneratedUpdates || merged[key] === previous[key])
|
|
416
|
+
merged[key] = value;
|
|
417
|
+
else
|
|
418
|
+
throw new Error(`Conflict in ${filePath}: key ${key} has a user-defined value.`);
|
|
419
|
+
}
|
|
420
|
+
return Object.fromEntries(Object.entries(merged).sort(([left], [right]) => left.localeCompare(right)));
|
|
421
|
+
}
|
|
422
|
+
function writeRootPackage(root, options, mode, allowGeneratedUpdates, previousGenerated) {
|
|
423
|
+
const filePath = path.join(root, 'package.json');
|
|
424
|
+
const desired = desiredRootPackage(options);
|
|
425
|
+
if (mode === 'init' || !pathEntryExists(filePath)) {
|
|
426
|
+
writeFile(filePath, JSON.stringify(desired, null, 2) + '\n');
|
|
427
|
+
return;
|
|
428
|
+
}
|
|
429
|
+
const current = JSON.parse(readFileSync(filePath, 'utf8'));
|
|
430
|
+
const desiredWorkspaces = desired.workspaces;
|
|
431
|
+
const currentWorkspaces = Array.isArray(current.workspaces) ? current.workspaces.filter((value) => typeof value === 'string') : [];
|
|
432
|
+
const mergeMetadataField = (field) => {
|
|
433
|
+
const currentValue = current[field];
|
|
434
|
+
const desiredValue = desired[field];
|
|
435
|
+
const previousValue = previousGenerated?.[field];
|
|
436
|
+
if (allowGeneratedUpdates
|
|
437
|
+
|| currentValue === undefined
|
|
438
|
+
|| (previousValue !== undefined && sameJson(currentValue, previousValue))) {
|
|
439
|
+
return desiredValue;
|
|
440
|
+
}
|
|
441
|
+
if (previousValue !== undefined && !sameJson(previousValue, desiredValue)) {
|
|
442
|
+
throw new Error(`Conflict in package.json: ${field} was user-modified and must satisfy the newly selected modules.`);
|
|
443
|
+
}
|
|
444
|
+
return currentValue;
|
|
445
|
+
};
|
|
446
|
+
const merged = {
|
|
447
|
+
...desired,
|
|
448
|
+
...current,
|
|
449
|
+
private: true,
|
|
450
|
+
packageManager: mergeMetadataField('packageManager'),
|
|
451
|
+
engines: mergeMetadataField('engines'),
|
|
452
|
+
workspaces: [...new Set([...currentWorkspaces, ...desiredWorkspaces])].sort(),
|
|
453
|
+
scripts: mergeStringMap(current.scripts, desired.scripts, previousGenerated?.scripts, 'package.json scripts', allowGeneratedUpdates),
|
|
454
|
+
devDependencies: mergeStringMap(current.devDependencies, desired.devDependencies, previousGenerated?.devDependencies, 'package.json devDependencies', allowGeneratedUpdates),
|
|
455
|
+
};
|
|
456
|
+
writeFile(filePath, JSON.stringify(merged, null, 2) + '\n');
|
|
457
|
+
}
|
|
458
|
+
function mergeJsonConfig(root, relativePath, desired, previousGenerated, trustPreviousGenerated) {
|
|
459
|
+
const filePath = path.join(root, relativePath);
|
|
460
|
+
if (!pathEntryExists(filePath)) {
|
|
461
|
+
writeFile(filePath, JSON.stringify(desired, null, 2) + '\n');
|
|
462
|
+
return;
|
|
463
|
+
}
|
|
464
|
+
const current = JSON.parse(readFileSync(filePath, 'utf8'));
|
|
465
|
+
const merged = mergeGeneratedStructure(current, desired, previousGenerated, relativePath, trustPreviousGenerated);
|
|
466
|
+
writeFile(filePath, JSON.stringify(merged, null, 2) + '\n');
|
|
467
|
+
}
|
|
468
|
+
function writeRootEnv(root, options) {
|
|
469
|
+
const corsOrigins = [
|
|
470
|
+
options.apps.web ? 'http://localhost:3000' : null,
|
|
471
|
+
options.apps.mobile ? 'http://localhost:8081' : null,
|
|
472
|
+
options.apps.desktop ? 'http://127.0.0.1:5173' : null,
|
|
473
|
+
options.apps.desktop ? 'null' : null,
|
|
474
|
+
].filter((value) => value !== null);
|
|
475
|
+
const lines = composeRootEnvironment(collectModuleContributions(options.modules), { corsOrigins });
|
|
476
|
+
const filePath = path.join(root, '.env.example');
|
|
477
|
+
const current = pathEntryExists(filePath) ? readFileSync(filePath, 'utf8') : '';
|
|
478
|
+
const existingKeys = new Set([...current.matchAll(/^([A-Z][A-Z0-9_]*)=/gm)].map((match) => match[1]));
|
|
479
|
+
const additions = lines.filter((line) => !existingKeys.has(line.slice(0, line.indexOf('='))));
|
|
480
|
+
const separator = current && additions.length ? (current.endsWith('\n') ? '\n' : '\n\n') : '';
|
|
481
|
+
writeFile(filePath, `${current}${separator}${additions.join('\n')}${additions.length ? '\n' : ''}`);
|
|
482
|
+
}
|
|
483
|
+
function desiredTurboConfig() {
|
|
484
|
+
return {
|
|
485
|
+
$schema: 'https://turborepo.dev/schema.json',
|
|
486
|
+
tasks: {
|
|
487
|
+
build: {
|
|
488
|
+
dependsOn: ['^build'],
|
|
489
|
+
outputs: ['.next/**', '!.next/cache/**', '.output/**', 'dist/**'],
|
|
490
|
+
},
|
|
491
|
+
typecheck: { dependsOn: ['^build'] },
|
|
492
|
+
dev: { cache: false, persistent: true },
|
|
493
|
+
},
|
|
494
|
+
};
|
|
495
|
+
}
|
|
496
|
+
function desiredVercelConfig(options) {
|
|
497
|
+
const services = {};
|
|
498
|
+
if (options.apps.api) {
|
|
499
|
+
services.api = { root: 'apps/api' };
|
|
500
|
+
}
|
|
501
|
+
if (options.apps.web) {
|
|
502
|
+
services.web = { root: 'apps/web', framework: 'nextjs' };
|
|
503
|
+
}
|
|
504
|
+
const rewrites = [
|
|
505
|
+
options.apps.api ? { source: '/api/(.*)', destination: { service: 'api' } } : null,
|
|
506
|
+
options.apps.web ? { source: '/(.*)', destination: { service: 'web' } } : null,
|
|
507
|
+
].filter((rewrite) => rewrite !== null);
|
|
508
|
+
const crons = composeVercelCrons(collectModuleContributions(options.modules));
|
|
509
|
+
return {
|
|
510
|
+
$schema: 'https://openapi.vercel.sh/vercel.json',
|
|
511
|
+
...(Object.keys(services).length > 0 ? { services } : {}),
|
|
512
|
+
...(rewrites.length > 0 ? { rewrites } : {}),
|
|
513
|
+
...(crons.length > 0 ? { crons } : {}),
|
|
514
|
+
};
|
|
515
|
+
}
|
|
516
|
+
function generatedCi(options) {
|
|
517
|
+
const nodeVersion = options.apps.mobile ? '22.13.0' : '20.19.0';
|
|
518
|
+
const commands = [
|
|
519
|
+
'pnpm typecheck',
|
|
520
|
+
options.apps.api ? 'pnpm --filter ./apps/api test:coverage' : null,
|
|
521
|
+
'pnpm build',
|
|
522
|
+
].filter((value) => value !== null).join('\n ');
|
|
523
|
+
const databaseSteps = options.features.database ? `
|
|
524
|
+
- name: Verify committed database migration history
|
|
525
|
+
run: pnpm verify:db
|
|
526
|
+
- name: Verify database schema and migration parity
|
|
527
|
+
run: |
|
|
528
|
+
pnpm db:generate
|
|
529
|
+
git diff --exit-code -- packages/db/migrations
|
|
530
|
+
if [[ -n "$(git status --porcelain --untracked-files=all -- packages/db/migrations)" ]]; then
|
|
531
|
+
echo "drizzle-kit generated uncommitted migration artifacts:"
|
|
532
|
+
git status --short --untracked-files=all -- packages/db/migrations
|
|
533
|
+
exit 1
|
|
534
|
+
fi
|
|
535
|
+
` : '';
|
|
536
|
+
return `name: Anhedral CI
|
|
127
537
|
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
- Shared packages: \`packages/*\`
|
|
133
|
-
- Auth: ${options.auth}
|
|
134
|
-
- Payments: ${options.payments}
|
|
135
|
-
- Database: ${options.db} + ${options.orm}
|
|
136
|
-
- Storage: ${options.storage}
|
|
137
|
-
- API: ${options.api ?? 'framework-native'}
|
|
138
|
-
- Toolchain: ${toolchainLine}
|
|
139
|
-
- Dependency manifest: recorded in \`stack.json\`
|
|
538
|
+
on:
|
|
539
|
+
pull_request:
|
|
540
|
+
push:
|
|
541
|
+
branches: [main]
|
|
140
542
|
|
|
141
|
-
|
|
543
|
+
permissions:
|
|
544
|
+
contents: read
|
|
142
545
|
|
|
143
|
-
|
|
546
|
+
concurrency:
|
|
547
|
+
group: anhedral-ci-\${{ github.ref }}
|
|
548
|
+
cancel-in-progress: true
|
|
144
549
|
|
|
145
|
-
|
|
550
|
+
jobs:
|
|
551
|
+
verify:
|
|
552
|
+
runs-on: ubuntu-latest
|
|
553
|
+
timeout-minutes: 30
|
|
554
|
+
steps:
|
|
555
|
+
- uses: ${ACTIONS.checkout} # v6
|
|
556
|
+
with:
|
|
557
|
+
persist-credentials: false
|
|
558
|
+
- uses: ${ACTIONS.pnpm} # v6
|
|
559
|
+
with:
|
|
560
|
+
version: ${PACKAGE_MANAGER.replace('pnpm@', '')}
|
|
561
|
+
- uses: ${ACTIONS.node} # v6
|
|
562
|
+
with:
|
|
563
|
+
node-version: ${nodeVersion}
|
|
564
|
+
cache: pnpm
|
|
565
|
+
- run: pnpm install --frozen-lockfile
|
|
566
|
+
${databaseSteps} - name: Verify generated workspace
|
|
567
|
+
run: |
|
|
568
|
+
${commands}
|
|
569
|
+
`;
|
|
570
|
+
}
|
|
571
|
+
function writeDatabaseVerificationScript(root, options) {
|
|
572
|
+
if (!options.features.database)
|
|
573
|
+
return;
|
|
574
|
+
writeFile(path.join(root, 'scripts/verify-db-migrations.mjs'), `import { readdirSync } from 'node:fs';
|
|
575
|
+
import path from 'node:path';
|
|
576
|
+
import { spawnSync } from 'node:child_process';
|
|
146
577
|
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
cp .env.example .env
|
|
150
|
-
# Frontend/.env is generated for local Expo development
|
|
151
|
-
cp Extension/.env.example Extension/.env
|
|
152
|
-
pnpm db:generate
|
|
153
|
-
pnpm db:migrate
|
|
154
|
-
pnpm verify
|
|
155
|
-
pnpm dev:backend
|
|
156
|
-
pnpm dev:frontend
|
|
157
|
-
pnpm dev:extension
|
|
158
|
-
\`\`\`
|
|
578
|
+
const projectRoot = process.cwd();
|
|
579
|
+
const migrationsRoot = path.join(projectRoot, 'packages/db/migrations');
|
|
159
580
|
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
- Create a Neon project and database: https://neon.com/docs/get-started-with-neon/connect-neon
|
|
170
|
-
- Put the pooled connection string in \`DATABASE_URL\` in \`.env\`, \`Backend/.env\`, and the Backend Vercel project.
|
|
171
|
-
- Run \`pnpm db:generate\` and \`pnpm db:migrate\` after \`DATABASE_URL\` is real.
|
|
172
|
-
|
|
173
|
-
2. Clerk auth
|
|
174
|
-
- Expo setup: https://docs.expo.dev/guides/using-clerk/
|
|
175
|
-
- Clerk Expo quickstart: https://clerk.com/docs/quickstarts/get-started-with-expo
|
|
176
|
-
- Set \`EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY\` in \`Frontend/.env\`, Vercel Frontend, and EAS.
|
|
177
|
-
- Set \`CLERK_PUBLISHABLE_KEY\` and \`CLERK_SECRET_KEY\` in \`Backend/.env\` and Vercel Backend.
|
|
178
|
-
- Set \`VITE_CLERK_PUBLISHABLE_KEY\` in \`Extension/.env\`.
|
|
179
|
-
- Add allowed origins for \`http://localhost:8081\`, the Frontend Vercel domain, and the extension origin after Chrome assigns an extension id.
|
|
180
|
-
|
|
181
|
-
3. RevenueCat + Stripe
|
|
182
|
-
- RevenueCat Web overview: https://www.revenuecat.com/docs/web/overview
|
|
183
|
-
- RevenueCat Stripe Billing integration: https://www.revenuecat.com/docs/web/integrations/stripe
|
|
184
|
-
- Stripe API keys: https://docs.stripe.com/keys
|
|
185
|
-
- Create an entitlement named \`pro\`.
|
|
186
|
-
- Create iOS, Android, and Web apps in RevenueCat and copy their public SDK keys into \`EXPO_PUBLIC_RC_API_KEY_IOS\`, \`EXPO_PUBLIC_RC_API_KEY_ANDROID\`, and \`EXPO_PUBLIC_RC_WEB_API_KEY\`.
|
|
187
|
-
- Set \`EXPO_PUBLIC_RC_ENTITLEMENT_ID=pro\`.
|
|
188
|
-
- Set \`RC_SECRET_API_KEY\` and \`RC_WEBHOOK_SECRET\` only in Backend envs.
|
|
189
|
-
- Point the RevenueCat webhook to \`https://<backend-domain>/webhooks/revenuecat\`.
|
|
190
|
-
|
|
191
|
-
4. Cloudflare R2/CDN
|
|
192
|
-
- R2 S3-compatible setup: https://developers.cloudflare.com/r2/get-started/s3/
|
|
193
|
-
- R2 API tokens: https://developers.cloudflare.com/r2/api/tokens/
|
|
194
|
-
- Create a bucket and least-privilege API token.
|
|
195
|
-
- Set \`R2_ACCOUNT_ID\`, \`R2_ACCESS_KEY_ID\`, \`R2_SECRET_ACCESS_KEY\`, and \`R2_BUCKET\` only in Backend envs.
|
|
196
|
-
- If you use a public CDN/custom domain for uploaded files, add that URL to your own app config before exposing uploads broadly.
|
|
197
|
-
|
|
198
|
-
5. Vercel web/API deploys
|
|
199
|
-
- Monorepo docs: https://vercel.com/docs/monorepos
|
|
200
|
-
- Monorepo FAQ for source outside root: https://vercel.com/docs/monorepos/monorepo-faq
|
|
201
|
-
- Import this same Git repository twice. Use \`Frontend\` as the root directory for the Expo web project and \`Backend\` as the root directory for the Fastify API project.
|
|
202
|
-
- Enable access to source files outside each project root so workspace packages under \`packages/*\` are available during builds.
|
|
203
|
-
- Frontend build command: \`pnpm build:web\`; output directory: \`dist\`.
|
|
204
|
-
- Backend build command: \`pnpm build\`; Vercel detects \`Backend/src/index.ts\` as the Fastify entrypoint.
|
|
205
|
-
|
|
206
|
-
6. EAS native app builds
|
|
207
|
-
- EAS docs: https://docs.expo.dev/eas/
|
|
208
|
-
- Store submission docs: https://docs.expo.dev/deploy/submit-to-app-stores/
|
|
209
|
-
- Use \`Frontend\` as the Expo project root for iOS and Android builds. Vercel deploys the web export from the same source.
|
|
210
|
-
|
|
211
|
-
7. Chrome Web Store
|
|
212
|
-
- WXT publishing: https://wxt.dev/guide/essentials/publishing.html
|
|
213
|
-
- Chrome publishing: https://developer.chrome.com/docs/webstore/publish
|
|
214
|
-
- Build with \`pnpm extension:zip\`, then upload \`Extension/.output/*-chrome.zip\` in the Chrome Web Store Developer Dashboard.
|
|
215
|
-
|
|
216
|
-
## Setup Notes
|
|
217
|
-
|
|
218
|
-
1. Copy \`.env.example\` into the runtime env files your apps need and fill in provider values.
|
|
219
|
-
2. Review \`install-skills.sh\` and run the listed skill commands manually so you can choose scope and agent targets.
|
|
220
|
-
3. Add the real provider configuration for Clerk, RevenueCat, Stripe web billing, Neon, and R2 where the scaffolded helper files indicate.
|
|
221
|
-
4. Use \`stack.json\` when debugging generated projects; it records the verified dependency manifest used by this init run.
|
|
222
|
-
5. Review \`PRODUCTION.md\` before connecting live provider projects.
|
|
223
|
-
6. Run database generation and migrations from the shared DB package:
|
|
224
|
-
|
|
225
|
-
\`\`\`bash
|
|
226
|
-
pnpm db:generate
|
|
227
|
-
pnpm db:migrate
|
|
228
|
-
\`\`\`
|
|
581
|
+
function collectSqlFiles(directory, relativeDirectory = '') {
|
|
582
|
+
const files = [];
|
|
583
|
+
for (const entry of readdirSync(directory, { withFileTypes: true })) {
|
|
584
|
+
const relativePath = path.posix.join(relativeDirectory, entry.name);
|
|
585
|
+
if (entry.isDirectory()) files.push(...collectSqlFiles(path.join(directory, entry.name), relativePath));
|
|
586
|
+
else if (entry.isFile() && entry.name.endsWith('.sql')) files.push(path.posix.join('packages/db/migrations', relativePath));
|
|
587
|
+
}
|
|
588
|
+
return files.sort();
|
|
589
|
+
}
|
|
229
590
|
|
|
230
|
-
|
|
591
|
+
const sqlFiles = collectSqlFiles(migrationsRoot);
|
|
592
|
+
if (sqlFiles.length === 0) {
|
|
593
|
+
throw new Error('No database migration SQL is committed. Run \`pnpm db:generate\`, review packages/db/migrations, and commit the generated migration before verification.');
|
|
594
|
+
}
|
|
231
595
|
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
\`\`\`
|
|
596
|
+
const gitRoot = spawnSync('git', ['rev-parse', '--show-toplevel'], {
|
|
597
|
+
cwd: projectRoot,
|
|
598
|
+
encoding: 'utf8',
|
|
599
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
600
|
+
});
|
|
238
601
|
|
|
239
|
-
|
|
602
|
+
if (gitRoot.status === 0) {
|
|
603
|
+
const repositoryRoot = String(gitRoot.stdout).trim();
|
|
604
|
+
const tracked = spawnSync('git', ['ls-files', '--full-name', '-z', '--', 'packages/db/migrations'], {
|
|
605
|
+
cwd: projectRoot,
|
|
606
|
+
encoding: 'utf8',
|
|
607
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
608
|
+
});
|
|
609
|
+
if (tracked.status !== 0) {
|
|
610
|
+
throw new Error('Unable to inspect committed database migrations: ' + String(tracked.stderr).trim());
|
|
611
|
+
}
|
|
612
|
+
const trackedFiles = new Set(String(tracked.stdout)
|
|
613
|
+
.split('\\0')
|
|
614
|
+
.filter(Boolean)
|
|
615
|
+
.map((entry) => path.resolve(repositoryRoot, entry)));
|
|
616
|
+
const untrackedSql = sqlFiles.filter((entry) => !trackedFiles.has(path.resolve(projectRoot, entry)));
|
|
617
|
+
if (untrackedSql.length > 0) {
|
|
618
|
+
throw new Error('Database migration SQL must be tracked by Git before verification: ' + untrackedSql.join(', '));
|
|
619
|
+
}
|
|
620
|
+
} else if (process.env.CI) {
|
|
621
|
+
throw new Error('CI must run database migration verification inside a Git worktree.');
|
|
622
|
+
}
|
|
240
623
|
|
|
241
|
-
|
|
242
|
-
pnpm dev:extension
|
|
243
|
-
pnpm extension:zip
|
|
244
|
-
\`\`\`
|
|
624
|
+
console.log('Database migration baseline is present' + (gitRoot.status === 0 ? ' and tracked by Git.' : '.'));
|
|
245
625
|
`);
|
|
246
626
|
}
|
|
247
|
-
function
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
627
|
+
function isRecordedFileUnmodified(root, manifest, relativePath) {
|
|
628
|
+
if (!manifest)
|
|
629
|
+
return true;
|
|
630
|
+
const record = manifest.files[relativePath];
|
|
631
|
+
if (!record?.hash)
|
|
632
|
+
return false;
|
|
633
|
+
const filePath = path.join(root, relativePath);
|
|
634
|
+
return pathEntryExists(filePath) && hashContent(readFileSync(filePath)) === record.hash;
|
|
635
|
+
}
|
|
636
|
+
function writeRootFiles(root, options, mode, currentRoot, manifest) {
|
|
637
|
+
const packageUnmodified = isRecordedFileUnmodified(currentRoot, manifest, 'package.json');
|
|
638
|
+
const workspaceUnmodified = manifest !== undefined
|
|
639
|
+
&& isRecordedFileUnmodified(currentRoot, manifest, 'pnpm-workspace.yaml');
|
|
640
|
+
const previousOptions = manifest
|
|
641
|
+
? { ...options, ...selectionsFromModules(manifest.modules), modules: [...manifest.modules] }
|
|
642
|
+
: undefined;
|
|
643
|
+
const previousPackage = previousOptions ? desiredRootPackage(previousOptions) : undefined;
|
|
644
|
+
writeRootPackage(root, options, mode, packageUnmodified, previousPackage);
|
|
645
|
+
const workspacePackages = [
|
|
646
|
+
Object.values(options.apps).some(Boolean) ? 'apps/*' : null,
|
|
647
|
+
options.apps.api || options.features.database ? 'packages/*' : null,
|
|
648
|
+
].filter((value) => value !== null);
|
|
649
|
+
mergeWorkspaceFile(root, workspacePackages, desiredWorkspacePolicy(), workspaceUnmodified);
|
|
650
|
+
mergeJsonConfig(root, 'turbo.json', desiredTurboConfig(), desiredTurboConfig(), true);
|
|
651
|
+
mergeJsonConfig(root, 'vercel.json', desiredVercelConfig(options), previousOptions ? desiredVercelConfig(previousOptions) : {}, true);
|
|
652
|
+
appendGitignore(root, [
|
|
653
|
+
'node_modules',
|
|
654
|
+
'.turbo',
|
|
655
|
+
'.next',
|
|
656
|
+
'.output',
|
|
657
|
+
'.wxt',
|
|
658
|
+
'.expo',
|
|
659
|
+
'coverage',
|
|
660
|
+
'dist',
|
|
661
|
+
'release',
|
|
662
|
+
'.env',
|
|
663
|
+
'.env.*',
|
|
664
|
+
'!.env.example',
|
|
665
|
+
'*.tsbuildinfo',
|
|
666
|
+
]);
|
|
667
|
+
writeRootEnv(root, options);
|
|
668
|
+
writeDatabaseVerificationScript(root, options);
|
|
669
|
+
const vercelIgnore = path.join(root, '.vercelignore');
|
|
670
|
+
const currentIgnore = pathEntryExists(vercelIgnore) ? readFileSync(vercelIgnore, 'utf8') : '';
|
|
671
|
+
const ignoreLines = [...new Set([...currentIgnore.split('\n').filter(Boolean), 'apps/extension/.output', 'apps/mobile/dist', 'apps/desktop/release', 'apps/assets-private-proxy'])];
|
|
672
|
+
writeFile(vercelIgnore, ignoreLines.join('\n') + '\n');
|
|
673
|
+
writeFile(path.join(root, '.github/workflows/anhedral-ci.yml'), generatedCi(options));
|
|
674
|
+
}
|
|
675
|
+
function enabledModuleNames(options) {
|
|
676
|
+
return resolveModules(options.modules).resolvedModules;
|
|
677
|
+
}
|
|
678
|
+
function writeProjectDocs(root, options, includeUserDocs) {
|
|
679
|
+
const modules = enabledModuleNames(options);
|
|
680
|
+
const storageBucketName = r2BucketName(options.projectName);
|
|
681
|
+
const commands = [
|
|
682
|
+
'pnpm install',
|
|
683
|
+
options.apps.api ? 'cp apps/api/.env.example apps/api/.env' : null,
|
|
684
|
+
options.features.database ? 'cp packages/db/.env.example packages/db/.env' : null,
|
|
685
|
+
options.apps.web ? 'cp apps/web/.env.example apps/web/.env.local' : null,
|
|
686
|
+
options.apps.mobile ? 'cp apps/mobile/.env.example apps/mobile/.env' : null,
|
|
687
|
+
options.apps.desktop ? 'cp apps/desktop/.env.example apps/desktop/.env' : null,
|
|
688
|
+
options.apps.extension ? 'cp apps/extension/.env.example apps/extension/.env' : null,
|
|
689
|
+
options.features.database ? 'pnpm db:generate' : null,
|
|
690
|
+
options.features.database ? 'git add packages/db/migrations' : null,
|
|
691
|
+
'pnpm verify',
|
|
692
|
+
options.features.database ? 'pnpm db:migrate' : null,
|
|
693
|
+
].filter((value) => value !== null).join('\n');
|
|
694
|
+
const deploymentRows = [
|
|
695
|
+
options.apps.web || options.apps.api ? '| Web/API | Vercel Git integration | Import this repository once; branch pushes create previews and the production branch deploys automatically. |' : null,
|
|
696
|
+
options.apps.mobile ? '| Mobile | EAS Build + App Store Connect + Google Play Console | EAS creates signed binaries; Apple TestFlight/App Review and Google testing tracks/store review control release. |' : null,
|
|
697
|
+
options.features.database ? '| Database | Neon | Provision the project, set `DATABASE_URL`, review/apply Drizzle migrations, and use separate branches or projects for preview and production. |' : null,
|
|
698
|
+
options.features.storage ? '| Object storage | Private Cloudflare R2 + `assets-private-proxy` Worker | Authenticated uploads use presigned R2 URLs; the Worker streams known-key GET/HEAD downloads through `assets.<domain>` while direct bucket access stays disabled. |' : null,
|
|
699
|
+
options.apps.extension ? '| Chrome extension | Chrome Web Store | Build the production ZIP, test it as an unpublished/trusted-tester item, complete privacy disclosures, and submit it for review. |' : null,
|
|
700
|
+
options.apps.desktop ? '| Desktop | electron-builder artifacts | Build and sign on each target OS, then publish through the release channel chosen for the product. |' : null,
|
|
701
|
+
].filter((value) => value !== null).join('\n');
|
|
702
|
+
const deploymentCommands = [
|
|
703
|
+
options.apps.web || options.apps.api ? 'pnpm deploy:vercel:link' : null,
|
|
704
|
+
options.apps.web || options.apps.api ? 'pnpm deploy:vercel:preview' : null,
|
|
705
|
+
options.apps.web || options.apps.api ? 'pnpm deploy:vercel:production' : null,
|
|
706
|
+
options.apps.mobile ? 'pnpm mobile:eas:login' : null,
|
|
707
|
+
options.apps.mobile ? 'pnpm mobile:build:internal:ios' : null,
|
|
708
|
+
options.apps.mobile ? 'pnpm mobile:build:internal:android' : null,
|
|
709
|
+
options.features.database ? `pnpm neon:project:create -- --name ${options.projectName}` : null,
|
|
710
|
+
options.features.storage ? 'pnpm r2:bucket:create' : null,
|
|
711
|
+
options.features.storage ? 'pnpm assets:proxy:check' : null,
|
|
712
|
+
options.features.storage ? 'pnpm assets:proxy:deploy' : null,
|
|
713
|
+
options.apps.extension ? 'pnpm extension:zip' : null,
|
|
714
|
+
].filter((value) => value !== null).join('\n');
|
|
715
|
+
const sourceRows = [
|
|
716
|
+
options.apps.web ? '| Web frontend | `apps/web/app/`, `apps/web/components/`, `apps/web/lib/` | Next.js App Router pages, layouts, components, and web utilities. |' : null,
|
|
717
|
+
options.apps.mobile ? '| Mobile frontend | `apps/mobile/app/`, `apps/mobile/components/` | Expo Router screens, layouts, and native UI. |' : null,
|
|
718
|
+
options.apps.api ? '| Backend API | `apps/api/src/routes/`, `apps/api/src/services/` | Fastify routes and server-only business/provider code. |' : null,
|
|
719
|
+
options.apps.desktop ? '| Desktop app | `apps/desktop/src/renderer/`, `apps/desktop/src/main/` | React UI and privileged Electron main-process code. |' : null,
|
|
720
|
+
options.apps.extension ? '| Browser extension | `apps/extension/entrypoints/`, `apps/extension/components/` | WXT entrypoints and extension UI. |' : null,
|
|
721
|
+
options.apps.api ? '| Shared API contracts | `packages/contracts/src/` | Zod request and response schemas imported by clients and the API. |' : null,
|
|
722
|
+
options.apps.api ? '| Typed API client | `packages/api-client/src/` | Shared fetch client used by every selected frontend. |' : null,
|
|
723
|
+
options.features.database ? '| Database | `packages/db/src/schema.ts`, `packages/db/migrations/` | Drizzle tables, queries, and reviewed SQL migrations for managed Neon Postgres. |' : null,
|
|
724
|
+
].filter((value) => value !== null).join('\n');
|
|
725
|
+
const moduleCommands = [
|
|
726
|
+
options.apps.web ? '- Web: `pnpm dev:web`' : null,
|
|
727
|
+
options.apps.mobile ? '- Mobile: `pnpm dev:mobile`' : null,
|
|
728
|
+
options.apps.api ? '- API: `pnpm dev:api`' : null,
|
|
729
|
+
options.apps.desktop ? '- Desktop: `pnpm dev:desktop`' : null,
|
|
730
|
+
options.apps.extension ? '- Extension: `pnpm dev:extension`' : null,
|
|
731
|
+
].filter((value) => value !== null).join('\n');
|
|
732
|
+
const toolRows = [
|
|
733
|
+
options.apps.web ? '| Next.js | Web routes and rendering | `apps/web` | https://nextjs.org/docs/app/getting-started |' : null,
|
|
734
|
+
options.apps.mobile ? '| Expo Router | iOS and Android app | `apps/mobile` | https://docs.expo.dev/router/introduction/ |' : null,
|
|
735
|
+
options.apps.api ? '| Fastify | HTTP API | `apps/api` | https://fastify.dev/docs/latest/ |' : null,
|
|
736
|
+
options.features.database ? '| Neon | Managed Postgres; no local Postgres | `DATABASE_URL` | https://neon.com/docs/introduction |' : null,
|
|
737
|
+
options.features.database ? '| Drizzle | SQL schema, queries, migrations | `packages/db` | https://orm.drizzle.team/docs/get-started |' : null,
|
|
738
|
+
options.features.auth ? '| Clerk | Identity and sessions | generated auth files | https://clerk.com/docs/getting-started/quickstart/overview |' : null,
|
|
739
|
+
options.features.storage ? '| Cloudflare R2 | Private object storage | upload API and `apps/assets-private-proxy` | https://developers.cloudflare.com/r2/ |' : null,
|
|
740
|
+
options.features.billing ? '| RevenueCat | Subscription authority | API and native client | https://www.revenuecat.com/docs |' : null,
|
|
741
|
+
options.features.billing ? '| Ably | Realtime invalidation | `packages/realtime` | https://ably.com/docs |' : null,
|
|
742
|
+
options.apps.desktop ? '| Electron | Desktop runtime | `apps/desktop` | https://www.electronjs.org/docs/latest/ |' : null,
|
|
743
|
+
options.apps.extension ? '| WXT | Browser extension tooling | `apps/extension` | https://wxt.dev/guide/installation.html |' : null,
|
|
744
|
+
options.apps.web || options.apps.desktop || options.apps.extension ? '| shadcn/ui | Source-owned DOM UI | each DOM app\'s `components/ui` | https://ui.shadcn.com/docs |' : null,
|
|
745
|
+
'| Turborepo | Workspace tasks | root `turbo.json` | https://turborepo.com/docs |',
|
|
746
|
+
].filter((value) => value !== null).join('\n');
|
|
747
|
+
const developmentSteps = [
|
|
748
|
+
options.apps.api ? 'Define shared Zod schemas in `packages/contracts/src/` so the network boundary has one definition.' : null,
|
|
749
|
+
options.features.database ? 'Define persistent state in `packages/db/src/schema.ts`. Run `pnpm db:generate`, review the SQL, and commit it. This project uses managed Neon—do not add a local Postgres container.' : null,
|
|
750
|
+
options.apps.api ? 'Put business logic and provider calls in `apps/api/src/services/`. Keep `apps/api/src/routes/` focused on auth, validation, calling the service, and returning the contract.' : null,
|
|
751
|
+
options.apps.api ? 'Expose client-safe methods from `packages/api-client/src/`; never import API implementation files into a frontend.' : null,
|
|
752
|
+
options.apps.web ? 'Add web routes in `apps/web/app/<route>/page.tsx` and reusable UI in `apps/web/components/`. Use a client component only for browser state, events, or hooks.' : null,
|
|
753
|
+
options.apps.mobile ? 'Add mobile routes in `apps/mobile/app/` and reusable native UI in `apps/mobile/components/`. Keep platform-only APIs in platform-specific modules.' : null,
|
|
754
|
+
'Test the smallest affected package first, then run `pnpm verify`.',
|
|
755
|
+
].filter((value) => value !== null).map((value, index) => `${index + 1}. ${value}`).join('\n');
|
|
756
|
+
const commonTaskSections = [
|
|
757
|
+
options.apps.web ? `### Add a web page
|
|
758
|
+
|
|
759
|
+
Create \`apps/web/app/<route>/page.tsx\`. Follow Next.js App Router conventions directly. Put reusable components under \`apps/web/components/<feature>/\` and web-only helpers under \`apps/web/lib/\`.` : null,
|
|
760
|
+
options.apps.api ? `### Add an API endpoint
|
|
761
|
+
|
|
762
|
+
Define its Zod contract in \`packages/contracts/src/\`, add a service function in \`apps/api/src/services/\`, and register a Fastify route in \`apps/api/src/routes/\`. Authenticate on the server and derive the user ID from the verified session.` : null,
|
|
763
|
+
options.features.database ? `### Change the database
|
|
764
|
+
|
|
765
|
+
Edit \`packages/db/src/schema.ts\`, then run:
|
|
292
766
|
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
767
|
+
\`\`\`sh
|
|
768
|
+
pnpm db:generate
|
|
769
|
+
pnpm verify:db
|
|
770
|
+
pnpm db:migrate
|
|
771
|
+
\`\`\`
|
|
297
772
|
|
|
298
|
-
|
|
773
|
+
Review generated SQL before applying it. \`DATABASE_URL\` points to a managed Neon branch or project; there is intentionally no local Postgres service.` : null,
|
|
774
|
+
options.features.auth ? `### Use authentication
|
|
299
775
|
|
|
300
|
-
|
|
776
|
+
Frontend applications use their generated Clerk provider and hooks. The API verifies Clerk sessions. Public keys may use a framework public environment prefix; \`CLERK_SECRET_KEY\` remains in the API environment only.` : null,
|
|
777
|
+
options.features.storage ? `### Upload a file
|
|
301
778
|
|
|
302
|
-
|
|
779
|
+
Use \`@shared/api-client\`. The API authorizes the user and creates a short-lived signed R2 upload; the client uploads directly and confirms through the API. Never put R2 credentials in a client or make the bucket public.` : null,
|
|
780
|
+
].filter((value) => value !== null).join('\n\n');
|
|
781
|
+
const dependencyLines = [
|
|
782
|
+
options.apps.api ? 'frontend apps -> @shared/api-client -> HTTP -> apps/api' : null,
|
|
783
|
+
options.apps.api ? 'frontend apps -> @shared/contracts <- apps/api' : null,
|
|
784
|
+
options.apps.api && options.features.database ? 'apps/api -> @shared/db -> managed Neon Postgres' : null,
|
|
785
|
+
].filter((value) => value !== null).join('\n');
|
|
786
|
+
const uiTaskSection = Object.values(options.apps).some(Boolean) && (options.apps.web || options.apps.mobile || options.apps.desktop || options.apps.extension)
|
|
787
|
+
? `### Add UI primitives
|
|
303
788
|
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
-
|
|
789
|
+
\`\`\`sh
|
|
790
|
+
anhedral ui add dialog
|
|
791
|
+
${options.apps.web ? 'anhedral ui add data-table --target web\n' : ''}\`\`\`
|
|
307
792
|
|
|
308
|
-
|
|
793
|
+
DOM apps receive source-owned shadcn/ui files. Mobile receives React Native Reusables files. Customize those files normally.`
|
|
794
|
+
: '';
|
|
795
|
+
if (includeUserDocs) {
|
|
796
|
+
writeFile(path.join(root, 'README.md'), `# ${markdownHeading(options.displayName)}
|
|
309
797
|
|
|
310
|
-
|
|
798
|
+
This is a complete, readable TypeScript product stack generated by Anhedral ${GENERATOR_VERSION}. Anhedral assembled and connected the tools; application code remains normal framework code.
|
|
311
799
|
|
|
312
|
-
|
|
800
|
+
## Start here
|
|
313
801
|
|
|
314
802
|
\`\`\`sh
|
|
315
803
|
pnpm install
|
|
316
804
|
pnpm dev
|
|
317
805
|
\`\`\`
|
|
318
806
|
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
\`\`\`sh
|
|
322
|
-
pnpm dev:frontend
|
|
323
|
-
pnpm dev:backend
|
|
324
|
-
pnpm dev:extension
|
|
325
|
-
\`\`\`
|
|
326
|
-
|
|
327
|
-
Use these before deploy:
|
|
328
|
-
|
|
329
|
-
\`\`\`sh
|
|
330
|
-
pnpm verify
|
|
331
|
-
pnpm verify:frontend
|
|
332
|
-
pnpm verify:backend
|
|
333
|
-
pnpm verify:extension
|
|
334
|
-
\`\`\`
|
|
335
|
-
|
|
336
|
-
Database workflow:
|
|
337
|
-
|
|
338
|
-
\`\`\`sh
|
|
339
|
-
pnpm db:generate
|
|
340
|
-
pnpm db:migrate
|
|
341
|
-
pnpm db:studio
|
|
342
|
-
pnpm db:check
|
|
343
|
-
\`\`\`
|
|
807
|
+
\`pnpm dev\` starts every selected application. To run one surface:
|
|
344
808
|
|
|
345
|
-
|
|
809
|
+
${moduleCommands}
|
|
346
810
|
|
|
347
|
-
|
|
811
|
+
There is no hidden Anhedral application runtime. Open the framework directory you want and write ordinary TypeScript there.
|
|
348
812
|
|
|
349
|
-
##
|
|
813
|
+
## Where to write code
|
|
350
814
|
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
- Extension: \`VITE_API_URL\`, \`VITE_CLERK_PUBLISHABLE_KEY\`, and optionally \`VITE_CRX_PUBLIC_KEY\`.
|
|
355
|
-
- EAS: add native app public keys with \`eas secret:create\` or the EAS dashboard.
|
|
815
|
+
| Concern | Location | What belongs there |
|
|
816
|
+
| --- | --- | --- |
|
|
817
|
+
${sourceRows}
|
|
356
818
|
|
|
357
|
-
|
|
819
|
+
${options.apps.api ? 'For an end-to-end feature, define shared contracts first, implement server and persistence behavior, expose it through the typed client, then build each frontend.' : 'Build product features directly inside each selected application using its native framework conventions.'} Read [docs/DEVELOPMENT.md](docs/DEVELOPMENT.md) for concrete recipes and [docs/STACK.md](docs/STACK.md) for every selected tool and its official documentation.
|
|
358
820
|
|
|
359
|
-
|
|
821
|
+
## Selected modules
|
|
360
822
|
|
|
361
|
-
|
|
823
|
+
${modules.map((moduleName) => `- \`${moduleName}\``).join('\n')}
|
|
362
824
|
|
|
363
|
-
|
|
364
|
-
- https://orm.drizzle.team/docs/tutorials/drizzle-with-neon
|
|
825
|
+
## UI and customization
|
|
365
826
|
|
|
366
|
-
|
|
827
|
+
DOM clients use source-owned shadcn/ui. Expo uses React Native Reusables with ${options.nativeStyling}. Add components with \`anhedral ui add <component>\`; use \`--target\` when a component belongs to one client. Customize the resulting source normally.
|
|
367
828
|
|
|
368
|
-
|
|
369
|
-
2. Copy the pooled connection string.
|
|
370
|
-
3. Set \`DATABASE_URL\` in the root \`.env\`, \`Backend/.env\`, and the Backend Vercel project.
|
|
371
|
-
4. Run:
|
|
829
|
+
## Environment and first verification
|
|
372
830
|
|
|
373
831
|
\`\`\`sh
|
|
374
|
-
|
|
375
|
-
pnpm db:migrate
|
|
832
|
+
${commands}
|
|
376
833
|
\`\`\`
|
|
377
834
|
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
Docs:
|
|
835
|
+
## Deployment
|
|
381
836
|
|
|
382
|
-
-
|
|
383
|
-
- https://clerk.com/docs/quickstarts/get-started-with-expo
|
|
837
|
+
Only selected surfaces and providers contribute deployment scripts. Exact-version deployment CLIs run on demand instead of inflating the application lockfile.
|
|
384
838
|
|
|
385
|
-
|
|
839
|
+
| Selection | Delivery target | Strategy |
|
|
840
|
+
| --- | --- | --- |
|
|
841
|
+
${deploymentRows}
|
|
386
842
|
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
4. Set \`VITE_CLERK_PUBLISHABLE_KEY\` in \`Extension/.env\`.
|
|
391
|
-
5. Add allowed origins for local Expo web, the deployed Frontend Vercel domain, and the Chrome extension origin after the extension id is stable.
|
|
392
|
-
6. Configure native redirect/deep-link settings for the Expo scheme in \`Frontend/app.json\`.
|
|
393
|
-
|
|
394
|
-
### RevenueCat + Stripe
|
|
843
|
+
\`\`\`sh
|
|
844
|
+
${deploymentCommands}
|
|
845
|
+
\`\`\`
|
|
395
846
|
|
|
396
|
-
|
|
847
|
+
Read \`PRODUCTION.md\` before creating accounts or production resources. Generated ownership and tool versions are recorded in \`anhedral.json\`. Run \`anhedral doctor\` before structural changes and preview them with \`--dry-run\`.
|
|
848
|
+
`);
|
|
849
|
+
}
|
|
850
|
+
writeFile(path.join(root, 'docs/DEVELOPMENT.md'), `# Developing ${markdownHeading(options.displayName)}
|
|
397
851
|
|
|
398
|
-
|
|
399
|
-
- https://www.revenuecat.com/docs/web/integrations/stripe
|
|
400
|
-
- https://docs.stripe.com/keys
|
|
852
|
+
Anhedral generated this stack; it does not replace the frameworks inside it. Use official framework APIs and keep product logic in ordinary source files.
|
|
401
853
|
|
|
402
|
-
|
|
854
|
+
## End-to-end feature loop
|
|
403
855
|
|
|
404
|
-
|
|
405
|
-
2. Create an entitlement named \`pro\`.
|
|
406
|
-
3. Create iOS, Android, and Web apps in RevenueCat.
|
|
407
|
-
4. Copy the public SDK keys into \`EXPO_PUBLIC_RC_API_KEY_IOS\`, \`EXPO_PUBLIC_RC_API_KEY_ANDROID\`, and \`EXPO_PUBLIC_RC_WEB_API_KEY\`.
|
|
408
|
-
5. Set \`EXPO_PUBLIC_RC_ENTITLEMENT_ID=pro\`.
|
|
409
|
-
6. Connect Stripe as the RevenueCat web billing source.
|
|
410
|
-
7. Set \`RC_SECRET_API_KEY\` and \`RC_WEBHOOK_SECRET\` only in Backend envs.
|
|
411
|
-
8. Configure the RevenueCat webhook URL as \`https://<backend-domain>/webhooks/revenuecat\`.
|
|
856
|
+
${developmentSteps}
|
|
412
857
|
|
|
413
|
-
|
|
858
|
+
## Common tasks
|
|
414
859
|
|
|
415
|
-
|
|
860
|
+
${commonTaskSections}
|
|
416
861
|
|
|
417
|
-
|
|
418
|
-
- https://developers.cloudflare.com/r2/api/tokens/
|
|
862
|
+
${uiTaskSection}
|
|
419
863
|
|
|
420
|
-
|
|
864
|
+
### Add another app surface
|
|
421
865
|
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
5. Configure a public bucket URL or custom domain if uploaded assets need public CDN delivery.
|
|
866
|
+
\`\`\`sh
|
|
867
|
+
anhedral add mobile --dry-run
|
|
868
|
+
anhedral add mobile
|
|
869
|
+
\`\`\`
|
|
427
870
|
|
|
428
|
-
|
|
871
|
+
Anhedral refuses ownership conflicts instead of overwriting product changes. Run \`anhedral doctor\` when an add cannot proceed.
|
|
429
872
|
|
|
430
|
-
|
|
873
|
+
## Verification
|
|
431
874
|
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
875
|
+
- While iterating, run the affected package's typecheck or tests.
|
|
876
|
+
- Before handoff, run \`pnpm verify\`.
|
|
877
|
+
- Before generation, run \`anhedral doctor\` and use \`--dry-run\`.
|
|
878
|
+
- For schema changes, commit reviewed migration SQL and run \`pnpm verify:db\`.
|
|
879
|
+
`);
|
|
880
|
+
writeFile(path.join(root, 'docs/STACK.md'), `# Stack guide
|
|
436
881
|
|
|
437
|
-
|
|
438
|
-
- Root Directory: \`Backend\`
|
|
439
|
-
- Build command: \`pnpm build\`
|
|
440
|
-
- Fastify entrypoint: \`src/index.ts\`
|
|
882
|
+
This maps generated source to upstream documentation. Anhedral owns initial integration and safe incremental generation. Each framework owns its runtime and programming model.
|
|
441
883
|
|
|
442
|
-
|
|
884
|
+
| Tool | Responsibility | Generated location | Official documentation |
|
|
885
|
+
| --- | --- | --- | --- |
|
|
886
|
+
${toolRows}
|
|
443
887
|
|
|
444
|
-
|
|
888
|
+
## Dependency direction
|
|
445
889
|
|
|
446
|
-
\`\`\`
|
|
447
|
-
|
|
448
|
-
pnpm dlx eas-cli@latest login
|
|
449
|
-
pnpm dlx eas-cli@latest init
|
|
450
|
-
pnpm dlx eas-cli@latest build --platform all --profile production
|
|
451
|
-
pnpm dlx eas-cli@latest submit --platform all --latest --profile production
|
|
890
|
+
\`\`\`text
|
|
891
|
+
${dependencyLines || 'selected applications are independent framework projects'}
|
|
452
892
|
\`\`\`
|
|
453
893
|
|
|
454
|
-
|
|
894
|
+
Clients may import contracts and the API client. They must not import API services, database connections, or server environment modules. Provider secrets terminate at the API or provider-specific Worker.
|
|
455
895
|
|
|
456
|
-
|
|
457
|
-
pnpm extension:zip
|
|
458
|
-
\`\`\`
|
|
459
|
-
|
|
460
|
-
Upload \`Extension/.output/*-chrome.zip\` to the Chrome Web Store Developer Dashboard.
|
|
461
|
-
|
|
462
|
-
## Production Checklist
|
|
463
|
-
|
|
464
|
-
- Replace every \`*_placeholder\` value before production deploy.
|
|
465
|
-
- Keep server secrets out of Frontend, Extension, and EAS public envs.
|
|
466
|
-
- Confirm Clerk works on local web, Vercel web, iOS, Android, and the Chrome extension.
|
|
467
|
-
- Confirm RevenueCat returns the \`pro\` entitlement after Stripe web purchase and native store purchase.
|
|
468
|
-
- Confirm \`pnpm db:migrate\` has run against the production Neon database.
|
|
469
|
-
- Confirm R2 upload, signed URL retrieval, and deletion work from the deployed Backend domain.
|
|
470
|
-
- Confirm both Vercel projects can resolve \`packages/*\` workspace packages.
|
|
471
|
-
- Confirm the Chrome extension ZIP is tested locally with \`chrome://extensions\` before Chrome Web Store upload.
|
|
472
|
-
|
|
473
|
-
## Relevant Docs
|
|
474
|
-
|
|
475
|
-
- [Vercel monorepos](https://vercel.com/docs/monorepos)
|
|
476
|
-
- [Vercel monorepo FAQ](https://vercel.com/docs/monorepos/monorepo-faq)
|
|
477
|
-
- [Expo web publishing](https://docs.expo.dev/guides/publishing-websites/)
|
|
478
|
-
- [Expo EAS](https://docs.expo.dev/eas/)
|
|
479
|
-
- [Expo store submissions](https://docs.expo.dev/deploy/submit-to-app-stores/)
|
|
480
|
-
- [Clerk with Expo](https://docs.expo.dev/guides/using-clerk/)
|
|
481
|
-
- [Clerk Expo quickstart](https://clerk.com/docs/quickstarts/get-started-with-expo)
|
|
482
|
-
- [Neon connection strings](https://neon.com/docs/get-started-with-neon/connect-neon)
|
|
483
|
-
- [Drizzle with Neon](https://orm.drizzle.team/docs/tutorials/drizzle-with-neon)
|
|
484
|
-
- [RevenueCat Web](https://www.revenuecat.com/docs/web/overview)
|
|
485
|
-
- [RevenueCat Stripe Billing](https://www.revenuecat.com/docs/web/integrations/stripe)
|
|
486
|
-
- [Stripe API keys](https://docs.stripe.com/keys)
|
|
487
|
-
- [Cloudflare R2 S3 API](https://developers.cloudflare.com/r2/get-started/s3/)
|
|
488
|
-
- [Cloudflare R2 API tokens](https://developers.cloudflare.com/r2/api/tokens/)
|
|
489
|
-
- [WXT publishing](https://wxt.dev/guide/essentials/publishing.html)
|
|
490
|
-
- [Chrome Web Store publishing](https://developer.chrome.com/docs/webstore/publish)
|
|
896
|
+
\`anhedral add\` adds modules and integration files. \`anhedral ui add\` adds source-owned UI. \`anhedral doctor\` checks recorded ownership. Product features, models, pages, routes, and services remain developer-owned TypeScript.
|
|
491
897
|
`);
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
'
|
|
506
|
-
'
|
|
507
|
-
'
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
898
|
+
if (includeUserDocs) {
|
|
899
|
+
const productionItems = [
|
|
900
|
+
options.apps.api ? '- Keep `ANHEDRAL_DEMO=false` in production.' : null,
|
|
901
|
+
options.apps.api ? '- Set `TRUST_PROXY_HOPS` only to the number of trusted reverse-proxy hops.' : null,
|
|
902
|
+
options.apps.api ? '- Store server secrets only in the API deployment environment.' : null,
|
|
903
|
+
options.apps.api || options.apps.web ? '- Select the Vercel Services framework preset and deploy from the repository root.' : null,
|
|
904
|
+
options.apps.api && options.apps.web ? '- Keep the top-level `/api/(.*)` service rewrite before the web catch-all rewrite.' : null,
|
|
905
|
+
options.apps.api && options.apps.web ? '- The web client defaults to same-origin `/api` in production; override `NEXT_PUBLIC_API_URL` only when the API uses another origin.' : null,
|
|
906
|
+
options.features.storage ? '- Set a strong `CRON_SECRET` and verify Vercel invokes `/api/internal/storage/cleanup` on schedule.' : null,
|
|
907
|
+
options.features.billing ? '- Configure `ABLY_API_KEY`, set a strong `CRON_SECRET`, and verify Vercel invokes `/api/internal/realtime/flush` every five minutes to retry the transactional outbox.' : null,
|
|
908
|
+
options.features.billing ? '- Use a dedicated RevenueCat secret REST API key with customer-read access; keep it server-only and rotate it independently from the 32+ character webhook authorization secret.' : null,
|
|
909
|
+
options.features.storage ? '- List the live R2 CORS policy, merge every exact browser origin into `cloudflare/r2-cors.template.json`, then apply the complete replacement policy and verify preflight plus signed PUT.' : null,
|
|
910
|
+
options.features.storage ? '- Configure an R2 lifecycle rule for the `storage/staging/` prefix as a backstop, with an age longer than the application cleanup grace period.' : null,
|
|
911
|
+
options.features.database ? '- Commit every reviewed Drizzle SQL migration and its metadata with the schema change; `pnpm verify:db` rejects a missing or untracked SQL baseline and validates migration history.' : null,
|
|
912
|
+
options.features.database ? '- Generated CI runs `pnpm db:generate` and fails when `packages/db/migrations` changes, preventing schema changes without a matching migration.' : null,
|
|
913
|
+
'- Run `pnpm verify` before deployment.',
|
|
914
|
+
'- Run `anhedral doctor` before incremental generation.',
|
|
915
|
+
].filter((item) => item !== null);
|
|
916
|
+
const productionSections = [
|
|
917
|
+
options.apps.web || options.apps.api || options.features.storage ? `## Domain registration and Cloudflare control plane
|
|
918
|
+
|
|
919
|
+
Registration and DNS hosting are separate jobs. You can buy the domain at GoDaddy while Cloudflare becomes authoritative DNS immediately; transferring the registrar later is optional.
|
|
920
|
+
|
|
921
|
+
1. Buy the domain at GoDaddy under an organization-controlled account. Enable auto-renewal, MFA, accurate registrant contact details, and record renewal ownership.
|
|
922
|
+
2. Add the domain as a website/zone in Cloudflare. Before changing nameservers, copy every existing DNS record—especially MX, TXT, DKIM, SPF, DMARC, verification, and subdomain records—and disable DNSSEC/DS records at GoDaddy if enabled.
|
|
923
|
+
3. Cloudflare assigns two authoritative nameservers. Replace the GoDaddy nameservers with those exact values, then wait until Cloudflare marks the zone **Active**. Recreate and verify mail and other records before considering the migration complete. Re-enable DNSSEC in Cloudflare after activation.
|
|
924
|
+
4. Optional registrar transfer: after the domain is eligible (commonly not within 60 days of registration, a prior transfer, or certain registrant changes), unlock it at GoDaddy, request its EPP/authorization code, and start **Transfer Domains** in Cloudflare. Approve the transfer and payment. DNS can remain live throughout because Cloudflare was already authoritative.
|
|
925
|
+
5. Keep Cloudflare as the shared domain control plane: DNS and DNSSEC at the zone; Workers and R2 for the asset hostname; and optional Queues, Workflows, Durable Objects, WAF, Turnstile, or other compute/security products when the application actually needs them. Vercel remains the web/API runtime.
|
|
926
|
+
|
|
927
|
+
Use organization-owned Cloudflare and GoDaddy accounts with MFA and least-privilege member roles. Do not confuse changing nameservers (DNS delegation) with transferring the registration (registrar/billing ownership). Follow the current [GoDaddy nameserver instructions](https://help.dc-aws.godaddy.com/help/edit-my-domain-nameservers-664), [GoDaddy transfer-away sequence](https://www.godaddy.com/en-ca/help/transfer-my-domain-away-from-godaddy-3560), [Cloudflare nameserver guidance](https://developers.cloudflare.com/dns/nameservers/update-nameservers/), and [Cloudflare registrar-transfer sequence](https://developers.cloudflare.com/registrar/get-started/transfer-domain-to-cloudflare/).` : null,
|
|
928
|
+
options.apps.web || options.apps.api ? `## Vercel: web and API
|
|
929
|
+
|
|
930
|
+
1. Push the repository to GitHub and import it in Vercel. Choose the **Services** framework preset and keep the repository root as the project root; \`vercel.json\` maps the selected \`apps/web\` and \`apps/api\` services.
|
|
931
|
+
2. Add every required variable from the package-local \`.env.example\` files to Vercel's Development, Preview, and Production environments. Server secrets belong only to the API service. Never put a secret in a \`NEXT_PUBLIC_*\` variable.
|
|
932
|
+
3. Run \`pnpm deploy:vercel:link\` for local CLI access. The normal release path is Git: every non-production branch/PR receives a preview deployment, and merging to the configured production branch creates production automatically. The explicit \`deploy:vercel:preview\` and \`deploy:vercel:production\` scripts are escape hatches for manual releases.
|
|
933
|
+
4. Run \`pnpm deploy:vercel:inspect -- <deployment-url>\` when diagnosing a deployment. Verify health, authentication, scheduled jobs, and provider callbacks in Preview before merging.
|
|
934
|
+
5. Add \`app.example.com\` in Vercel **Project → Settings → Domains** before changing DNS. Inspect it with \`pnpm deploy:vercel:domain:inspect -- app.example.com\`, then create the exact A/CNAME/TXT records Vercel reports in Cloudflare DNS. Leave the Vercel A/CNAME record **DNS only** (gray cloud), because placing Cloudflare's reverse proxy in front of Vercel hides traffic signals, adds another CDN hop, and can interfere with Vercel caching/firewall behavior. Ownership-verification TXT records are also DNS only. Vercel provisions TLS after validation.
|
|
935
|
+
|
|
936
|
+
When web and API are both selected, keep the generated \`/api/(.*)\` route before the web catch-all. The browser uses same-origin \`/api\`; mobile, desktop, and extension builds need the absolute production API URL.` : null,
|
|
937
|
+
options.features.auth ? `## Clerk: production identity
|
|
938
|
+
|
|
939
|
+
1. Create the Clerk application for development, then create its separate **Production** instance. Copy \`pk_live_*\` and \`sk_live_*\` keys into the production environments; keep \`CLERK_SECRET_KEY\` server-only.
|
|
940
|
+
2. Add the production root domain in Clerk and publish the DNS records shown on **Domains**. Configure a subdomain allowlist, production OAuth credentials, allowlisted redirect URLs, webhook URLs/signing secrets, and native application identifiers that apply to the selected clients.
|
|
941
|
+
3. Use development keys locally and production keys only for production builds. Vercel Preview deployments should use a separate Clerk application/domain when stable preview auth is required; do not point previews at live user data.
|
|
942
|
+
4. Redeploy every selected client after changing public Clerk keys. Test sign-in, sign-out, token refresh, deep links, and physical-device behavior before release.${options.apps.extension ? '\n5. For the extension, create a stable CRX ID, configure Clerk Chrome Extension deployment for that ID, and set `VITE_CLERK_FRONTEND_API_URL` plus `VITE_CLERK_SYNC_HOST` when using web-to-extension session sync. OAuth and email-link flows require Sync Host.' : ''}` : null,
|
|
943
|
+
options.features.database ? `## Neon and Drizzle: database
|
|
944
|
+
|
|
945
|
+
1. Create a Neon account, then run \`pnpm neon:login\` and \`pnpm neon:project:create -- --name ${options.projectName}\`, or create the project in the Neon console.
|
|
946
|
+
2. Copy the pooled Postgres connection string to \`DATABASE_URL\` in \`packages/db/.env\` locally and the API's Vercel environment in production. Keep preview and production databases isolated with Neon branches or separate projects.
|
|
947
|
+
3. Change the Drizzle schema, run \`pnpm db:generate\`, review and commit the SQL and metadata, then run \`pnpm verify:db\`.
|
|
948
|
+
4. Apply \`pnpm db:migrate\` against the intended database as a controlled release step before sending production traffic to code that requires the new schema. Backward-compatible migrations make rollback safer; never run unreviewed migration generation during a Vercel build.
|
|
949
|
+
5. Enable Neon backups/restore controls appropriate to the plan, restrict credentials, and rotate a leaked connection string immediately.` : null,
|
|
950
|
+
options.features.storage ? `## Cloudflare R2: private bucket and generated Worker
|
|
951
|
+
|
|
952
|
+
1. Run \`pnpm r2:login\` and \`pnpm r2:bucket:create\` to create \`${storageBucketName}\`, or create that bucket in **R2 → Overview**. Keep both the \`r2.dev\` development URL and R2 bucket custom-domain access disabled; the bucket itself remains private.
|
|
953
|
+
2. Create an Object Read & Write S3 API token scoped to this bucket. Put \`BASE_URL\`, \`R2_ACCOUNT_ID\`, \`R2_ACCESS_KEY_ID\`, \`R2_SECRET_ACCESS_KEY\`, \`R2_BUCKET_NAME=${storageBucketName}\`, \`R2_PREFIX=storage\`, and \`R2_PROXY_READ_URL_TTL_SECONDS=600\` in the API deployment. The Worker uses the in-process \`ASSETS\` binding instead of these S3 credentials. Keep \`CLOUDFLARE_API_TOKEN\` operations/CI-only for Wrangler.
|
|
954
|
+
3. Direct browser uploads continue to use short-lived presigned PUT URLs on \`<ACCOUNT_ID>.r2.cloudflarestorage.com\`. Presigned URLs do **not** work on custom domains. Run \`pnpm r2:cors:list\`, edit the user-owned \`cloudflare/r2-cors.template.json\`, then run \`pnpm r2:cors:set\`. The set command replaces the complete live policy, so retain every exact uploading origin.
|
|
955
|
+
4. Open \`apps/assets-private-proxy/wrangler.jsonc\`. Replace both \`assets.example.com\` values with \`assets.yourdomain.com\`. The generated config names the Worker \`assets-private-proxy\`, disables \`workers.dev\` and preview URLs, binds \`${storageBucketName}\` as \`ASSETS\`, sets \`R2_PREFIX=storage\`, enables logs, and declares the hostname as a Worker Custom Domain.
|
|
956
|
+
5. Run \`pnpm assets:proxy:check\`, then \`pnpm assets:proxy:deploy\`. Wrangler creates or updates the Worker, R2 binding, managed proxied DNS record, TLS certificate, and custom domain. The dashboard equivalent is **Workers & Pages → assets-private-proxy → Settings → Bindings** (R2, variable \`ASSETS\`, bucket \`${storageBucketName}\`) and **Domains & Routes → Add → Custom domain**.
|
|
957
|
+
6. The Worker streams GET/HEAD bodies, preserves metadata/ranges/conditionals, caches complete public responses, rejects other methods and unexpected hosts, and never lists the bucket. It exposes only \`storage/confirmed/\` by unguessable key; \`storage/staging/\` and \`generation-inputs\` return 404. Authenticated private reads use \`GET /api/storage/uploads/:uploadId/read-url\`, which verifies ownership before returning a short-lived S3 URL.
|
|
958
|
+
7. Add an R2 lifecycle rule for \`storage/staging/\` longer than the API cleanup grace period. Set a strong \`CRON_SECRET\` in Vercel and verify cleanup. Test missing keys, invalid encodings, GET, HEAD, range, conditional, cache HIT/MISS, forbidden methods, private-prefix rejection, authenticated read authorization, TTL bounds, and direct bucket inaccessibility.
|
|
959
|
+
|
|
960
|
+
\`app.yourdomain.com\` is a Cloudflare DNS-only record targeting Vercel. \`assets.yourdomain.com\` is a Cloudflare-managed Worker Custom Domain and stays proxied. Never connect the asset hostname directly to R2, never CNAME it to \`r2.dev\`, and never expose S3 credentials in a client bundle.` : null,
|
|
961
|
+
options.apps.mobile ? `## Expo, TestFlight, and app stores
|
|
962
|
+
|
|
963
|
+
Accounts required: an Expo/EAS account, an Apple Developer Program membership with App Store Connect access for iOS, and a Google Play Console developer account for Android. Create unique iOS bundle and Android package identifiers before the first store build.
|
|
964
|
+
|
|
965
|
+
1. Run \`pnpm mobile:eas:login\`, then \`pnpm mobile:eas:init\` from the repository root to create/link the EAS project. Review and commit the project ID/configuration that EAS adds.
|
|
966
|
+
2. Put public build-time values in the matching EAS environment/profile; keep server secrets out of Expo. Configure Apple/Google credentials with EAS and test sign-in/deep links on physical devices.
|
|
967
|
+
3. Internal EAS distribution: run \`pnpm mobile:build:internal:ios\` and/or \`pnpm mobile:build:internal:android\`. iOS ad hoc distribution requires registered device UDIDs; Android internal builds can be installed from the EAS share URL. These builds do not require a development server.
|
|
968
|
+
4. TestFlight: run \`pnpm mobile:build:production:ios\`, then \`pnpm mobile:submit:ios\`. After App Store Connect processes the build, assign it to internal testers. External testers require TestFlight Beta App Review. TestFlight approval is not App Store production approval.
|
|
969
|
+
5. Google Play: create the app/listing and required policy declarations in Play Console. Run \`pnpm mobile:build:production:android\`, then \`pnpm mobile:submit:android\`. Start with the internal testing track, promote through closed/open testing as appropriate, and only then roll out production. A brand-new Play app may require its first binary to be uploaded manually before API-based submissions work.
|
|
970
|
+
6. Complete store metadata, screenshots, privacy/data-safety declarations, content ratings, export compliance, pricing/availability, review credentials, and release notes. Submit for store review and use staged/phased rollout where appropriate.` : null,
|
|
971
|
+
options.apps.extension ? `## Chrome Web Store
|
|
972
|
+
|
|
973
|
+
1. Register a Chrome Web Store developer account, verify its contact email, accept the agreement, and pay Google's one-time registration fee.
|
|
974
|
+
2. Configure production extension environment values and a stable CRX public key/ID, then run \`pnpm verify:extension\` and \`pnpm extension:zip\`. Load the unpacked production build in Chrome first and test install, update, permissions, authentication, API calls, and sign-out.
|
|
975
|
+
3. In the Developer Dashboard, create an item and upload the ZIP from \`apps/extension/.output\`. Complete the listing (description, icons, screenshots, category, regions) and keep the manifest version higher for every update.
|
|
976
|
+
4. State one narrow purpose, justify every permission/host permission, disclose all handled data, certify limited use, and provide a public privacy-policy URL consistent with actual behavior. Clerk login counts as handling authentication data. Supply reviewer test instructions and credentials when features are gated.
|
|
977
|
+
5. Publish first to trusted testers/unlisted visibility, verify the store-installed CRX ID matches Clerk and backend allowlists, then submit the production listing for review. Store review and rollout are separate from GitHub/Vercel deployment.` : null,
|
|
978
|
+
options.apps.desktop ? `## Electron desktop
|
|
979
|
+
|
|
980
|
+
Builds are platform-specific: produce macOS, Windows, and Linux artifacts on their matching CI runners with the package's \`build:mac\`, \`build:win\`, and \`build:linux\` scripts. Configure signing/notarization credentials in CI, never in the repository. Test clean install, upgrade, deep links, Clerk return flow, auto-update strategy, and OS security warnings before publishing artifacts to the chosen release channel.` : null,
|
|
981
|
+
].filter((section) => section !== null);
|
|
982
|
+
writeFile(path.join(root, 'PRODUCTION.md'), `# ${markdownHeading(options.displayName)} production guide
|
|
983
|
+
|
|
984
|
+
This guide includes only the surfaces and providers selected when the project was generated. Provision separate Preview and Production resources, use least-privilege credentials, and keep account ownership with the organization rather than an individual developer.
|
|
985
|
+
|
|
986
|
+
## Release gate
|
|
987
|
+
|
|
988
|
+
${productionItems.join('\n')}
|
|
989
|
+
|
|
990
|
+
${productionSections.join('\n\n')}
|
|
991
|
+
|
|
992
|
+
## Final release order
|
|
993
|
+
|
|
994
|
+
- Run \`pnpm verify\` and \`anhedral doctor\`; review the exact production diff.
|
|
995
|
+
${options.features.database ? '- Apply reviewed, backward-compatible database migrations.' : ''}
|
|
996
|
+
${options.apps.web || options.apps.api ? '- Deploy provider infrastructure and secrets, then deploy API/web.' : ''}
|
|
997
|
+
${options.apps.mobile || options.apps.extension || options.apps.desktop ? '- Build immutable client artifacts only after production URLs and public keys are final.\n- Release to internal testers, verify telemetry and rollback, then promote through each store review/rollout.' : ''}
|
|
542
998
|
`);
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
import * as schema from './schema';
|
|
546
|
-
|
|
547
|
-
export function createDb(databaseUrl = process.env.DATABASE_URL) {
|
|
548
|
-
if (!databaseUrl) {
|
|
549
|
-
throw new Error('DATABASE_URL is not defined');
|
|
550
|
-
}
|
|
551
|
-
|
|
552
|
-
const sql = neon(databaseUrl);
|
|
553
|
-
return drizzle(sql, { schema });
|
|
554
|
-
}
|
|
555
|
-
|
|
556
|
-
export type Database = ReturnType<typeof createDb>;
|
|
557
|
-
|
|
558
|
-
let cachedDb: Database | undefined;
|
|
999
|
+
}
|
|
1000
|
+
writeFile(path.join(root, 'ANHEDRAL.md'), `# Anhedral-managed project information
|
|
559
1001
|
|
|
560
|
-
|
|
561
|
-
cachedDb ??= createDb();
|
|
562
|
-
return cachedDb;
|
|
563
|
-
}
|
|
1002
|
+
Generator: ${GENERATOR_VERSION}
|
|
564
1003
|
|
|
565
|
-
|
|
566
|
-
get(_target, prop, receiver) {
|
|
567
|
-
return Reflect.get(getDb(), prop, receiver);
|
|
568
|
-
},
|
|
569
|
-
});
|
|
1004
|
+
Resolved modules: ${modules.join(', ')}
|
|
570
1005
|
|
|
571
|
-
|
|
1006
|
+
- \`anhedral add <module> --dry-run\` previews incremental changes.
|
|
1007
|
+
- \`anhedral ui add <component> --dry-run\` previews platform-routed component additions.
|
|
1008
|
+
- \`anhedral doctor\` reports manifest and filesystem drift before incremental changes.
|
|
1009
|
+
- README and existing user workflows are never rewritten by \`anhedral add\`.
|
|
572
1010
|
`);
|
|
573
|
-
|
|
574
|
-
|
|
1011
|
+
const surfaceGuidance = [
|
|
1012
|
+
options.apps.web ? '- Web lives in `apps/web`: use Next.js App Router, server-first rendering, and shadcn/ui source components.' : null,
|
|
1013
|
+
options.apps.mobile ? `- Mobile lives in \`apps/mobile\`: use Expo Router and React Native Reusables with ${options.nativeStyling}. Keep native-only APIs behind platform-safe modules.` : null,
|
|
1014
|
+
options.apps.api ? '- HTTP and provider integration lives in `apps/api`: keep Fastify routes thin, validate boundaries, and put secrets only in server environment files.' : null,
|
|
1015
|
+
options.apps.desktop ? '- Desktop lives in `apps/desktop`: keep Electron main/preload privileges minimal and application UI in the sandboxed React renderer.' : null,
|
|
1016
|
+
options.apps.extension ? '- Browser extension code lives in `apps/extension`: use WXT entrypoints and request only permissions required by the feature.' : null,
|
|
1017
|
+
options.features.storage ? '- Private-bucket asset delivery lives in `apps/assets-private-proxy`: preserve the `ASSETS` R2 binding, streaming responses, method/host restrictions, and Cloudflare-managed custom domain.' : null,
|
|
1018
|
+
].filter((value) => value !== null).join('\n');
|
|
1019
|
+
const featureGuidance = [
|
|
1020
|
+
options.apps.api ? '- Reuse `@shared/contracts` at every network boundary and call the API through `@shared/api-client`; clients must not import server implementation modules.' : null,
|
|
1021
|
+
options.features.database ? '- Neon/Drizzle state is authoritative. Change `packages/db/src/schema.ts`, generate SQL with `pnpm db:generate`, review it, and Git-track the migration.' : null,
|
|
1022
|
+
options.features.auth ? '- Clerk owns identity and sessions. Never trust a client-supplied user ID; derive identity from verified server authentication.' : null,
|
|
1023
|
+
options.features.billing ? '- RevenueCat events reconcile into Neon before Ably publishes an invalidation. Clients refetch entitlements instead of treating realtime payloads as authority.' : null,
|
|
1024
|
+
options.features.storage ? '- R2 credentials and signed-upload policy stay in the API. The `assets-private-proxy` Worker uses its binding instead of S3 credentials and publicly serves GET/HEAD only by known unguessable key.' : null,
|
|
1025
|
+
].filter((value) => value !== null).join('\n');
|
|
1026
|
+
const skillFeatureSteps = [
|
|
1027
|
+
options.apps.api ? 'Define shared network schemas in `packages/contracts/src/`.' : null,
|
|
1028
|
+
options.features.database ? 'Define persistent state in `packages/db/src/schema.ts`; generate, review, and commit Drizzle SQL. Use managed Neon, never a generated local Postgres service.' : null,
|
|
1029
|
+
options.apps.api ? 'Put backend behavior in `apps/api/src/services/` and keep `apps/api/src/routes/` thin.' : null,
|
|
1030
|
+
options.apps.api ? 'Add client-safe calls to `packages/api-client/src/`; frontends must not import server implementations.' : null,
|
|
1031
|
+
options.apps.web ? 'Write web product code with normal Next.js App Router conventions in `apps/web`.' : null,
|
|
1032
|
+
options.apps.mobile ? 'Write native product code with normal Expo Router conventions in `apps/mobile`.' : null,
|
|
1033
|
+
'Verify the affected package, then run the root verification before handoff.',
|
|
1034
|
+
].filter((value) => value !== null).map((value, index) => `${index + 1}. ${value}`).join('\n');
|
|
1035
|
+
writeFile(path.join(root, 'SKILL.md'), `---
|
|
1036
|
+
name: anhedral-project
|
|
1037
|
+
description: Build and extend this Anhedral-generated ${modules.join(', ')} TypeScript application while preserving its framework, ownership, security, and verification conventions.
|
|
1038
|
+
---
|
|
575
1039
|
|
|
576
|
-
|
|
577
|
-
export type SubscriptionTier = (typeof SUBSCRIPTION_TIERS)[number];
|
|
1040
|
+
# Anhedral project
|
|
578
1041
|
|
|
579
|
-
|
|
580
|
-
export type SubscriptionStatus = (typeof SUBSCRIPTION_STATUSES)[number];
|
|
1042
|
+
Use this skill whenever you plan, implement, review, or diagnose work in this repository.
|
|
581
1043
|
|
|
582
|
-
|
|
583
|
-
export type SubscriptionMethod = (typeof SUBSCRIPTION_METHODS)[number];
|
|
1044
|
+
## Product model
|
|
584
1045
|
|
|
585
|
-
|
|
586
|
-
export type SubscriptionOrigin = (typeof SUBSCRIPTION_ORIGINS)[number];
|
|
1046
|
+
This is a standard TypeScript monorepo assembled by Anhedral, not an application running inside an Anhedral framework. Write normal Next.js, Expo Router, Fastify, Drizzle, Electron, or WXT code in the generated workspace. Use Anhedral only for structural operations such as adding a module, adding source-owned UI, and checking generated-file ownership.
|
|
587
1047
|
|
|
588
|
-
|
|
589
|
-
'trial_started', 'trial_converted', 'trial_expired',
|
|
590
|
-
'initial_purchase', 'renewal', 'product_change',
|
|
591
|
-
'cancellation_scheduled', 'cancellation_unscheduled', 'subscription_expired', 'subscription_canceled',
|
|
592
|
-
'billing_issue', 'billing_recovered',
|
|
593
|
-
] as const;
|
|
594
|
-
export type SubscriptionEventType = (typeof SUBSCRIPTION_EVENT_TYPES)[number];
|
|
1048
|
+
Before implementing a feature, read \`README.md\` for the source map, \`docs/DEVELOPMENT.md\` for task recipes, and \`docs/STACK.md\` when you need the selected tools' responsibility boundaries and official documentation.
|
|
595
1049
|
|
|
596
|
-
|
|
597
|
-
revenueCatProductId?: string;
|
|
598
|
-
lastWebhookUpdate?: string;
|
|
599
|
-
cancelReason?: string;
|
|
600
|
-
};
|
|
1050
|
+
## Start safely
|
|
601
1051
|
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
price?: { amount: number; currency: string };
|
|
607
|
-
store?: string;
|
|
608
|
-
transactionId?: string;
|
|
609
|
-
reason?: string;
|
|
610
|
-
};
|
|
1052
|
+
1. Read \`anhedral.json\` for the selected modules, native styling provider, installed UI components, and file ownership.
|
|
1053
|
+
2. Run \`pnpm dlx anhedral@${GENERATOR_VERSION} doctor\` before generator operations.
|
|
1054
|
+
3. Preview structural changes with \`anhedral add <module> --dry-run\` or \`anhedral ui add <component> --dry-run\`.
|
|
1055
|
+
4. Never hand-edit \`anhedral.json\`, ownership hashes, or bundled-template provenance.
|
|
611
1056
|
|
|
612
|
-
|
|
613
|
-
id: text('id').primaryKey(),
|
|
614
|
-
clerkUserId: text('clerk_user_id').unique(),
|
|
615
|
-
email: text('email').notNull().unique(),
|
|
616
|
-
displayName: text('display_name'),
|
|
617
|
-
lastLoginAt: timestamp('last_login_at'),
|
|
618
|
-
profileImageUrl: text('profile_image_url'),
|
|
619
|
-
subscriptionTier: text('subscription_tier').notNull().default('free'),
|
|
620
|
-
subscriptionStatus: text('subscription_status').notNull().default('active'),
|
|
621
|
-
createdAt: timestamp('created_at').$defaultFn(() => new Date()).notNull(),
|
|
622
|
-
updatedAt: timestamp('updated_at').$defaultFn(() => new Date()).notNull(),
|
|
623
|
-
}, (t) => [
|
|
624
|
-
index('users_clerk_user_id_idx').on(t.clerkUserId),
|
|
625
|
-
index('users_email_idx').on(t.email),
|
|
626
|
-
]);
|
|
1057
|
+
Resolved modules: ${modules.map((moduleName) => `\`${moduleName}\``).join(', ')}.
|
|
627
1058
|
|
|
628
|
-
|
|
629
|
-
id: text('id').primaryKey(),
|
|
630
|
-
userId: text('user_id').notNull().references(() => users.id, { onDelete: 'cascade' }),
|
|
631
|
-
objectKey: text('object_key').notNull().unique(),
|
|
632
|
-
bucket: text('bucket').notNull(),
|
|
633
|
-
contentType: text('content_type'),
|
|
634
|
-
createdAt: timestamp('created_at').$defaultFn(() => new Date()).notNull(),
|
|
635
|
-
});
|
|
1059
|
+
## Repository boundaries
|
|
636
1060
|
|
|
637
|
-
|
|
638
|
-
id: text('id').primaryKey(),
|
|
639
|
-
userId: text('user_id').notNull().references(() => users.id, { onDelete: 'cascade' }).unique(),
|
|
640
|
-
tier: text('tier').$type<SubscriptionTier>().notNull().default('free'),
|
|
641
|
-
status: text('status').$type<SubscriptionStatus>().notNull().default('active'),
|
|
642
|
-
method: text('method').$type<SubscriptionMethod>(),
|
|
643
|
-
origin: text('origin').$type<SubscriptionOrigin>(),
|
|
644
|
-
billingPeriod: text('billing_period'),
|
|
645
|
-
currentPeriodStart: timestamp('current_period_start'),
|
|
646
|
-
currentPeriodEnd: timestamp('current_period_end'),
|
|
647
|
-
canceledAt: timestamp('canceled_at'),
|
|
648
|
-
cancelAtPeriodEnd: boolean('cancel_at_period_end').notNull().default(false),
|
|
649
|
-
trialStart: timestamp('trial_start'),
|
|
650
|
-
trialEnd: timestamp('trial_end'),
|
|
651
|
-
dailyLimit: integer('daily_limit'),
|
|
652
|
-
metadata: jsonb('metadata').$type<SubscriptionMetadata>(),
|
|
653
|
-
createdAt: timestamp('created_at').$defaultFn(() => new Date()).notNull(),
|
|
654
|
-
updatedAt: timestamp('updated_at').$defaultFn(() => new Date()).notNull(),
|
|
655
|
-
}, (t) => [
|
|
656
|
-
index('subscriptions_user_idx').on(t.userId),
|
|
657
|
-
index('subscriptions_status_idx').on(t.status),
|
|
658
|
-
index('subscriptions_tier_idx').on(t.tier),
|
|
659
|
-
index('subscriptions_period_end_idx').on(t.currentPeriodEnd),
|
|
660
|
-
]);
|
|
1061
|
+
${surfaceGuidance}
|
|
661
1062
|
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
userId: text('user_id').notNull().references(() => users.id, { onDelete: 'cascade' }),
|
|
665
|
-
subscriptionId: text('subscription_id').references(() => subscriptions.id, { onDelete: 'set null' }),
|
|
666
|
-
eventType: text('event_type').$type<SubscriptionEventType>().notNull(),
|
|
667
|
-
previousTier: text('previous_tier').$type<SubscriptionTier>(),
|
|
668
|
-
previousStatus: text('previous_status').$type<SubscriptionStatus>(),
|
|
669
|
-
previousMethod: text('previous_method').$type<SubscriptionMethod>(),
|
|
670
|
-
newTier: text('new_tier').$type<SubscriptionTier>(),
|
|
671
|
-
newStatus: text('new_status').$type<SubscriptionStatus>(),
|
|
672
|
-
newMethod: text('new_method').$type<SubscriptionMethod>(),
|
|
673
|
-
revenueCatEventType: text('revenuecat_event_type'),
|
|
674
|
-
revenueCatProductId: text('revenuecat_product_id'),
|
|
675
|
-
origin: text('origin').$type<SubscriptionOrigin>(),
|
|
676
|
-
periodStart: timestamp('period_start'),
|
|
677
|
-
periodEnd: timestamp('period_end'),
|
|
678
|
-
metadata: jsonb('metadata').$type<SubscriptionEventMetadata>(),
|
|
679
|
-
createdAt: timestamp('created_at').$defaultFn(() => new Date()).notNull(),
|
|
680
|
-
}, (t) => [
|
|
681
|
-
index('sub_events_user_idx').on(t.userId),
|
|
682
|
-
index('sub_events_user_created_idx').on(t.userId, t.createdAt),
|
|
683
|
-
index('sub_events_type_idx').on(t.eventType),
|
|
684
|
-
]);
|
|
1063
|
+
- Shared source belongs in focused packages under \`packages/\`; do not create a second workspace, lockfile, or nested dependency island.
|
|
1064
|
+
${featureGuidance}
|
|
685
1065
|
|
|
686
|
-
|
|
687
|
-
id: text('id').primaryKey(),
|
|
688
|
-
userId: text('user_id').references(() => users.id, { onDelete: 'set null' }),
|
|
689
|
-
email: text('email').notNull().unique(),
|
|
690
|
-
claimedAt: timestamp('claimed_at').$defaultFn(() => new Date()).notNull(),
|
|
691
|
-
}, (t) => [index('trial_claims_email_idx').on(t.email)]);
|
|
692
|
-
|
|
693
|
-
export type Users = InferSelectModel<typeof users>;
|
|
694
|
-
export type NewUsers = InferInsertModel<typeof users>;
|
|
695
|
-
export type Uploads = InferSelectModel<typeof uploads>;
|
|
696
|
-
export type NewUploads = InferInsertModel<typeof uploads>;
|
|
697
|
-
export type Subscriptions = InferSelectModel<typeof subscriptions>;
|
|
698
|
-
export type NewSubscriptions = InferInsertModel<typeof subscriptions>;
|
|
699
|
-
export type SubscriptionEvents = InferSelectModel<typeof subscriptionEvents>;
|
|
700
|
-
export type NewSubscriptionEvents = InferInsertModel<typeof subscriptionEvents>;
|
|
701
|
-
export type TrialClaims = InferSelectModel<typeof trialClaims>;
|
|
702
|
-
export type NewTrialClaims = InferInsertModel<typeof trialClaims>;
|
|
703
|
-
`);
|
|
704
|
-
writeFile(path.join(dbRoot, 'src/queries/users.ts'), `import { eq } from 'drizzle-orm';
|
|
705
|
-
import { db } from '../index';
|
|
706
|
-
import { uploads, users } from '../schema';
|
|
707
|
-
|
|
708
|
-
type SyncUserInput = {
|
|
709
|
-
clerkUserId: string;
|
|
710
|
-
email: string;
|
|
711
|
-
displayName: string | null;
|
|
712
|
-
};
|
|
1066
|
+
## Feature workflow
|
|
713
1067
|
|
|
714
|
-
|
|
715
|
-
return db.query.users.findFirst({
|
|
716
|
-
where: eq(users.clerkUserId, clerkUserId),
|
|
717
|
-
});
|
|
718
|
-
}
|
|
1068
|
+
${skillFeatureSteps}
|
|
719
1069
|
|
|
720
|
-
|
|
721
|
-
await db
|
|
722
|
-
.insert(users)
|
|
723
|
-
.values({
|
|
724
|
-
id: input.clerkUserId,
|
|
725
|
-
clerkUserId: input.clerkUserId,
|
|
726
|
-
email: input.email,
|
|
727
|
-
displayName: input.displayName,
|
|
728
|
-
})
|
|
729
|
-
.onConflictDoUpdate({
|
|
730
|
-
target: users.clerkUserId,
|
|
731
|
-
set: {
|
|
732
|
-
email: input.email,
|
|
733
|
-
displayName: input.displayName,
|
|
734
|
-
updatedAt: new Date(),
|
|
735
|
-
},
|
|
736
|
-
});
|
|
1070
|
+
## UI conventions
|
|
737
1071
|
|
|
738
|
-
|
|
739
|
-
}
|
|
1072
|
+
- Add source-owned components with \`pnpm dlx anhedral@${GENERATOR_VERSION} ui add <component>\`; use \`--target\` only when the component should not exist in every selected client.
|
|
1073
|
+
- Web, desktop, and extension components come from shadcn/ui. Mobile components come from React Native Reusables using ${options.nativeStyling}.
|
|
1074
|
+
- Compose application-specific UI around installed primitives. Preserve accessibility, keyboard behavior, focus handling, and platform conventions.
|
|
1075
|
+
- Use lowercase kebab-case filenames, PascalCase component exports, and \`use-\` prefixes for hooks.
|
|
740
1076
|
|
|
741
|
-
|
|
742
|
-
clerkUserId: string,
|
|
743
|
-
input: { objectKey: string; bucket: string; contentType: string | null },
|
|
744
|
-
) {
|
|
745
|
-
await db.insert(uploads).values({
|
|
746
|
-
id: crypto.randomUUID(),
|
|
747
|
-
userId: clerkUserId,
|
|
748
|
-
objectKey: input.objectKey,
|
|
749
|
-
bucket: input.bucket,
|
|
750
|
-
contentType: input.contentType,
|
|
751
|
-
});
|
|
752
|
-
}
|
|
753
|
-
`);
|
|
754
|
-
writeFile(path.join(dbRoot, 'src/queries/uploads.ts'), `import { eq } from 'drizzle-orm';
|
|
755
|
-
import { db } from '../index';
|
|
756
|
-
import { uploads } from '../schema';
|
|
1077
|
+
## Ownership rules
|
|
757
1078
|
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
});
|
|
762
|
-
}
|
|
763
|
-
`);
|
|
764
|
-
writeFile(path.join(dbRoot, 'src/queries/index.ts'), `export * from './uploads';
|
|
765
|
-
export * from './users';
|
|
766
|
-
`);
|
|
767
|
-
writeFile(path.join(dbRoot, 'src/migrate.ts'), `import { drizzle } from 'drizzle-orm/neon-http';
|
|
768
|
-
import { migrate } from 'drizzle-orm/neon-http/migrator';
|
|
769
|
-
import { neon } from '@neondatabase/serverless';
|
|
770
|
-
import dotenv from 'dotenv';
|
|
1079
|
+
- \`README.md\` and \`PRODUCTION.md\` are user-owned. Root JSON/YAML configuration is mergeable. Other recorded files are generator-managed unless \`anhedral.json\` says otherwise.
|
|
1080
|
+
- Prefer new application files and narrow composition points over editing managed substrate files. If a managed file must change, understand that future \`anhedral add\` operations will stop until the project is reconciled.
|
|
1081
|
+
- Never overwrite user changes, bypass a generator conflict, or replace a failed ownership check with fabricated hashes.
|
|
771
1082
|
|
|
772
|
-
|
|
773
|
-
dotenv.config({ quiet: true });
|
|
1083
|
+
## Environment and security
|
|
774
1084
|
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
1085
|
+
- The root \`.env.example\` is an inventory, not a runtime environment file. Copy package-local examples and keep real environment files uncommitted.
|
|
1086
|
+
- Keep server secrets out of browser, Expo, Electron renderer, and extension bundles. Only variables with the framework's explicit public prefix may enter client code.
|
|
1087
|
+
- Validate external input at the API boundary, use parameterized Drizzle queries, and keep privileged Electron functionality behind a narrow context-isolated preload bridge.
|
|
778
1088
|
|
|
779
|
-
|
|
780
|
-
const database = drizzle(client);
|
|
1089
|
+
## Deployment conventions
|
|
781
1090
|
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
const simplePackages = [
|
|
789
|
-
['contracts', {
|
|
790
|
-
exports: { '.': './src/index.ts' },
|
|
791
|
-
dependencies: CONTRACTS_DEPENDENCIES.dependencies,
|
|
792
|
-
}, `import { z } from 'zod';
|
|
793
|
-
|
|
794
|
-
export const ClientPlatformSchema = z.enum(['frontend', 'extension']);
|
|
795
|
-
export type ClientPlatform = z.infer<typeof ClientPlatformSchema>;
|
|
796
|
-
|
|
797
|
-
export const ApiErrorSchema = z.object({
|
|
798
|
-
error: z.string(),
|
|
799
|
-
message: z.string(),
|
|
800
|
-
});
|
|
801
|
-
export type ApiError = z.infer<typeof ApiErrorSchema>;
|
|
802
|
-
|
|
803
|
-
export const AuthMeResponseSchema = z.object({
|
|
804
|
-
user: z.object({
|
|
805
|
-
id: z.string(),
|
|
806
|
-
email: z.string().email(),
|
|
807
|
-
firstName: z.string().nullable().optional(),
|
|
808
|
-
lastName: z.string().nullable().optional(),
|
|
809
|
-
displayName: z.string(),
|
|
810
|
-
imageUrl: z.string().url().nullable().optional(),
|
|
811
|
-
}),
|
|
812
|
-
});
|
|
813
|
-
export type AuthMeResponse = z.infer<typeof AuthMeResponseSchema>;
|
|
814
|
-
|
|
815
|
-
export const PricingResponseSchema = z.object({
|
|
816
|
-
tiers: z.array(z.object({
|
|
817
|
-
tier: z.enum(['free', 'pro']),
|
|
818
|
-
displayName: z.string(),
|
|
819
|
-
description: z.string(),
|
|
820
|
-
priceMonthly: z.number().nullable(),
|
|
821
|
-
priceYearly: z.number().nullable(),
|
|
822
|
-
currency: z.string(),
|
|
823
|
-
limits: z.object({
|
|
824
|
-
dailyLimit: z.number().nullable(),
|
|
825
|
-
}),
|
|
826
|
-
paymentInfo: z.object({
|
|
827
|
-
revenueCatEntitlementId: z.string(),
|
|
828
|
-
revenueCatOfferingId: z.string(),
|
|
829
|
-
}).optional(),
|
|
830
|
-
})),
|
|
831
|
-
});
|
|
832
|
-
export type PricingResponse = z.infer<typeof PricingResponseSchema>;
|
|
833
|
-
|
|
834
|
-
export const SubscriptionEntitlementsSchema = z.object({
|
|
835
|
-
pro: z.boolean(),
|
|
836
|
-
inTrial: z.boolean(),
|
|
837
|
-
trialEndsAt: z.string().optional(),
|
|
838
|
-
expiresAt: z.string().optional(),
|
|
839
|
-
periodStart: z.string().optional(),
|
|
840
|
-
periodEnd: z.string().optional(),
|
|
841
|
-
method: z.enum(['trialing', 'redeemed', 'paid']).nullable().optional(),
|
|
842
|
-
managementUrl: z.string().url().optional(),
|
|
843
|
-
cancelAtPeriodEnd: z.boolean().optional(),
|
|
844
|
-
});
|
|
845
|
-
export type SubscriptionEntitlements = z.infer<typeof SubscriptionEntitlementsSchema>;
|
|
1091
|
+
- Read \`PRODUCTION.md\` before provisioning or changing production resources. It is tailored to this project's selected surfaces and providers.
|
|
1092
|
+
${options.apps.web || options.apps.api ? '- Prefer GitHub-triggered Vercel Preview and Production deployments. Keep the generated Services routing intact; use manual `deploy:vercel:*` scripts only when explicitly required.' : ''}
|
|
1093
|
+
${options.features.database ? '- Treat reviewed, committed Drizzle SQL as the release artifact. Apply migrations as a controlled step against the intended Neon environment; never generate migrations during an application build.' : ''}
|
|
1094
|
+
${options.features.storage ? '- Keep the R2 bucket private and deploy `assets-private-proxy` at the Cloudflare Worker custom domain. Expose only `storage/confirmed/` publicly; use the owner-authorized read-URL endpoint for private objects and keep `CLOUDFLARE_API_TOKEN` operations-only.' : ''}
|
|
1095
|
+
${options.apps.mobile ? '- Promote mobile artifacts through EAS internal distribution, TestFlight/Google Play testing, then store review. Build-time public variables are not secrets.' : ''}
|
|
1096
|
+
${options.apps.extension ? '- Publish the exact verified WXT ZIP through trusted/unlisted Chrome Web Store testing before production review; preserve a stable CRX ID and least-privilege permissions.' : ''}
|
|
846
1097
|
|
|
847
|
-
|
|
848
|
-
success: z.boolean(),
|
|
849
|
-
});
|
|
850
|
-
export type SignOutResponse = z.infer<typeof SignOutResponseSchema>;
|
|
1098
|
+
## Verify changes
|
|
851
1099
|
|
|
852
|
-
|
|
853
|
-
fileName: z.string().min(1).max(200).optional(),
|
|
854
|
-
contentType: z.string().min(1).max(200),
|
|
855
|
-
});
|
|
856
|
-
export type CreateUploadRequest = z.infer<typeof CreateUploadRequestSchema>;
|
|
1100
|
+
Run the strongest applicable checks before handing work back:
|
|
857
1101
|
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
export type CreateUploadResponse = z.infer<typeof CreateUploadResponseSchema>;
|
|
1102
|
+
\`\`\`sh
|
|
1103
|
+
pnpm typecheck
|
|
1104
|
+
pnpm verify
|
|
1105
|
+
pnpm build
|
|
1106
|
+
pnpm dlx anhedral@${GENERATOR_VERSION} doctor
|
|
1107
|
+
\`\`\`
|
|
865
1108
|
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
downloadUrl: z.string().url(),
|
|
869
|
-
expiresIn: z.number(),
|
|
870
|
-
});
|
|
871
|
-
export type StorageFileResponse = z.infer<typeof StorageFileResponseSchema>;
|
|
872
|
-
`],
|
|
873
|
-
['types', {
|
|
874
|
-
exports: { '.': './src/index.ts' },
|
|
875
|
-
dependencies: { '@shared/contracts': 'workspace:*' },
|
|
876
|
-
}, `export type ApiEnvelope<T> = { data: T } | { error: string; message: string };
|
|
877
|
-
export type {
|
|
878
|
-
AuthMeResponse,
|
|
879
|
-
ClientPlatform,
|
|
880
|
-
CreateUploadRequest,
|
|
881
|
-
CreateUploadResponse,
|
|
882
|
-
PricingResponse,
|
|
883
|
-
SignOutResponse,
|
|
884
|
-
StorageFileResponse,
|
|
885
|
-
SubscriptionEntitlements,
|
|
886
|
-
} from '@shared/contracts';
|
|
887
|
-
`],
|
|
888
|
-
['config', { exports: { '.': './src/index.ts' } }, `export const DEFAULT_API_PATH_PREFIX = '/api';
|
|
889
|
-
export const DEFAULT_LOCAL_API_URL = 'http://localhost:8787';
|
|
890
|
-
export const DEFAULT_FRONTEND_URL = 'http://localhost:8081';
|
|
891
|
-
export const DEFAULT_EXTENSION_URL = 'chrome-extension://';
|
|
892
|
-
|
|
893
|
-
export function joinApiUrl(baseUrl: string, path: string) {
|
|
894
|
-
const base = baseUrl.replace(/\\/$/, '');
|
|
895
|
-
const suffix = path.startsWith('/') ? path : \`/\${path}\`;
|
|
896
|
-
return \`\${base}\${suffix}\`;
|
|
897
|
-
}
|
|
898
|
-
`],
|
|
899
|
-
['api-client', {
|
|
900
|
-
exports: { '.': './src/index.ts' },
|
|
901
|
-
dependencies: API_CLIENT_DEPENDENCIES.dependencies,
|
|
902
|
-
}, `import type { ZodType } from 'zod';
|
|
903
|
-
import { joinApiUrl } from '@shared/config';
|
|
904
|
-
import {
|
|
905
|
-
AuthMeResponseSchema,
|
|
906
|
-
CreateUploadResponseSchema,
|
|
907
|
-
PricingResponseSchema,
|
|
908
|
-
SignOutResponseSchema,
|
|
909
|
-
StorageFileResponseSchema,
|
|
910
|
-
SubscriptionEntitlementsSchema,
|
|
911
|
-
type AuthMeResponse,
|
|
912
|
-
type ClientPlatform,
|
|
913
|
-
type CreateUploadRequest,
|
|
914
|
-
type CreateUploadResponse,
|
|
915
|
-
type PricingResponse,
|
|
916
|
-
type SignOutResponse,
|
|
917
|
-
type StorageFileResponse,
|
|
918
|
-
type SubscriptionEntitlements,
|
|
919
|
-
} from '@shared/contracts';
|
|
920
|
-
|
|
921
|
-
export class APIRequestError extends Error {
|
|
922
|
-
constructor(
|
|
923
|
-
public statusCode: number,
|
|
924
|
-
message: string,
|
|
925
|
-
public errorCode?: string,
|
|
926
|
-
) {
|
|
927
|
-
super(message);
|
|
928
|
-
this.name = 'APIRequestError';
|
|
929
|
-
}
|
|
1109
|
+
Use the package-specific \`verify:*\` scripts while iterating. A database schema change is incomplete until its reviewed migration is Git-tracked. Report exact failing packages and commands; do not weaken checks to make a change pass.
|
|
1110
|
+
`);
|
|
930
1111
|
}
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
}
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
1112
|
+
function collectFiles(root, relativeRoot = '') {
|
|
1113
|
+
const absoluteRoot = path.join(root, relativeRoot);
|
|
1114
|
+
if (!pathEntryExists(absoluteRoot))
|
|
1115
|
+
return [];
|
|
1116
|
+
const files = [];
|
|
1117
|
+
for (const entry of readdirSync(absoluteRoot, { withFileTypes: true })) {
|
|
1118
|
+
if (GENERATED_CACHE_NAMES.has(entry.name))
|
|
1119
|
+
continue;
|
|
1120
|
+
const relativePath = relativeRoot ? `${relativeRoot}/${entry.name}` : entry.name;
|
|
1121
|
+
if (relativePath === 'anhedral.json' || isTransactionMetadata(relativePath))
|
|
1122
|
+
continue;
|
|
1123
|
+
if (entry.isDirectory())
|
|
1124
|
+
files.push(...collectFiles(root, relativePath));
|
|
1125
|
+
else if (entry.isFile())
|
|
1126
|
+
files.push(relativePath);
|
|
946
1127
|
}
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
if (
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
1128
|
+
return files.sort();
|
|
1129
|
+
}
|
|
1130
|
+
function ownerForPath(relativePath) {
|
|
1131
|
+
if (relativePath.startsWith('apps/assets-private-proxy/'))
|
|
1132
|
+
return 'storage';
|
|
1133
|
+
if (relativePath.startsWith('cloudflare/'))
|
|
1134
|
+
return 'storage';
|
|
1135
|
+
const app = /^apps\/(web|mobile|api|desktop|extension)(?:\/|$)/.exec(relativePath);
|
|
1136
|
+
if (app)
|
|
1137
|
+
return app[1];
|
|
1138
|
+
if (relativePath.startsWith('packages/db/'))
|
|
1139
|
+
return 'db';
|
|
1140
|
+
return 'root';
|
|
1141
|
+
}
|
|
1142
|
+
function defaultOwnership(relativePath) {
|
|
1143
|
+
if (relativePath === 'README.md' || relativePath === 'PRODUCTION.md')
|
|
1144
|
+
return 'user';
|
|
1145
|
+
if (relativePath === 'apps/assets-private-proxy/wrangler.jsonc')
|
|
1146
|
+
return 'user';
|
|
1147
|
+
if (relativePath === 'cloudflare/r2-cors.template.json')
|
|
1148
|
+
return 'user';
|
|
1149
|
+
if (ROOT_MERGEABLE_FILES.has(relativePath))
|
|
1150
|
+
return 'mergeable';
|
|
1151
|
+
return 'managed';
|
|
1152
|
+
}
|
|
1153
|
+
function createProjectManifest(root, options, operation, templates, previous, components = previous?.ui.components ?? []) {
|
|
1154
|
+
const contributions = new Map();
|
|
1155
|
+
for (const relativePath of collectFiles(root)) {
|
|
1156
|
+
const previousRecord = previous?.files[relativePath];
|
|
1157
|
+
const ownership = previousRecord?.ownership ?? defaultOwnership(relativePath);
|
|
1158
|
+
const owner = previousRecord?.owner ?? ownerForPath(relativePath);
|
|
1159
|
+
const files = contributions.get(owner) ?? [];
|
|
1160
|
+
files.push({
|
|
1161
|
+
path: relativePath,
|
|
1162
|
+
ownership,
|
|
1163
|
+
content: readFileSync(path.join(root, relativePath), 'utf8'),
|
|
1164
|
+
});
|
|
1165
|
+
contributions.set(owner, files);
|
|
963
1166
|
}
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
}
|
|
969
|
-
|
|
970
|
-
getMe() {
|
|
971
|
-
return this.request<AuthMeResponse>('/auth/me', {}, AuthMeResponseSchema);
|
|
972
|
-
}
|
|
973
|
-
|
|
974
|
-
getPricing() {
|
|
975
|
-
return this.request<PricingResponse>('/subscriptions/pricing', {}, PricingResponseSchema);
|
|
976
|
-
}
|
|
977
|
-
|
|
978
|
-
getSubscriptionPricing() {
|
|
979
|
-
return this.getPricing();
|
|
980
|
-
}
|
|
981
|
-
|
|
982
|
-
getSubscriptionEntitlements(options?: { refresh?: boolean }) {
|
|
983
|
-
return this.request<SubscriptionEntitlements>(
|
|
984
|
-
options?.refresh ? '/subscriptions/entitlements/me?refresh=true' : '/subscriptions/entitlements/me',
|
|
985
|
-
{},
|
|
986
|
-
SubscriptionEntitlementsSchema,
|
|
987
|
-
);
|
|
988
|
-
}
|
|
989
|
-
|
|
990
|
-
signOut() {
|
|
991
|
-
return this.request<SignOutResponse>('/auth/signout', {
|
|
992
|
-
method: 'POST',
|
|
993
|
-
}, SignOutResponseSchema);
|
|
994
|
-
}
|
|
995
|
-
|
|
996
|
-
deleteAccount() {
|
|
997
|
-
return this.request<void>('/auth/account', {
|
|
998
|
-
method: 'DELETE',
|
|
1167
|
+
const plan = buildGenerationPlan({
|
|
1168
|
+
operation,
|
|
1169
|
+
requestedModules: options.modules,
|
|
1170
|
+
contributions: [...contributions].map(([module, files]) => ({ module, files })),
|
|
999
1171
|
});
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
getStorageFile(objectKey: string) {
|
|
1010
|
-
return this.request<StorageFileResponse>(
|
|
1011
|
-
\`/storage/files/\${encodeURIComponent(objectKey)}\`,
|
|
1012
|
-
{},
|
|
1013
|
-
StorageFileResponseSchema,
|
|
1014
|
-
);
|
|
1015
|
-
}
|
|
1016
|
-
|
|
1017
|
-
deleteStorageFile(objectKey: string) {
|
|
1018
|
-
return this.request<void>(\`/storage/files/\${encodeURIComponent(objectKey)}\`, {
|
|
1019
|
-
method: 'DELETE',
|
|
1172
|
+
const manifest = createManifest({
|
|
1173
|
+
generatorVersion: GENERATOR_VERSION,
|
|
1174
|
+
project: { name: options.projectName, displayName: options.displayName },
|
|
1175
|
+
plan,
|
|
1176
|
+
toolchain: options.toolchainChannel,
|
|
1177
|
+
templates,
|
|
1178
|
+
nativeStyling: options.nativeStyling,
|
|
1179
|
+
components,
|
|
1020
1180
|
});
|
|
1021
|
-
|
|
1181
|
+
const files = Object.freeze(Object.fromEntries(Object.entries(manifest.files).map(([relativePath, record]) => [
|
|
1182
|
+
relativePath,
|
|
1183
|
+
Object.freeze({
|
|
1184
|
+
...record,
|
|
1185
|
+
hash: hashContent(readFileSync(path.join(root, relativePath))),
|
|
1186
|
+
mode: normalizedFileMode(lstatSync(path.join(root, relativePath)).mode),
|
|
1187
|
+
}),
|
|
1188
|
+
])));
|
|
1189
|
+
return Object.freeze({ ...manifest, files });
|
|
1022
1190
|
}
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
typecheck: 'tsc --noEmit',
|
|
1035
|
-
},
|
|
1036
|
-
devDependencies: SHARED_PACKAGE_DEPENDENCIES.devDependencies,
|
|
1037
|
-
...packageFields,
|
|
1038
|
-
}, null, 2) + '\n');
|
|
1039
|
-
writeFile(path.join(packageRoot, 'tsconfig.json'), JSON.stringify({
|
|
1040
|
-
compilerOptions: {
|
|
1041
|
-
target: 'ESNext',
|
|
1042
|
-
module: 'ESNext',
|
|
1043
|
-
moduleResolution: 'Bundler',
|
|
1044
|
-
strict: true,
|
|
1045
|
-
skipLibCheck: true,
|
|
1046
|
-
noEmit: true,
|
|
1047
|
-
},
|
|
1048
|
-
include: ['src/**/*'],
|
|
1049
|
-
}, null, 2) + '\n');
|
|
1050
|
-
writeFile(path.join(packageRoot, 'src/index.ts'), source);
|
|
1191
|
+
function writeManifest(root, manifest) {
|
|
1192
|
+
writeFile(path.join(root, 'anhedral.json'), serializeManifest(manifest));
|
|
1193
|
+
}
|
|
1194
|
+
function readProjectManifest(root) {
|
|
1195
|
+
const filePath = path.join(root, 'anhedral.json');
|
|
1196
|
+
if (!pathEntryExists(filePath))
|
|
1197
|
+
throw new Error('anhedral.json was not found. Run anhedral init first.');
|
|
1198
|
+
const manifest = readManifest(readFileSync(filePath, 'utf8'));
|
|
1199
|
+
if (manifest.generatorVersion !== GENERATOR_VERSION) {
|
|
1200
|
+
throw new Error(`This project was generated by Anhedral ${manifest.generatorVersion}; current CLI ${GENERATOR_VERSION} only supports exact-current projects. `
|
|
1201
|
+
+ 'Regenerate the project with the current CLI before adding modules.');
|
|
1051
1202
|
}
|
|
1203
|
+
assertTemplateProvenance(manifest.modules, manifest.templates);
|
|
1204
|
+
return manifest;
|
|
1052
1205
|
}
|
|
1053
|
-
function
|
|
1054
|
-
|
|
1055
|
-
const
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
VITE_CRX_PUBLIC_KEY=
|
|
1066
|
-
VITE_RC_BILLING_URL=
|
|
1067
|
-
`;
|
|
1068
|
-
const paymentsEnv = `# RevenueCat
|
|
1069
|
-
RC_SECRET_API_KEY=
|
|
1070
|
-
RC_WEBHOOK_SECRET=
|
|
1071
|
-
RC_ENTITLEMENT_ID=pro
|
|
1072
|
-
RC_OFFERING_ID=default
|
|
1073
|
-
`;
|
|
1074
|
-
writeFile(path.join(root, '.env.example'), `# Apps
|
|
1075
|
-
FRONTEND_URL=${frontendUrl}
|
|
1076
|
-
ANHEDRAL_DEMO=false
|
|
1077
|
-
${expoEnv}${extensionEnv}
|
|
1078
|
-
|
|
1079
|
-
# Server
|
|
1080
|
-
PORT=8787
|
|
1081
|
-
DATABASE_URL=postgresql://user:pass@ep-xxx.us-east-1.aws.neon.tech/dbname?sslmode=require
|
|
1082
|
-
|
|
1083
|
-
# Clerk
|
|
1084
|
-
CLERK_PUBLISHABLE_KEY=pk_test_***
|
|
1085
|
-
CLERK_SECRET_KEY=sk_test_***
|
|
1086
|
-
|
|
1087
|
-
# Cloudflare R2
|
|
1088
|
-
R2_ACCOUNT_ID=
|
|
1089
|
-
R2_ACCESS_KEY_ID=
|
|
1090
|
-
R2_SECRET_ACCESS_KEY=
|
|
1091
|
-
R2_BUCKET=
|
|
1092
|
-
|
|
1093
|
-
${paymentsEnv}`);
|
|
1206
|
+
function cleanNestedArtifacts(root) {
|
|
1207
|
+
rmSync(path.join(root, 'node_modules'), { recursive: true, force: true });
|
|
1208
|
+
const appsRoot = path.join(root, 'apps');
|
|
1209
|
+
if (!pathEntryExists(appsRoot))
|
|
1210
|
+
return;
|
|
1211
|
+
for (const app of readdirSync(appsRoot, { withFileTypes: true })) {
|
|
1212
|
+
if (!app.isDirectory())
|
|
1213
|
+
continue;
|
|
1214
|
+
for (const artifact of ['.git', 'node_modules', 'package-lock.json', 'pnpm-lock.yaml', 'pnpm-workspace.yaml', 'yarn.lock']) {
|
|
1215
|
+
rmSync(path.join(appsRoot, app.name, artifact), { recursive: true, force: true });
|
|
1216
|
+
}
|
|
1217
|
+
}
|
|
1094
1218
|
}
|
|
1095
|
-
function
|
|
1096
|
-
|
|
1097
|
-
Extension/.wxt
|
|
1098
|
-
Extension/dist
|
|
1099
|
-
`);
|
|
1219
|
+
function selectedUiTargets(options) {
|
|
1220
|
+
return UI_TARGETS.filter((target) => options.apps[target]);
|
|
1100
1221
|
}
|
|
1101
|
-
function
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
push:
|
|
1107
|
-
branches:
|
|
1108
|
-
- main
|
|
1109
|
-
|
|
1110
|
-
permissions:
|
|
1111
|
-
contents: read
|
|
1112
|
-
|
|
1113
|
-
concurrency:
|
|
1114
|
-
group: ci-\${{ github.workflow }}-\${{ github.ref }}
|
|
1115
|
-
cancel-in-progress: true
|
|
1116
|
-
|
|
1117
|
-
jobs:
|
|
1118
|
-
verify:
|
|
1119
|
-
runs-on: ubuntu-latest
|
|
1120
|
-
timeout-minutes: 45
|
|
1121
|
-
steps:
|
|
1122
|
-
- name: Checkout
|
|
1123
|
-
uses: actions/checkout@v4
|
|
1124
|
-
|
|
1125
|
-
- name: Setup pnpm
|
|
1126
|
-
uses: pnpm/action-setup@v4
|
|
1127
|
-
with:
|
|
1128
|
-
version: 10.15.1
|
|
1129
|
-
|
|
1130
|
-
- name: Setup Node.js
|
|
1131
|
-
uses: actions/setup-node@v4
|
|
1132
|
-
with:
|
|
1133
|
-
node-version: 20
|
|
1134
|
-
cache: pnpm
|
|
1135
|
-
|
|
1136
|
-
- name: Install dependencies
|
|
1137
|
-
run: pnpm install --frozen-lockfile
|
|
1138
|
-
|
|
1139
|
-
- name: Check Expo dependency alignment
|
|
1140
|
-
run: pnpm --filter ./Frontend exec expo install --check
|
|
1141
|
-
|
|
1142
|
-
- name: Build Expo web
|
|
1143
|
-
run: pnpm --filter ./Frontend build:web
|
|
1144
|
-
|
|
1145
|
-
- name: Test API
|
|
1146
|
-
run: pnpm --filter ./Backend test
|
|
1147
|
-
|
|
1148
|
-
- name: Build API
|
|
1149
|
-
run: pnpm --filter ./Backend build
|
|
1150
|
-
|
|
1151
|
-
- name: Build extension
|
|
1152
|
-
run: pnpm --filter ./Extension build
|
|
1153
|
-
|
|
1154
|
-
- name: Zip extension
|
|
1155
|
-
run: pnpm --filter ./Extension zip
|
|
1156
|
-
|
|
1157
|
-
- name: Build workspace
|
|
1158
|
-
run: pnpm build
|
|
1159
|
-
`);
|
|
1222
|
+
function installSelectedUiComponents(root, options) {
|
|
1223
|
+
const installs = resolveUiInstalls(options.uiComponents, selectedUiTargets(options), options.nativeStyling);
|
|
1224
|
+
if (installs.length > 0 && !options.dryRun)
|
|
1225
|
+
installUiComponents(root, installs);
|
|
1226
|
+
return installs;
|
|
1160
1227
|
}
|
|
1161
|
-
function
|
|
1162
|
-
const
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
const
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1228
|
+
function installWorkspaceDependencies(root) {
|
|
1229
|
+
const executable = process.platform === 'win32' ? 'pnpm.cmd' : 'pnpm';
|
|
1230
|
+
execFile(executable, ['install', '--no-frozen-lockfile'], root);
|
|
1231
|
+
}
|
|
1232
|
+
async function writeSelectedModules(root, options) {
|
|
1233
|
+
const templates = materializeTemplates(root, resolveModules(options.modules).resolvedModules);
|
|
1234
|
+
const shared = projectOptions(options);
|
|
1235
|
+
scaffoldSharedPackages(root, shared);
|
|
1236
|
+
if (options.apps.api)
|
|
1237
|
+
await scaffoldApi(root, shared);
|
|
1238
|
+
if (options.apps.mobile)
|
|
1239
|
+
await scaffoldMobile(root, shared);
|
|
1240
|
+
if (options.apps.web)
|
|
1241
|
+
await scaffoldWeb(root, shared);
|
|
1242
|
+
if (options.apps.desktop)
|
|
1243
|
+
await scaffoldDesktop(root, shared);
|
|
1244
|
+
if (options.apps.extension)
|
|
1245
|
+
await scaffoldExtension(root, shared);
|
|
1246
|
+
if (options.features.storage)
|
|
1247
|
+
scaffoldAssetsPrivateProxy(root, shared);
|
|
1248
|
+
return templates;
|
|
1249
|
+
}
|
|
1250
|
+
function printPlan(operation, paths, json) {
|
|
1251
|
+
if (json) {
|
|
1252
|
+
console.log(JSON.stringify({ operation, paths }, null, 2));
|
|
1253
|
+
return;
|
|
1254
|
+
}
|
|
1255
|
+
anhedralPrint.info(`${operation} plan: ${paths.length} path${paths.length === 1 ? '' : 's'}`);
|
|
1256
|
+
for (const relativePath of paths)
|
|
1257
|
+
console.log(` ${relativePath}`);
|
|
1258
|
+
}
|
|
1259
|
+
function assertSafeChangedPaths(root, stageRoot, manifest, paths, deleting = new Set()) {
|
|
1260
|
+
for (const relativePath of paths) {
|
|
1261
|
+
if (relativePath === 'anhedral.json')
|
|
1262
|
+
continue;
|
|
1263
|
+
const target = path.join(root, relativePath);
|
|
1264
|
+
const record = manifest.files[relativePath];
|
|
1265
|
+
const targetStat = lstatIfPresent(target);
|
|
1266
|
+
if (targetStat?.isSymbolicLink())
|
|
1267
|
+
throw new Error(`Refusing to modify symbolic-link path: ${relativePath}`);
|
|
1268
|
+
if (targetStat && !record) {
|
|
1269
|
+
throw new Error(`Refusing to overwrite unowned path: ${relativePath}`);
|
|
1270
|
+
}
|
|
1271
|
+
if (!record || !targetStat)
|
|
1272
|
+
continue;
|
|
1273
|
+
assertManagedFileMode(relativePath, record, targetStat);
|
|
1274
|
+
const actualHash = hashContent(readFileSync(target));
|
|
1275
|
+
if (record.ownership === 'user') {
|
|
1276
|
+
throw new Error(`Refusing to modify user-owned path: ${relativePath}`);
|
|
1277
|
+
}
|
|
1278
|
+
if (record.ownership === 'managed' && actualHash !== record.hash) {
|
|
1279
|
+
throw new Error(`Managed file has user modifications: ${relativePath}`);
|
|
1280
|
+
}
|
|
1281
|
+
if (!deleting.has(relativePath) && !pathEntryExists(path.join(stageRoot, relativePath))) {
|
|
1282
|
+
throw new Error(`Internal plan error: staged path is missing: ${relativePath}`);
|
|
1283
|
+
}
|
|
1284
|
+
}
|
|
1285
|
+
}
|
|
1286
|
+
function stagedFileDiff(root, stageRoot, manifest) {
|
|
1287
|
+
const changed = [...collectFiles(stageRoot), 'anhedral.json'].filter((relativePath) => {
|
|
1288
|
+
const target = path.join(root, relativePath);
|
|
1289
|
+
const targetStat = lstatIfPresent(target);
|
|
1290
|
+
if (!targetStat)
|
|
1291
|
+
return true;
|
|
1292
|
+
if (targetStat.isSymbolicLink())
|
|
1293
|
+
throw new Error(`Refusing to compare symbolic-link path: ${relativePath}`);
|
|
1294
|
+
const stagedTarget = path.join(stageRoot, relativePath);
|
|
1295
|
+
const stagedStat = lstatSync(stagedTarget);
|
|
1296
|
+
const targetMode = normalizedFileMode(targetStat.mode);
|
|
1297
|
+
const stagedMode = normalizedFileMode(stagedStat.mode);
|
|
1298
|
+
return !readFileSync(target).equals(readFileSync(stagedTarget))
|
|
1299
|
+
|| (targetMode !== null && stagedMode !== null && targetMode !== stagedMode);
|
|
1187
1300
|
});
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1301
|
+
const deleted = Object.keys(manifest?.files ?? {}).filter((relativePath) => pathEntryExists(path.join(root, relativePath)) && !pathEntryExists(path.join(stageRoot, relativePath)));
|
|
1302
|
+
return { changed, deleted };
|
|
1303
|
+
}
|
|
1304
|
+
export async function scaffoldProject(inputOptions) {
|
|
1305
|
+
const options = canonicalInitOptions(inputOptions);
|
|
1306
|
+
assertInstallNodeCompatibility(options);
|
|
1307
|
+
const root = path.resolve(options.rootDirectory ?? process.cwd());
|
|
1308
|
+
let createdRoot = false;
|
|
1309
|
+
if (!pathEntryExists(root)) {
|
|
1310
|
+
mkdirSync(root);
|
|
1311
|
+
createdRoot = true;
|
|
1312
|
+
}
|
|
1313
|
+
const previousChannel = env.ANHEDRAL_TOOLCHAIN;
|
|
1314
|
+
env.ANHEDRAL_TOOLCHAIN = options.toolchainChannel;
|
|
1315
|
+
const commitPaths = [];
|
|
1316
|
+
const seedPaths = [];
|
|
1317
|
+
try {
|
|
1318
|
+
anhedralPrint.banner(`Initializing ${options.displayName}`);
|
|
1319
|
+
const planned = await runStagedTransaction(root, {
|
|
1320
|
+
commitPaths,
|
|
1321
|
+
seedPaths,
|
|
1322
|
+
dryRun: options.dryRun,
|
|
1323
|
+
prepare: () => {
|
|
1324
|
+
ensureScaffoldRoot(root);
|
|
1325
|
+
if (pathEntryExists(path.join(root, '.gitignore')))
|
|
1326
|
+
seedPaths.push('.gitignore');
|
|
1195
1327
|
},
|
|
1196
|
-
|
|
1197
|
-
|
|
1328
|
+
build: async (stageRoot) => {
|
|
1329
|
+
writeRootFiles(stageRoot, options, 'init', root);
|
|
1330
|
+
const templates = await writeSelectedModules(stageRoot, options);
|
|
1331
|
+
const components = installSelectedUiComponents(stageRoot, options);
|
|
1332
|
+
writeProjectDocs(stageRoot, options, true);
|
|
1333
|
+
cleanNestedArtifacts(stageRoot);
|
|
1334
|
+
rmSync(path.join(stageRoot, 'pnpm-lock.yaml'), { force: true });
|
|
1335
|
+
writeManifest(stageRoot, createProjectManifest(stageRoot, options, 'init', templates, undefined, components));
|
|
1336
|
+
commitPaths.push(...readdirSync(stageRoot));
|
|
1198
1337
|
},
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1338
|
+
afterCommit: () => {
|
|
1339
|
+
if (!options.skipInstall) {
|
|
1340
|
+
anhedralPrint.section('Workspace install');
|
|
1341
|
+
installWorkspaceDependencies(root);
|
|
1342
|
+
}
|
|
1202
1343
|
},
|
|
1203
|
-
}
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1344
|
+
});
|
|
1345
|
+
if (options.dryRun)
|
|
1346
|
+
printPlan('init', planned, options.json);
|
|
1347
|
+
if (!options.dryRun)
|
|
1348
|
+
anhedralPrint.done(`Committed ${planned.length} paths`);
|
|
1349
|
+
if (!options.dryRun && options.json)
|
|
1350
|
+
printPlan('init', planned, true);
|
|
1351
|
+
}
|
|
1352
|
+
finally {
|
|
1353
|
+
if (previousChannel == null)
|
|
1354
|
+
delete env.ANHEDRAL_TOOLCHAIN;
|
|
1355
|
+
else
|
|
1356
|
+
env.ANHEDRAL_TOOLCHAIN = previousChannel;
|
|
1357
|
+
if (createdRoot && pathEntryExists(root) && readdirSync(root).length === 0)
|
|
1358
|
+
rmdirSync(root);
|
|
1359
|
+
}
|
|
1218
1360
|
}
|
|
1219
|
-
async function
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
const
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1361
|
+
export async function scaffoldUiComponents(uiOptions) {
|
|
1362
|
+
const root = path.resolve(process.cwd());
|
|
1363
|
+
let manifest;
|
|
1364
|
+
let options;
|
|
1365
|
+
let additions = [];
|
|
1366
|
+
let components = [];
|
|
1367
|
+
let noOp = false;
|
|
1368
|
+
const seedPaths = [];
|
|
1369
|
+
const commitPaths = [];
|
|
1370
|
+
const previousChannel = env.ANHEDRAL_TOOLCHAIN;
|
|
1371
|
+
try {
|
|
1372
|
+
const planned = await runStagedTransaction(root, {
|
|
1373
|
+
seedPaths,
|
|
1374
|
+
commitPaths,
|
|
1375
|
+
dryRun: uiOptions.dryRun,
|
|
1376
|
+
prepare: () => {
|
|
1377
|
+
manifest = readProjectManifest(root);
|
|
1378
|
+
assertManagedFileModes(root, manifest);
|
|
1379
|
+
const installedTargets = UI_TARGETS.filter((target) => manifest.modules.includes(target));
|
|
1380
|
+
const targets = uiOptions.targets.length > 0 ? uiOptions.targets : installedTargets;
|
|
1381
|
+
if (targets.length === 0)
|
|
1382
|
+
throw new Error('This project has no UI client. Add web, mobile, desktop, or extension first.');
|
|
1383
|
+
for (const target of targets) {
|
|
1384
|
+
if (!manifest.modules.includes(target))
|
|
1385
|
+
throw new Error(`UI target is not installed: ${target}`);
|
|
1386
|
+
}
|
|
1387
|
+
const requested = resolveUiInstalls(uiOptions.components, targets, manifest.ui.nativeStyling);
|
|
1388
|
+
const installedKeys = new Set(manifest.ui.components.map(uiInstallKey));
|
|
1389
|
+
additions = requested.filter((entry) => !installedKeys.has(uiInstallKey(entry)));
|
|
1390
|
+
components = mergeUiInstalls(manifest.ui.components, additions);
|
|
1391
|
+
if (additions.length === 0) {
|
|
1392
|
+
noOp = true;
|
|
1393
|
+
return false;
|
|
1394
|
+
}
|
|
1395
|
+
options = {
|
|
1396
|
+
projectName: manifest.project.name,
|
|
1397
|
+
displayName: manifest.project.displayName,
|
|
1398
|
+
modules: [...manifest.modules],
|
|
1399
|
+
...selectionsFromModules(manifest.modules),
|
|
1400
|
+
skipInstall: uiOptions.skipInstall,
|
|
1401
|
+
dryRun: uiOptions.dryRun,
|
|
1402
|
+
json: uiOptions.json,
|
|
1403
|
+
toolchainChannel: toolchainChannelFromManifest(manifest),
|
|
1404
|
+
uiComponents: [],
|
|
1405
|
+
nativeStyling: manifest.ui.nativeStyling,
|
|
1406
|
+
};
|
|
1407
|
+
env.ANHEDRAL_TOOLCHAIN = options.toolchainChannel;
|
|
1408
|
+
seedPaths.push(...new Set([
|
|
1409
|
+
...Object.keys(manifest.files).filter((relativePath) => pathEntryExists(path.join(root, relativePath))),
|
|
1410
|
+
'anhedral.json',
|
|
1411
|
+
]));
|
|
1412
|
+
anhedralPrint.banner(`Adding UI components`);
|
|
1413
|
+
},
|
|
1414
|
+
build: async (stageRoot) => {
|
|
1415
|
+
if (!manifest || !options)
|
|
1416
|
+
throw new Error('Internal UI plan was not prepared.');
|
|
1417
|
+
if (!uiOptions.dryRun)
|
|
1418
|
+
installUiComponents(stageRoot, additions);
|
|
1419
|
+
cleanNestedArtifacts(stageRoot);
|
|
1420
|
+
rmSync(path.join(stageRoot, 'pnpm-lock.yaml'), { force: true });
|
|
1421
|
+
writeManifest(stageRoot, createProjectManifest(stageRoot, options, 'add', manifest.templates, manifest, components));
|
|
1422
|
+
const diff = stagedFileDiff(root, stageRoot, manifest);
|
|
1423
|
+
assertSafeChangedPaths(root, stageRoot, manifest, [...diff.changed, ...diff.deleted], new Set(diff.deleted));
|
|
1424
|
+
commitPaths.push(...diff.changed);
|
|
1425
|
+
},
|
|
1426
|
+
afterCommit: () => {
|
|
1427
|
+
if (!uiOptions.skipInstall)
|
|
1428
|
+
installWorkspaceDependencies(root);
|
|
1429
|
+
},
|
|
1430
|
+
});
|
|
1431
|
+
if (noOp) {
|
|
1432
|
+
if (uiOptions.json)
|
|
1433
|
+
console.log(JSON.stringify({ operation: 'ui-add', paths: [], components: [] }, null, 2));
|
|
1434
|
+
else
|
|
1435
|
+
anhedralPrint.info('All requested UI components are already installed in the selected clients.');
|
|
1436
|
+
return;
|
|
1437
|
+
}
|
|
1438
|
+
const componentPlan = additions.map((entry) => ({
|
|
1439
|
+
component: entry.name,
|
|
1440
|
+
target: entry.target,
|
|
1441
|
+
provider: entry.provider,
|
|
1442
|
+
source: entry.source,
|
|
1443
|
+
}));
|
|
1444
|
+
if (uiOptions.json) {
|
|
1445
|
+
console.log(JSON.stringify({ operation: 'ui-add', paths: planned, components: componentPlan }, null, 2));
|
|
1446
|
+
}
|
|
1447
|
+
else {
|
|
1448
|
+
anhedralPrint.info(`ui-add plan: ${componentPlan.length} installation${componentPlan.length === 1 ? '' : 's'}`);
|
|
1449
|
+
for (const entry of componentPlan)
|
|
1450
|
+
console.log(` ${entry.target}: ${entry.component} (${entry.provider})`);
|
|
1451
|
+
for (const relativePath of planned)
|
|
1452
|
+
console.log(` ${relativePath}`);
|
|
1453
|
+
}
|
|
1454
|
+
}
|
|
1455
|
+
finally {
|
|
1456
|
+
if (previousChannel == null)
|
|
1457
|
+
delete env.ANHEDRAL_TOOLCHAIN;
|
|
1458
|
+
else
|
|
1459
|
+
env.ANHEDRAL_TOOLCHAIN = previousChannel;
|
|
1460
|
+
}
|
|
1261
1461
|
}
|
|
1262
|
-
export async function
|
|
1462
|
+
export async function scaffoldAddModules(addOptions) {
|
|
1263
1463
|
const root = path.resolve(process.cwd());
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1464
|
+
let manifest;
|
|
1465
|
+
let options;
|
|
1466
|
+
let missing = [];
|
|
1467
|
+
let noOp = false;
|
|
1468
|
+
const seedPaths = [];
|
|
1469
|
+
const commitPaths = [];
|
|
1470
|
+
const deletePaths = [];
|
|
1471
|
+
const previousChannel = env.ANHEDRAL_TOOLCHAIN;
|
|
1267
1472
|
try {
|
|
1268
|
-
await
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1473
|
+
const planned = await runStagedTransaction(root, {
|
|
1474
|
+
commitPaths,
|
|
1475
|
+
deletePaths,
|
|
1476
|
+
seedPaths,
|
|
1477
|
+
dryRun: addOptions.dryRun,
|
|
1478
|
+
prepare: () => {
|
|
1479
|
+
manifest = readProjectManifest(root);
|
|
1480
|
+
assertManagedFileModes(root, manifest);
|
|
1481
|
+
const desiredRequested = [...new Set([...manifest.modules, ...addOptions.modules])];
|
|
1482
|
+
const resolution = resolveModules(desiredRequested);
|
|
1483
|
+
const installed = new Set(manifest.modules);
|
|
1484
|
+
missing = resolution.resolvedModules.filter((moduleId) => !installed.has(moduleId));
|
|
1485
|
+
if (!missing.length) {
|
|
1486
|
+
noOp = true;
|
|
1487
|
+
return false;
|
|
1488
|
+
}
|
|
1489
|
+
options = optionsFromManifest(manifest, addOptions, resolution.requestedModules);
|
|
1490
|
+
assertInstallNodeCompatibility(options);
|
|
1491
|
+
env.ANHEDRAL_TOOLCHAIN = options.toolchainChannel;
|
|
1492
|
+
seedPaths.push(...new Set([
|
|
1493
|
+
...Object.keys(manifest.files).filter((relativePath) => pathEntryExists(path.join(root, relativePath))),
|
|
1494
|
+
'anhedral.json',
|
|
1495
|
+
]));
|
|
1496
|
+
anhedralPrint.banner(`Adding ${missing.join(', ')}`);
|
|
1497
|
+
},
|
|
1498
|
+
build: async (stageRoot) => {
|
|
1499
|
+
if (!manifest || !options)
|
|
1500
|
+
throw new Error('Internal add plan was not prepared.');
|
|
1501
|
+
writeRootFiles(stageRoot, options, 'add', root, manifest);
|
|
1502
|
+
const templates = await writeSelectedModules(stageRoot, options);
|
|
1503
|
+
writeProjectDocs(stageRoot, options, false);
|
|
1504
|
+
cleanNestedArtifacts(stageRoot);
|
|
1505
|
+
writeManifest(stageRoot, createProjectManifest(stageRoot, options, 'add', templates, manifest));
|
|
1506
|
+
const diff = stagedFileDiff(root, stageRoot, manifest);
|
|
1507
|
+
assertSafeChangedPaths(root, stageRoot, manifest, [...diff.changed, ...diff.deleted], new Set(diff.deleted));
|
|
1508
|
+
commitPaths.push(...diff.changed);
|
|
1509
|
+
deletePaths.push(...diff.deleted);
|
|
1510
|
+
},
|
|
1511
|
+
afterCommit: () => {
|
|
1512
|
+
if (!addOptions.skipInstall)
|
|
1513
|
+
installWorkspaceDependencies(root);
|
|
1514
|
+
},
|
|
1515
|
+
});
|
|
1516
|
+
if (noOp) {
|
|
1517
|
+
if (addOptions.json)
|
|
1518
|
+
console.log(JSON.stringify({ operation: 'add', paths: [] }, null, 2));
|
|
1519
|
+
else
|
|
1520
|
+
anhedralPrint.info('All requested modules are already installed.');
|
|
1521
|
+
return;
|
|
1284
1522
|
}
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
console.log(' cp Extension/.env.example Extension/.env');
|
|
1290
|
-
console.log(' pnpm db:generate && pnpm db:migrate');
|
|
1291
|
-
console.log(' pnpm verify');
|
|
1292
|
-
console.log(' pnpm dev:backend');
|
|
1293
|
-
console.log(' pnpm dev:frontend');
|
|
1294
|
-
console.log(' pnpm dev:extension');
|
|
1295
|
-
console.log('');
|
|
1523
|
+
if (addOptions.dryRun || !addOptions.json)
|
|
1524
|
+
printPlan('add', planned, addOptions.json);
|
|
1525
|
+
if (!addOptions.dryRun && addOptions.json)
|
|
1526
|
+
printPlan('add', planned, true);
|
|
1296
1527
|
}
|
|
1297
1528
|
finally {
|
|
1298
|
-
if (
|
|
1529
|
+
if (previousChannel == null)
|
|
1299
1530
|
delete env.ANHEDRAL_TOOLCHAIN;
|
|
1531
|
+
else
|
|
1532
|
+
env.ANHEDRAL_TOOLCHAIN = previousChannel;
|
|
1533
|
+
}
|
|
1534
|
+
}
|
|
1535
|
+
export function doctorProject() {
|
|
1536
|
+
const root = path.resolve(process.cwd());
|
|
1537
|
+
const filePath = path.join(root, 'anhedral.json');
|
|
1538
|
+
if (!pathEntryExists(filePath))
|
|
1539
|
+
throw new Error('anhedral.json was not found. Run anhedral init first.');
|
|
1540
|
+
const manifest = readManifest(readFileSync(filePath, 'utf8'));
|
|
1541
|
+
const issues = [];
|
|
1542
|
+
for (const entry of readdirSync(root, { withFileTypes: true })) {
|
|
1543
|
+
if (!isTransactionMetadata(entry.name))
|
|
1544
|
+
continue;
|
|
1545
|
+
if (entry.name === '.anhedral-journal.json') {
|
|
1546
|
+
issues.push({ path: entry.name, severity: 'error', message: 'An interrupted transaction requires recovery by init or add.' });
|
|
1547
|
+
}
|
|
1548
|
+
else if (entry.name.startsWith('.anhedral-journal.json.tmp-')) {
|
|
1549
|
+
issues.push({ path: entry.name, severity: 'error', message: 'An incomplete transaction journal artifact requires manual inspection.' });
|
|
1300
1550
|
}
|
|
1301
1551
|
else {
|
|
1302
|
-
|
|
1552
|
+
issues.push({ path: entry.name, severity: 'error', message: 'An Anhedral operation is running or left a transaction-lock artifact.' });
|
|
1303
1553
|
}
|
|
1304
1554
|
}
|
|
1555
|
+
if (manifest.generatorVersion !== GENERATOR_VERSION) {
|
|
1556
|
+
issues.push({
|
|
1557
|
+
path: 'anhedral.json',
|
|
1558
|
+
severity: 'error',
|
|
1559
|
+
message: `Project generator ${manifest.generatorVersion} differs from CLI ${GENERATOR_VERSION}; regenerate with the current CLI.`,
|
|
1560
|
+
});
|
|
1561
|
+
}
|
|
1562
|
+
try {
|
|
1563
|
+
assertTemplateProvenance(manifest.modules, manifest.templates);
|
|
1564
|
+
}
|
|
1565
|
+
catch (error) {
|
|
1566
|
+
issues.push({
|
|
1567
|
+
path: 'anhedral.json',
|
|
1568
|
+
severity: 'error',
|
|
1569
|
+
message: error instanceof Error ? error.message : 'Template provenance is invalid.',
|
|
1570
|
+
});
|
|
1571
|
+
}
|
|
1572
|
+
for (const [relativePath, record] of Object.entries(manifest.files)) {
|
|
1573
|
+
const target = path.join(root, relativePath);
|
|
1574
|
+
const targetStat = lstatIfPresent(target);
|
|
1575
|
+
if (!targetStat) {
|
|
1576
|
+
issues.push({ path: relativePath, severity: 'error', message: 'Recorded file is missing.' });
|
|
1577
|
+
continue;
|
|
1578
|
+
}
|
|
1579
|
+
if (targetStat.isSymbolicLink()) {
|
|
1580
|
+
issues.push({ path: relativePath, severity: 'error', message: 'Recorded path is a symbolic link.' });
|
|
1581
|
+
continue;
|
|
1582
|
+
}
|
|
1583
|
+
if (!targetStat.isFile()) {
|
|
1584
|
+
issues.push({ path: relativePath, severity: 'error', message: 'Recorded path is not a regular file.' });
|
|
1585
|
+
continue;
|
|
1586
|
+
}
|
|
1587
|
+
const actual = hashContent(readFileSync(target));
|
|
1588
|
+
if (actual !== record.hash) {
|
|
1589
|
+
issues.push({
|
|
1590
|
+
path: relativePath,
|
|
1591
|
+
severity: record.ownership === 'managed' ? 'error' : 'warning',
|
|
1592
|
+
message: `${record.ownership} file differs from its recorded hash.`,
|
|
1593
|
+
});
|
|
1594
|
+
}
|
|
1595
|
+
if (record.mode !== null) {
|
|
1596
|
+
const actualMode = normalizedFileMode(targetStat.mode);
|
|
1597
|
+
if (actualMode !== null && actualMode !== record.mode) {
|
|
1598
|
+
issues.push({
|
|
1599
|
+
path: relativePath,
|
|
1600
|
+
severity: record.ownership === 'managed' ? 'error' : 'warning',
|
|
1601
|
+
message: `${record.ownership} file mode differs from its recorded mode `
|
|
1602
|
+
+ `(${displayFileMode(record.mode)} expected, ${displayFileMode(actualMode)} found).`,
|
|
1603
|
+
});
|
|
1604
|
+
}
|
|
1605
|
+
}
|
|
1606
|
+
}
|
|
1607
|
+
return {
|
|
1608
|
+
ok: !issues.some((issue) => issue.severity === 'error'),
|
|
1609
|
+
schemaVersion: manifest.schemaVersion,
|
|
1610
|
+
generatorVersion: manifest.generatorVersion,
|
|
1611
|
+
issues,
|
|
1612
|
+
};
|
|
1305
1613
|
}
|