anhedral 0.17.0 → 0.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +33 -68
- package/assets/contracts/LICENSE +201 -0
- package/assets/contracts/LICENSE.environment +201 -0
- package/assets/contracts/LICENSE.operations +201 -0
- package/assets/contracts/deployment-provenance.json +15 -0
- package/assets/contracts/environment-provenance.json +11 -0
- package/assets/contracts/operations-provenance.json +12 -0
- package/assets/launch/application.server.ts.txt +13 -0
- package/assets/launch/auth-client.ts.txt +4 -0
- package/assets/launch/home.tsx.txt +20 -0
- package/assets/launch/minimal-application.server.ts.txt +5 -0
- package/assets/launch/minimal-server.ts.txt +7 -0
- package/assets/launch/oj/OJ.LICENSE +21 -0
- package/assets/launch/oj/run.mjs +82 -0
- package/assets/launch/oj/runtime.json +21 -0
- package/assets/launch/request-context.ts.txt +3 -0
- package/assets/launch/root.tsx.txt +26 -0
- package/assets/launch/router.tsx.txt +21 -0
- package/assets/launch/server.ts.txt +15 -0
- package/assets/launch/sign-in.tsx.txt +53 -0
- package/assets/launch/styles.css.txt +19 -0
- package/assets/security/credential-patterns.d.mts +3 -0
- package/assets/security/credential-patterns.mjs +59 -0
- package/assets/stack/api-index.ts.txt +6 -1
- package/assets/stack/stripe.ts.txt +30 -13
- package/assets/ui/catalog.json +36 -324
- package/dist/{platforms/web.d.ts → api-proxy.d.ts} +1 -3
- package/dist/api-proxy.js +48 -0
- package/dist/bin.js +55 -36
- package/dist/capability-catalog.d.ts +36 -57
- package/dist/capability-catalog.js +65 -67
- package/dist/capability-command.d.ts +3 -3
- package/dist/capability-command.js +146 -59
- package/dist/capability-editor.js +6 -5
- package/dist/capability-recipes.js +9 -296
- package/dist/cli-arguments.d.ts +2 -0
- package/dist/cli-arguments.js +101 -50
- package/dist/cli-commands.d.ts +1 -1
- package/dist/cli-commands.js +31 -5
- package/dist/cli-errors.d.ts +18 -0
- package/dist/cli-errors.js +63 -0
- package/dist/cli-output.d.ts +22 -0
- package/dist/cli-output.js +42 -7
- package/dist/command-runner.js +88 -0
- package/dist/command-schema.d.ts +16 -0
- package/dist/command-schema.js +496 -21
- package/dist/command-types.d.ts +1 -0
- package/dist/command-types.js +1 -0
- package/dist/completion.d.ts +2 -0
- package/dist/completion.js +201 -0
- package/dist/composition.d.ts +25 -0
- package/dist/composition.js +28 -0
- package/dist/contracts/cli-transport.d.ts +316 -0
- package/dist/contracts/cli-transport.js +236 -0
- package/dist/contracts/deployment.d.ts +233 -0
- package/dist/contracts/deployment.js +198 -0
- package/dist/contracts/environment-file.d.ts +7 -0
- package/dist/contracts/environment-file.js +112 -0
- package/dist/contracts/environment-transport.d.ts +79 -0
- package/dist/contracts/environment-transport.js +110 -0
- package/dist/contracts/production-transport.d.ts +71 -0
- package/dist/contracts/production-transport.js +56 -0
- package/dist/contracts/runtime-logs-transport.d.ts +127 -0
- package/dist/contracts/runtime-logs-transport.js +50 -0
- package/dist/contracts/source-bundle.d.ts +11 -0
- package/dist/contracts/source-bundle.js +197 -0
- package/dist/contracts/source-profile.d.ts +4 -0
- package/dist/contracts/source-profile.js +5 -0
- package/dist/contracts/staging-transport.d.ts +79 -0
- package/dist/contracts/staging-transport.js +43 -0
- package/dist/dependencies.d.ts +9 -27
- package/dist/dependencies.js +19 -66
- package/dist/index.d.ts +4 -2
- package/dist/index.js +3 -1
- package/dist/launch.d.ts +27 -0
- package/dist/launch.js +262 -0
- package/dist/platform-command.d.ts +9 -0
- package/dist/platform-command.js +787 -0
- package/dist/platform-environment.d.ts +18 -0
- package/dist/platform-environment.js +257 -0
- package/dist/platform-operations.d.ts +26 -0
- package/dist/platform-operations.js +155 -0
- package/dist/platform-production.d.ts +16 -0
- package/dist/platform-production.js +135 -0
- package/dist/platform-source.d.ts +8 -0
- package/dist/platform-source.js +111 -0
- package/dist/platform-state.d.ts +15 -0
- package/dist/platform-state.js +229 -0
- package/dist/platforms/tanstack.d.ts +10 -0
- package/dist/platforms/tanstack.js +248 -0
- package/dist/registry/usage.d.ts +4 -1
- package/dist/registry/usage.js +59 -4
- package/dist/scaffold/bootstrap.d.ts +3 -3
- package/dist/scaffold/styling.d.ts +3 -2
- package/dist/transaction.js +28 -3
- package/dist/ui-catalog.d.ts +3 -5
- package/dist/ui-catalog.js +8 -24
- package/dist/ui-command.d.ts +3 -1
- package/dist/ui-command.js +74 -72
- package/dist/ui-project.d.ts +4 -2
- package/dist/ui-project.js +40 -38
- package/dist/util.js +40 -61
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/docs/capabilities.md +23 -89
- package/docs/software-factory.md +208 -9
- package/docs/stack-standard.md +7 -17
- package/docs/ui.md +9 -22
- package/package.json +26 -22
- package/assets/stack/ai-schema.ts.txt +0 -5
- package/assets/stack/ai.ts.txt +0 -30
- package/assets/stack/desktop.rs.txt +0 -21
- package/assets/stack/events-schema.ts.txt +0 -12
- package/assets/stack/events.ts.txt +0 -59
- package/assets/stack/mobile-auth.ts.txt +0 -25
- package/assets/stack/mobile-billing.tsx.txt +0 -63
- package/assets/stack/mobile-session.tsx.txt +0 -83
- package/assets/stack/native-button.tsx.txt +0 -108
- package/assets/stack/native-global.css.txt +0 -4
- package/assets/stack/native-lib-utils.ts.txt +0 -5
- package/assets/stack/native-metro.config.js.txt +0 -6
- package/assets/stack/native-nativewind-env.d.ts.txt +0 -1
- package/assets/stack/native-tailwind.config.js.txt +0 -73
- package/assets/stack/native-text.tsx.txt +0 -89
- package/assets/stack/purchases.ts.txt +0 -65
- package/assets/stack/revenuecat.ts.txt +0 -88
- package/assets/stack/rtc-schema.ts.txt +0 -10
- package/assets/stack/rtc.ts.txt +0 -122
- package/assets/stack/web-sign-in.tsx.txt +0 -51
- package/dist/capabilities.d.ts +0 -11
- package/dist/capabilities.js +0 -14
- package/dist/dependency-order.d.ts +0 -2
- package/dist/dependency-order.js +0 -24
- package/dist/platforms/lint.d.ts +0 -1
- package/dist/platforms/lint.js +0 -5
- package/dist/platforms/web.js +0 -251
- package/dist/project-config.d.ts +0 -3
- package/dist/project-config.js +0 -16
- package/dist/registry/context.d.ts +0 -3
- package/dist/registry/context.js +0 -20
- package/dist/registry/options.d.ts +0 -2
- package/dist/registry/options.js +0 -44
- package/dist/registry/resolve.d.ts +0 -11
- package/dist/registry/resolve.js +0 -46
- package/dist/registry/types.d.ts +0 -60
- package/dist/scaffold/api.d.ts +0 -2
- package/dist/scaffold/api.js +0 -38
- package/dist/scaffold/backend.d.ts +0 -2
- package/dist/scaffold/backend.js +0 -36
- package/dist/scaffold/compose.d.ts +0 -4
- package/dist/scaffold/compose.js +0 -30
- package/dist/scaffold/database.d.ts +0 -2
- package/dist/scaffold/database.js +0 -41
- package/dist/scaffold/documentation.d.ts +0 -2
- package/dist/scaffold/documentation.js +0 -71
- package/dist/scaffold/environment.d.ts +0 -4
- package/dist/scaffold/environment.js +0 -22
- package/dist/scaffold/stack-documentation.d.ts +0 -2
- package/dist/scaffold/stack-documentation.js +0 -6
- package/dist/scaffold/storage.d.ts +0 -2
- package/dist/scaffold/storage.js +0 -21
- package/dist/scaffold/workspace.d.ts +0 -3
- package/dist/scaffold/workspace.js +0 -131
- package/dist/stack-registry.d.ts +0 -35
- package/dist/stack-registry.js +0 -189
- package/dist/standard.d.ts +0 -8
- package/dist/standard.js +0 -94
- package/dist/workspace-graph.d.ts +0 -7
- package/dist/workspace-graph.js +0 -74
- package/docs/anhedral-stack.md +0 -12
- package/docs/assets/anhedral-stack-light.png +0 -0
- package/docs/assets/anhedral-stack.png +0 -0
- package/docs/native-ui.md +0 -47
- /package/dist/{registry/types.js → command-runner.d.ts} +0 -0
package/dist/platforms/web.js
DELETED
|
@@ -1,251 +0,0 @@
|
|
|
1
|
-
import { initializeUiMetadata } from '../ui-project.js';
|
|
2
|
-
import { readFileSync } from 'node:fs';
|
|
3
|
-
import { fileURLToPath } from 'node:url';
|
|
4
|
-
import path from 'node:path';
|
|
5
|
-
import { resourceName, childPackageName, jsString } from '../render.js';
|
|
6
|
-
import { WEB_DEPENDENCIES } from '../dependencies.js';
|
|
7
|
-
import { json, put, workerConfig } from '../scaffold/files.js';
|
|
8
|
-
export function scaffoldWeb({ root, options, has }) {
|
|
9
|
-
const app = 'apps/web';
|
|
10
|
-
json(root, `${app}/package.json`, {
|
|
11
|
-
name: childPackageName(options.name, 'web'),
|
|
12
|
-
private: true,
|
|
13
|
-
version: '0.1.0',
|
|
14
|
-
type: 'module',
|
|
15
|
-
scripts: {
|
|
16
|
-
dev: 'next dev --turbopack --hostname 0.0.0.0 --port 3000',
|
|
17
|
-
'build:next': 'next build --webpack',
|
|
18
|
-
build: 'opennextjs-cloudflare build && pnpm build:worker',
|
|
19
|
-
'build:worker': 'wrangler deploy --dry-run --outdir dist',
|
|
20
|
-
preview: 'wrangler dev --port 3000 --inspector-port 9230',
|
|
21
|
-
deploy: 'wrangler deploy',
|
|
22
|
-
start: 'next start --hostname 0.0.0.0 --port 3000',
|
|
23
|
-
typecheck: 'next typegen && tsc --noEmit',
|
|
24
|
-
lint: 'eslint . --max-warnings 0',
|
|
25
|
-
},
|
|
26
|
-
dependencies: {
|
|
27
|
-
...WEB_DEPENDENCIES.dependencies,
|
|
28
|
-
...(has('hono') ? { '@workspace/contracts': 'workspace:*' } : {}),
|
|
29
|
-
'@workspace/styling': 'workspace:*',
|
|
30
|
-
},
|
|
31
|
-
devDependencies: {
|
|
32
|
-
...WEB_DEPENDENCIES.devDependencies,
|
|
33
|
-
'@workspace/eslint-config': 'workspace:*',
|
|
34
|
-
},
|
|
35
|
-
});
|
|
36
|
-
json(root, `${app}/wrangler.jsonc`, {
|
|
37
|
-
...workerConfig(resourceName(options.name, 'web')),
|
|
38
|
-
main: '.open-next/worker.js',
|
|
39
|
-
compatibility_flags: ['nodejs_compat', 'global_fetch_strictly_public'],
|
|
40
|
-
assets: { directory: '.open-next/assets', binding: 'ASSETS' },
|
|
41
|
-
services: [
|
|
42
|
-
...(has('hono')
|
|
43
|
-
? [{ binding: 'ANHEDRAL_API', service: resourceName(options.name, 'api') }]
|
|
44
|
-
: []),
|
|
45
|
-
{ binding: 'WORKER_SELF_REFERENCE', service: resourceName(options.name, 'web') },
|
|
46
|
-
],
|
|
47
|
-
});
|
|
48
|
-
put(root, `${app}/next.config.ts`, `import type { NextConfig } from 'next';
|
|
49
|
-
const previewOrigin = process.env.NODE_ENV === 'development' ? process.env.ANHEDRAL_PREVIEW_ORIGIN : undefined;
|
|
50
|
-
let allowedDevOrigins: string[] = [];
|
|
51
|
-
if (previewOrigin) {
|
|
52
|
-
const url = new URL(previewOrigin);
|
|
53
|
-
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.pathname !== '/' || url.search || url.hash) throw new Error('ANHEDRAL_PREVIEW_ORIGIN must be an HTTP(S) origin.');
|
|
54
|
-
allowedDevOrigins = [url.hostname];
|
|
55
|
-
}
|
|
56
|
-
const config: NextConfig = { allowedDevOrigins, transpilePackages: ${JSON.stringify(has('hono') ? ['@workspace/contracts', '@workspace/styling'] : ['@workspace/styling'])}, images: { unoptimized: true } };
|
|
57
|
-
export default config;
|
|
58
|
-
`);
|
|
59
|
-
put(root, `${app}/open-next.config.ts`, `import { defineCloudflareConfig } from '@opennextjs/cloudflare';
|
|
60
|
-
const config = { ...defineCloudflareConfig(), buildCommand: 'pnpm build:next' };
|
|
61
|
-
export default config;
|
|
62
|
-
`);
|
|
63
|
-
json(root, `${app}/tsconfig.json`, {
|
|
64
|
-
compilerOptions: {
|
|
65
|
-
target: 'ES2022',
|
|
66
|
-
lib: ['DOM', 'DOM.Iterable', 'ES2022'],
|
|
67
|
-
allowJs: true,
|
|
68
|
-
skipLibCheck: true,
|
|
69
|
-
strict: true,
|
|
70
|
-
noEmit: true,
|
|
71
|
-
esModuleInterop: true,
|
|
72
|
-
module: 'ESNext',
|
|
73
|
-
moduleResolution: 'Bundler',
|
|
74
|
-
resolveJsonModule: true,
|
|
75
|
-
isolatedModules: true,
|
|
76
|
-
jsx: 'react-jsx',
|
|
77
|
-
incremental: true,
|
|
78
|
-
plugins: [{ name: 'next' }],
|
|
79
|
-
paths: { '@/*': ['./*'] },
|
|
80
|
-
},
|
|
81
|
-
include: [
|
|
82
|
-
'next-env.d.ts',
|
|
83
|
-
'**/*.ts',
|
|
84
|
-
'**/*.tsx',
|
|
85
|
-
'.next/types/**/*.ts',
|
|
86
|
-
'.next/dev/types/**/*.ts',
|
|
87
|
-
],
|
|
88
|
-
exclude: ['node_modules', '.open-next', 'dist'],
|
|
89
|
-
});
|
|
90
|
-
put(root, `${app}/next-env.d.ts`, '/// <reference types="next" />\n/// <reference types="next/image-types/global" />\n');
|
|
91
|
-
put(root, `${app}/eslint.config.mjs`, `import { defineConfig, globalIgnores } from 'eslint/config';
|
|
92
|
-
import next from 'eslint-config-next/core-web-vitals';
|
|
93
|
-
import ts from 'eslint-config-next/typescript';
|
|
94
|
-
export default defineConfig([...next, ...ts, globalIgnores(['.next/**', '.open-next/**', 'dist/**', 'next-env.d.ts', 'worker-configuration.d.ts'])]);
|
|
95
|
-
`);
|
|
96
|
-
json(root, `${app}/components.json`, {
|
|
97
|
-
$schema: 'https://ui.shadcn.com/schema.json',
|
|
98
|
-
style: 'base-nova',
|
|
99
|
-
rsc: true,
|
|
100
|
-
tsx: true,
|
|
101
|
-
tailwind: { config: '', css: 'app/globals.css', baseColor: 'neutral', cssVariables: true },
|
|
102
|
-
aliases: {
|
|
103
|
-
components: '@/components',
|
|
104
|
-
ui: '@/components/ui',
|
|
105
|
-
utils: '@/lib/utils',
|
|
106
|
-
lib: '@/lib',
|
|
107
|
-
hooks: '@/hooks',
|
|
108
|
-
},
|
|
109
|
-
iconLibrary: 'lucide',
|
|
110
|
-
});
|
|
111
|
-
initializeUiMetadata(path.join(root, app), 'web');
|
|
112
|
-
put(root, `${app}/lib/utils.ts`, `import { clsx, type ClassValue } from 'clsx';
|
|
113
|
-
import { twMerge } from 'tailwind-merge';
|
|
114
|
-
export function cn(...values: ClassValue[]) { return twMerge(clsx(values)); }
|
|
115
|
-
`);
|
|
116
|
-
for (const component of ['button', 'input', 'label'])
|
|
117
|
-
put(root, `${app}/components/ui/${component}.tsx`, readFileSync(fileURLToPath(new URL(`../../assets/ui/web/${component}.tsx`, import.meta.url)), 'utf8'));
|
|
118
|
-
for (const file of ['LICENSE.shadcn', 'UPSTREAM.json'])
|
|
119
|
-
put(root, `${app}/${file}`, readFileSync(fileURLToPath(new URL(`../../assets/ui/${file}`, import.meta.url)), 'utf8'));
|
|
120
|
-
put(root, `${app}/postcss.config.mjs`, "const config = { plugins: { '@tailwindcss/postcss': {} } };\nexport default config;\n");
|
|
121
|
-
put(root, `${app}/app/globals.css`, `@import 'tailwindcss';
|
|
122
|
-
@import '@workspace/styling/globals.css';
|
|
123
|
-
@theme inline {
|
|
124
|
-
--color-background: hsl(var(--background)); --color-foreground: hsl(var(--foreground));
|
|
125
|
-
--color-primary: hsl(var(--primary)); --color-primary-foreground: hsl(var(--primary-foreground));
|
|
126
|
-
--color-secondary: hsl(var(--secondary)); --color-secondary-foreground: hsl(var(--secondary-foreground));
|
|
127
|
-
--color-muted: hsl(var(--muted)); --color-muted-foreground: hsl(var(--muted-foreground));
|
|
128
|
-
--color-border: hsl(var(--border)); --color-input: hsl(var(--input)); --color-ring: hsl(var(--ring));
|
|
129
|
-
--color-destructive: hsl(var(--destructive)); --radius-md: var(--radius); --radius-lg: calc(var(--radius) + 2px);
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
* { box-sizing: border-box; } body { margin: 0; background: hsl(var(--background)); color: hsl(var(--foreground)); font-family: Arial, Helvetica, sans-serif; }
|
|
133
|
-
h1 { font-size: 2rem; font-weight: 600; line-height: 1.2; letter-spacing: -.025em; } h2 { font-size: 1.25rem; font-weight: 600; line-height: 1.4; }
|
|
134
|
-
main { max-width: 64rem; margin: 0 auto; padding: 4rem 1.5rem; } nav, form, .stack { display: flex; gap: 1rem; } form, .stack { flex-direction: column; } form { max-width: 26rem; } label { display: grid; gap: .5rem; }
|
|
135
|
-
a { color: inherit; } .button, input { min-height: 2.75rem; padding: .65rem 1rem; border: 1px solid hsl(var(--border)); border-radius: var(--radius); font: inherit; }
|
|
136
|
-
.button { cursor: pointer; background: hsl(var(--primary)); color: hsl(var(--primary-foreground)); } .button:disabled { opacity: .5; cursor: default; } input { background: hsl(var(--background)); color: inherit; }
|
|
137
|
-
:focus-visible { outline: 2px solid hsl(var(--ring)); outline-offset: 3px; } .muted { color: hsl(var(--muted-foreground)); }
|
|
138
|
-
`);
|
|
139
|
-
put(root, `${app}/app/layout.tsx`, `import type { Metadata } from 'next';
|
|
140
|
-
import Link from 'next/link';
|
|
141
|
-
import './globals.css';
|
|
142
|
-
export const metadata: Metadata = { title: ${jsString(options.name)}, description: 'Anhedral application' };
|
|
143
|
-
export default function Layout({ children }: { children: React.ReactNode }) { return <html lang="en"><body><main><nav aria-label="Main"><Link href="/">Home</Link></nav>{children}</main></body></html>; }
|
|
144
|
-
`);
|
|
145
|
-
put(root, `${app}/app/page.tsx`, `import { FoundationExample } from '@/components/foundation-example';
|
|
146
|
-
export default function Home() {
|
|
147
|
-
return <section className="stack"><h1>${escapeJsx(options.name)}</h1><p>Next.js on Cloudflare, with Anhedral UI.</p><p className="muted" data-rendering="server">Prerendered at build time; ready to hydrate in the browser.</p><FoundationExample /></section>;
|
|
148
|
-
}
|
|
149
|
-
`);
|
|
150
|
-
put(root, `${app}/components/foundation-example.tsx`, `'use client';
|
|
151
|
-
import { useState } from 'react';
|
|
152
|
-
import { Button } from '@/components/ui/button';
|
|
153
|
-
import { Input } from '@/components/ui/input';
|
|
154
|
-
import { Label } from '@/components/ui/label';
|
|
155
|
-
export function FoundationExample() {
|
|
156
|
-
const [idea, setIdea] = useState('My next application');
|
|
157
|
-
return <section className="stack"><Label htmlFor="idea">What will you build?</Label><Input id="idea" value={idea} onChange={event => setIdea(event.target.value)} /><p aria-live="polite">{idea}</p><Button onClick={() => setIdea('My next application')}>Reset example</Button></section>;
|
|
158
|
-
}
|
|
159
|
-
`);
|
|
160
|
-
put(root, `${app}/app/loading.tsx`, `export default function Loading() { return <p role="status">Loading…</p>; }\n`);
|
|
161
|
-
put(root, `${app}/app/error.tsx`, `'use client';\nexport default function ErrorPage({ reset }: { reset: () => void }) { return <section><h1>Unable to load this page</h1><button onClick={reset}>Try again</button></section>; }\n`);
|
|
162
|
-
put(root, `${app}/public/_headers`, '/_next/static/*\n Cache-Control: public, max-age=31536000, immutable\n/*\n X-Content-Type-Options: nosniff\n');
|
|
163
|
-
put(root, `${app}/public/robots.txt`, 'User-agent: *\nAllow: /\n');
|
|
164
|
-
if (!has('hono'))
|
|
165
|
-
return;
|
|
166
|
-
put(root, `${app}/lib/api-proxy.ts`, WEB_API_PROXY);
|
|
167
|
-
put(root, `${app}/lib/server-api.ts`, `import 'server-only';
|
|
168
|
-
import { getCloudflareContext } from '@opennextjs/cloudflare';
|
|
169
|
-
import { proxyApi, type ApiBinding } from './api-proxy';
|
|
170
|
-
function isApiBinding(value: unknown): value is ApiBinding {
|
|
171
|
-
return typeof value === 'object' && value !== null && typeof Reflect.get(value, 'fetch') === 'function';
|
|
172
|
-
}
|
|
173
|
-
async function productionBinding(): Promise<ApiBinding | undefined> {
|
|
174
|
-
const { env } = await getCloudflareContext({ async: true });
|
|
175
|
-
const candidate: unknown = Reflect.get(env, 'ANHEDRAL_API');
|
|
176
|
-
return isApiBinding(candidate) ? candidate : undefined;
|
|
177
|
-
}
|
|
178
|
-
export async function apiRequest(request: Request): Promise<Response> {
|
|
179
|
-
const development = process.env.NODE_ENV === 'development';
|
|
180
|
-
const binding = development ? undefined : await productionBinding();
|
|
181
|
-
return proxyApi(request, { binding, development, devOrigin: process.env.API_INTERNAL_URL });
|
|
182
|
-
}
|
|
183
|
-
`);
|
|
184
|
-
put(root, `${app}/app/api/[[...path]]/route.ts`, `import { apiRequest } from '@/lib/server-api';
|
|
185
|
-
export const dynamic = 'force-dynamic';
|
|
186
|
-
export const GET = apiRequest;
|
|
187
|
-
export const POST = apiRequest;
|
|
188
|
-
export const PUT = apiRequest;
|
|
189
|
-
export const PATCH = apiRequest;
|
|
190
|
-
export const DELETE = apiRequest;
|
|
191
|
-
export const HEAD = apiRequest;
|
|
192
|
-
export const OPTIONS = apiRequest;
|
|
193
|
-
`);
|
|
194
|
-
put(root, `${app}/.env.example`, '# Development only. Production uses the ANHEDRAL_API service binding.\nAPI_INTERNAL_URL=http://127.0.0.1:8787\n');
|
|
195
|
-
}
|
|
196
|
-
function escapeJsx(value) {
|
|
197
|
-
return value
|
|
198
|
-
.replaceAll('&', '&')
|
|
199
|
-
.replaceAll('<', '<')
|
|
200
|
-
.replaceAll('>', '>')
|
|
201
|
-
.replaceAll('{', '{')
|
|
202
|
-
.replaceAll('}', '}');
|
|
203
|
-
}
|
|
204
|
-
export const WEB_API_PROXY = `export interface ApiBinding { fetch(request: Request): Promise<Response> }
|
|
205
|
-
type Options = { binding?: ApiBinding; development: boolean; devOrigin?: string; send?: typeof fetch };
|
|
206
|
-
function developmentOrigin(configured?: string): string {
|
|
207
|
-
const url = new URL(configured || 'http://127.0.0.1:8787');
|
|
208
|
-
const loopback = new Set(['127.0.0.1', 'localhost', '[::1]']);
|
|
209
|
-
const invalid = [url.protocol !== 'http:', !loopback.has(url.hostname), url.username, url.password, url.pathname !== '/', url.search, url.hash];
|
|
210
|
-
if (invalid.some(Boolean)) throw Error('API_INTERNAL_URL must be a loopback HTTP origin.');
|
|
211
|
-
return url.origin;
|
|
212
|
-
}
|
|
213
|
-
function backendOrigin(options: Options): string {
|
|
214
|
-
if (options.development) return developmentOrigin(options.devOrigin);
|
|
215
|
-
if ([!options.binding, options.devOrigin].some(Boolean)) throw Error('Production requires the API service binding.');
|
|
216
|
-
return 'https://api.internal';
|
|
217
|
-
}
|
|
218
|
-
function apiTarget(request: Request, origin: string): URL {
|
|
219
|
-
const url = new URL(request.url);
|
|
220
|
-
if (!/^\\/api(?:\\/|$)/.test(url.pathname)) throw Error('Unexpected API path.');
|
|
221
|
-
return new URL(url.pathname + url.search, origin);
|
|
222
|
-
}
|
|
223
|
-
function forwardedHeaders(request: Request): Headers {
|
|
224
|
-
const headers = new Headers();
|
|
225
|
-
for (const name of ['accept', 'content-type', 'cookie', 'origin', 'authorization', 'sec-fetch-site', 'expo-origin', 'idempotency-key']) {
|
|
226
|
-
const value = request.headers.get(name); if (value) headers.set(name, value);
|
|
227
|
-
}
|
|
228
|
-
return headers;
|
|
229
|
-
}
|
|
230
|
-
function upstreamRequest(request: Request, target: URL): Request {
|
|
231
|
-
const settings: RequestInit & { duplex?: 'half' } = { method: request.method, headers: forwardedHeaders(request), redirect: 'manual', signal: AbortSignal.any([request.signal, AbortSignal.timeout(15000)]) };
|
|
232
|
-
if (!['GET', 'HEAD'].includes(request.method)) { settings.body = request.body; settings.duplex = 'half'; }
|
|
233
|
-
return new Request(target, settings);
|
|
234
|
-
}
|
|
235
|
-
function privateResponse(response: Response, development: boolean): Response {
|
|
236
|
-
const headers = new Headers(response.headers);
|
|
237
|
-
for (const name of ['connection', 'transfer-encoding', 'access-control-allow-origin', 'access-control-allow-credentials']) headers.delete(name);
|
|
238
|
-
// Node fetch already decoded the local HTTP response. Next must frame/compress
|
|
239
|
-
// those decoded bytes itself; the sidecar's wire headers no longer describe them.
|
|
240
|
-
if (development) { headers.delete('content-encoding'); headers.delete('content-length'); }
|
|
241
|
-
headers.set('cache-control', 'private, no-store');
|
|
242
|
-
return new Response(response.body, { status: response.status, headers });
|
|
243
|
-
}
|
|
244
|
-
export async function proxyApi(request: Request, options: Options): Promise<Response> {
|
|
245
|
-
try {
|
|
246
|
-
const upstream = upstreamRequest(request, apiTarget(request, backendOrigin(options)));
|
|
247
|
-
const response = options.development ? await (options.send ?? fetch)(upstream) : await options.binding!.fetch(upstream);
|
|
248
|
-
return privateResponse(response, options.development);
|
|
249
|
-
} catch { return Response.json({ error: 'API unavailable' }, { status: 503, headers: { 'cache-control': 'private, no-store' } }); }
|
|
250
|
-
}
|
|
251
|
-
`;
|
package/dist/project-config.d.ts
DELETED
package/dist/project-config.js
DELETED
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
import { readFileSync, writeFileSync } from 'node:fs';
|
|
2
|
-
import path from 'node:path';
|
|
3
|
-
export const PROJECT_CONFIG_FILE = 'anhedral.json';
|
|
4
|
-
/** Called only inside a fresh staged workspace. Contains nonsecret generation provenance. */
|
|
5
|
-
export function writeProjectSection(root, section, value) {
|
|
6
|
-
const file = path.join(root, PROJECT_CONFIG_FILE);
|
|
7
|
-
let previous = {};
|
|
8
|
-
try {
|
|
9
|
-
previous = JSON.parse(readFileSync(file, 'utf8'));
|
|
10
|
-
}
|
|
11
|
-
catch (error) {
|
|
12
|
-
if (error.code !== 'ENOENT')
|
|
13
|
-
throw error;
|
|
14
|
-
}
|
|
15
|
-
writeFileSync(file, JSON.stringify({ ...previous, schemaVersion: 1, [section]: value }, null, 2) + '\n');
|
|
16
|
-
}
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import type { RecipeContext, StandardOptions } from './types.js';
|
|
2
|
-
export declare function createRecipeContext(root: string, options: StandardOptions): RecipeContext;
|
|
3
|
-
export declare function createResolutionContext(selection: Pick<StandardOptions, 'products' | 'hosting'> & Partial<Pick<StandardOptions, 'name'>>): RecipeContext;
|
package/dist/registry/context.js
DELETED
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
export function createRecipeContext(root, options) {
|
|
2
|
-
const selected = new Set(options.products);
|
|
3
|
-
return {
|
|
4
|
-
root,
|
|
5
|
-
options,
|
|
6
|
-
has: (product) => selected.has(product),
|
|
7
|
-
bindings: {},
|
|
8
|
-
};
|
|
9
|
-
}
|
|
10
|
-
export function createResolutionContext(selection) {
|
|
11
|
-
return createRecipeContext('', {
|
|
12
|
-
root: '',
|
|
13
|
-
name: selection.name ?? 'app',
|
|
14
|
-
skipInstall: true,
|
|
15
|
-
dryRun: true,
|
|
16
|
-
json: false,
|
|
17
|
-
initializeGit: false,
|
|
18
|
-
...selection,
|
|
19
|
-
});
|
|
20
|
-
}
|
package/dist/registry/options.js
DELETED
|
@@ -1,44 +0,0 @@
|
|
|
1
|
-
import { resolveStandardProducts } from './resolve.js';
|
|
2
|
-
import path from 'node:path';
|
|
3
|
-
import { packageNameFromText } from '../render.js';
|
|
4
|
-
function readGitFlag(token, previous) {
|
|
5
|
-
const value = token === '--git';
|
|
6
|
-
if (previous !== undefined && value !== previous)
|
|
7
|
-
throw new Error('Conflicting Git options.');
|
|
8
|
-
return value;
|
|
9
|
-
}
|
|
10
|
-
function parseStandardFlags(remaining) {
|
|
11
|
-
const products = new Set();
|
|
12
|
-
const hosting = 'cloudflare';
|
|
13
|
-
let gitSpecified;
|
|
14
|
-
for (const token of remaining) {
|
|
15
|
-
if (['--skip-install', '--dry-run', '--json', '--verbose'].includes(token))
|
|
16
|
-
continue;
|
|
17
|
-
if (token === '--git' || token === '--no-git') {
|
|
18
|
-
gitSpecified = readGitFlag(token, gitSpecified);
|
|
19
|
-
continue;
|
|
20
|
-
}
|
|
21
|
-
throw new Error(`Unknown init option: ${token}. Run anhedral init --help.`);
|
|
22
|
-
}
|
|
23
|
-
return { products, hosting, gitSpecified };
|
|
24
|
-
}
|
|
25
|
-
export function parseStandardOptions(args) {
|
|
26
|
-
const remaining = [...args];
|
|
27
|
-
const hasDirectory = remaining[0] && !remaining[0].startsWith('-');
|
|
28
|
-
const directory = hasDirectory ? remaining.shift() : process.cwd();
|
|
29
|
-
if (!directory || directory.startsWith('-'))
|
|
30
|
-
throw new Error('Specify a valid initialization directory.');
|
|
31
|
-
const root = path.resolve(directory);
|
|
32
|
-
const { products, hosting, gitSpecified } = parseStandardFlags(remaining);
|
|
33
|
-
resolveStandardProducts(products, hosting);
|
|
34
|
-
return {
|
|
35
|
-
root,
|
|
36
|
-
name: packageNameFromText(path.basename(root)),
|
|
37
|
-
products: [...products].sort(),
|
|
38
|
-
hosting,
|
|
39
|
-
skipInstall: remaining.includes('--skip-install'),
|
|
40
|
-
dryRun: remaining.includes('--dry-run'),
|
|
41
|
-
json: remaining.includes('--json'),
|
|
42
|
-
initializeGit: gitSpecified ?? Boolean(hasDirectory),
|
|
43
|
-
};
|
|
44
|
-
}
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import type { Hosting, StandardOptions, StandardProduct, StackRegistryItem } from './types.js';
|
|
2
|
-
export declare const CORE_PRODUCTS: readonly StandardProduct[];
|
|
3
|
-
/** Every initialization uses the same foundation. */
|
|
4
|
-
export declare function resolveStandardProducts(selected: Set<StandardProduct>, hosting: Hosting): void;
|
|
5
|
-
export interface ResolvedStackRegistry {
|
|
6
|
-
schemaVersion: number;
|
|
7
|
-
name: string;
|
|
8
|
-
cliVersion: string;
|
|
9
|
-
items: StackRegistryItem[];
|
|
10
|
-
}
|
|
11
|
-
export declare function resolveStackRegistry(options: Pick<StandardOptions, 'products' | 'hosting'> & Partial<Pick<StandardOptions, 'name'>>): ResolvedStackRegistry;
|
package/dist/registry/resolve.js
DELETED
|
@@ -1,46 +0,0 @@
|
|
|
1
|
-
import { dependencyOrder } from '../dependency-order.js';
|
|
2
|
-
import { STANDARD_PRODUCTS, STACK_REGISTRY, getStackDefinition, getStackItem, } from '../stack-registry.js';
|
|
3
|
-
import { createResolutionContext } from './context.js';
|
|
4
|
-
export const CORE_PRODUCTS = ['next', 'styling'];
|
|
5
|
-
/** Every initialization uses the same foundation. */
|
|
6
|
-
export function resolveStandardProducts(selected, hosting) {
|
|
7
|
-
if (hosting !== 'cloudflare')
|
|
8
|
-
throw new Error('Anhedral applications use Cloudflare Workers.');
|
|
9
|
-
for (const id of selected)
|
|
10
|
-
getStackDefinition(id);
|
|
11
|
-
for (const product of CORE_PRODUCTS)
|
|
12
|
-
selected.add(product);
|
|
13
|
-
resolveStackRegistry({ products: [...selected], hosting });
|
|
14
|
-
}
|
|
15
|
-
export function resolveStackRegistry(options) {
|
|
16
|
-
if (options.hosting !== 'cloudflare')
|
|
17
|
-
throw new Error('Anhedral applications use Cloudflare Workers.');
|
|
18
|
-
if (options.products.includes('expo'))
|
|
19
|
-
throw new Error('Legacy Expo source composition is retired. Use anhedral add expo, then anhedral add native-ui. Existing applications are not changed.');
|
|
20
|
-
for (const id of options.products)
|
|
21
|
-
if (!STANDARD_PRODUCTS.includes(id))
|
|
22
|
-
throw new Error(`Unknown stack product: ${id}.`);
|
|
23
|
-
const products = [...new Set([...CORE_PRODUCTS, ...options.products])];
|
|
24
|
-
const context = createResolutionContext({ ...options, products });
|
|
25
|
-
const resolved = new Map();
|
|
26
|
-
function collect(name) {
|
|
27
|
-
if (resolved.has(name))
|
|
28
|
-
return;
|
|
29
|
-
const definition = getStackDefinition(name);
|
|
30
|
-
const metadata = getStackItem(name);
|
|
31
|
-
if (definition.configure)
|
|
32
|
-
metadata.bindings = definition.configure(context);
|
|
33
|
-
resolved.set(name, metadata);
|
|
34
|
-
for (const dependency of metadata.registryDependencies)
|
|
35
|
-
collect(dependency);
|
|
36
|
-
}
|
|
37
|
-
for (const name of ['workspace', 'typescript', 'eslint', ...products.sort()])
|
|
38
|
-
collect(name);
|
|
39
|
-
const graph = new Map([...resolved].map(([name, item]) => [name, item.registryDependencies]));
|
|
40
|
-
return {
|
|
41
|
-
schemaVersion: STACK_REGISTRY.schemaVersion,
|
|
42
|
-
name: STACK_REGISTRY.name,
|
|
43
|
-
cliVersion: STACK_REGISTRY.cliVersion,
|
|
44
|
-
items: dependencyOrder(graph, 'Stack registry').map((name) => resolved.get(name)),
|
|
45
|
-
};
|
|
46
|
-
}
|
package/dist/registry/types.d.ts
DELETED
|
@@ -1,60 +0,0 @@
|
|
|
1
|
-
import type { StandardProduct } from '../stack-registry.js';
|
|
2
|
-
import type { Json } from '../scaffold/files.js';
|
|
3
|
-
export type { StandardProduct } from '../stack-registry.js';
|
|
4
|
-
export type Hosting = 'cloudflare';
|
|
5
|
-
export interface StandardOptions {
|
|
6
|
-
root: string;
|
|
7
|
-
name: string;
|
|
8
|
-
products: StandardProduct[];
|
|
9
|
-
hosting: Hosting;
|
|
10
|
-
skipInstall: boolean;
|
|
11
|
-
dryRun: boolean;
|
|
12
|
-
json: boolean;
|
|
13
|
-
initializeGit: boolean;
|
|
14
|
-
}
|
|
15
|
-
export type StandardRunner = (command: string, args: string[], cwd: string) => void;
|
|
16
|
-
export interface StackSelection {
|
|
17
|
-
conflicts?: readonly string[];
|
|
18
|
-
requiresAny?: readonly string[];
|
|
19
|
-
requiresAll?: readonly string[];
|
|
20
|
-
}
|
|
21
|
-
export interface SetupRequirements {
|
|
22
|
-
purpose: string;
|
|
23
|
-
tools: readonly string[];
|
|
24
|
-
access: readonly string[];
|
|
25
|
-
credentials: readonly string[];
|
|
26
|
-
resources: readonly string[];
|
|
27
|
-
verify: readonly string[];
|
|
28
|
-
}
|
|
29
|
-
export interface RecipeContext {
|
|
30
|
-
updating?: boolean;
|
|
31
|
-
root: string;
|
|
32
|
-
options: StandardOptions;
|
|
33
|
-
bindings: Json;
|
|
34
|
-
has: (product: string) => boolean;
|
|
35
|
-
}
|
|
36
|
-
export type Recipe = (context: RecipeContext) => void | Promise<void>;
|
|
37
|
-
export interface PackageRecipe {
|
|
38
|
-
name: string;
|
|
39
|
-
source: string;
|
|
40
|
-
dependencies: Record<string, string>;
|
|
41
|
-
}
|
|
42
|
-
export interface StackRegistryItem {
|
|
43
|
-
name: string;
|
|
44
|
-
version: string;
|
|
45
|
-
type: 'foundation' | 'application' | 'service' | 'package' | 'integration';
|
|
46
|
-
description: string;
|
|
47
|
-
registryDependencies: readonly string[];
|
|
48
|
-
targets: readonly string[];
|
|
49
|
-
selection: StackSelection;
|
|
50
|
-
installer: 'bootstrap' | 'recipe' | 'configuration';
|
|
51
|
-
runtime?: 'server' | 'worker' | 'optional-worker';
|
|
52
|
-
environment: readonly string[];
|
|
53
|
-
setup?: SetupRequirements;
|
|
54
|
-
package?: PackageRecipe;
|
|
55
|
-
bindings?: Json;
|
|
56
|
-
}
|
|
57
|
-
export interface ItemDefinition extends Omit<StackRegistryItem, 'bindings'> {
|
|
58
|
-
install?: Recipe;
|
|
59
|
-
configure?: (context: RecipeContext) => Json;
|
|
60
|
-
}
|
package/dist/scaffold/api.d.ts
DELETED
package/dist/scaffold/api.js
DELETED
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
import { scaffoldContracts } from './backend.js';
|
|
2
|
-
import { resourceName, jsString } from '../render.js';
|
|
3
|
-
import { STACK_DEPENDENCIES } from '../dependencies.js';
|
|
4
|
-
import { workerConfig, worker } from './files.js';
|
|
5
|
-
export function scaffoldApi({ root, options, bindings }) {
|
|
6
|
-
scaffoldContracts(root);
|
|
7
|
-
worker(root, 'api', { ...workerConfig(resourceName(options.name, 'api')), ...bindings }, `import { OpenAPIHono, createRoute } from '@hono/zod-openapi';
|
|
8
|
-
|
|
9
|
-
import { healthSchema } from '@workspace/contracts';
|
|
10
|
-
import { bodyLimit } from 'hono/body-limit';
|
|
11
|
-
|
|
12
|
-
const app = new OpenAPIHono<{ Bindings: Env }>();
|
|
13
|
-
app.use('/api/*', bodyLimit({ maxSize: 1024 * 1024 }));
|
|
14
|
-
const health = createRoute({
|
|
15
|
-
method: 'get',
|
|
16
|
-
path: '/health',
|
|
17
|
-
responses: {
|
|
18
|
-
200: {
|
|
19
|
-
description: 'Healthy',
|
|
20
|
-
content: { 'application/json': { schema: healthSchema } },
|
|
21
|
-
},
|
|
22
|
-
},
|
|
23
|
-
});
|
|
24
|
-
|
|
25
|
-
app.openapi(health, (c) => c.json({ ok: true as const }, 200));
|
|
26
|
-
app.get('/api/health', (c) => c.json(healthSchema.parse({ ok: true })));
|
|
27
|
-
app.doc('/openapi.json', {
|
|
28
|
-
openapi: '3.0.0',
|
|
29
|
-
info: { title: ${jsString(options.name)}, version: '1.0.0' },
|
|
30
|
-
});
|
|
31
|
-
|
|
32
|
-
export default app;
|
|
33
|
-
`, {
|
|
34
|
-
'@workspace/contracts': 'workspace:*',
|
|
35
|
-
hono: STACK_DEPENDENCIES['hono'],
|
|
36
|
-
'@hono/zod-openapi': STACK_DEPENDENCIES['@hono/zod-openapi'],
|
|
37
|
-
});
|
|
38
|
-
}
|
package/dist/scaffold/backend.js
DELETED
|
@@ -1,36 +0,0 @@
|
|
|
1
|
-
import { STACK_DEPENDENCIES } from '../dependencies.js';
|
|
2
|
-
import { put, sharedPackage } from './files.js';
|
|
3
|
-
/** Public contracts never import a framework, database or auth server. */
|
|
4
|
-
export function scaffoldContracts(root) {
|
|
5
|
-
sharedPackage(root, 'contracts', `import { z } from 'zod';
|
|
6
|
-
import { createHttpClient, type HttpOptions } from './http';
|
|
7
|
-
|
|
8
|
-
export const healthSchema = z.object({ ok: z.literal(true) });
|
|
9
|
-
|
|
10
|
-
export function createApiClient(baseURL = '/api', options: HttpOptions = {}) {
|
|
11
|
-
const request = createHttpClient(baseURL, options);
|
|
12
|
-
return {
|
|
13
|
-
health: (init?: RequestInit) => request('/health', healthSchema, init),
|
|
14
|
-
};
|
|
15
|
-
}
|
|
16
|
-
`, { zod: STACK_DEPENDENCIES.zod });
|
|
17
|
-
put(root, 'packages/contracts/src/http.ts', `import type { z } from 'zod';
|
|
18
|
-
|
|
19
|
-
export interface HttpOptions {
|
|
20
|
-
headers?: () => HeadersInit | Promise<HeadersInit>;
|
|
21
|
-
credentials?: 'omit' | 'same-origin' | 'include';
|
|
22
|
-
}
|
|
23
|
-
export function createHttpClient(baseURL: string, options: HttpOptions = {}) {
|
|
24
|
-
return async function request<T>(route: string, schema: z.ZodType<T>, init: RequestInit = {}): Promise<T> {
|
|
25
|
-
const headers = new Headers(await options.headers?.());
|
|
26
|
-
new Headers(init.headers).forEach((value, name) => headers.set(name, value));
|
|
27
|
-
headers.set('accept', 'application/json');
|
|
28
|
-
// Worker fetch types omit the browser credentials member.
|
|
29
|
-
const settings: RequestInit & { credentials: 'omit' | 'same-origin' | 'include' } = { ...init, credentials: options.credentials ?? 'same-origin', headers };
|
|
30
|
-
const response = await fetch(baseURL.replace(/\\/$/, '') + route, settings);
|
|
31
|
-
if (!response.ok) throw new Error('API request failed (' + response.status + ').');
|
|
32
|
-
return schema.parse(await response.json());
|
|
33
|
-
};
|
|
34
|
-
}
|
|
35
|
-
`);
|
|
36
|
-
}
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import type { ResolvedStackRegistry } from '../registry/resolve.js';
|
|
2
|
-
import type { StandardOptions } from '../registry/types.js';
|
|
3
|
-
/** Only used in a fresh staged workspace. Existing applications are never overlaid. */
|
|
4
|
-
export declare function composeStack(root: string, options: StandardOptions, registry: ResolvedStackRegistry): Promise<void>;
|
package/dist/scaffold/compose.js
DELETED
|
@@ -1,30 +0,0 @@
|
|
|
1
|
-
import { writeProjectSection } from '../project-config.js';
|
|
2
|
-
import { existsSync } from 'node:fs';
|
|
3
|
-
import path from 'node:path';
|
|
4
|
-
import { installStackItem } from '../stack-registry.js';
|
|
5
|
-
import { createRecipeContext } from '../registry/context.js';
|
|
6
|
-
import { inspectWorkspaceGraph } from '../workspace-graph.js';
|
|
7
|
-
import { writeStandardRoot } from './workspace.js';
|
|
8
|
-
/** Only used in a fresh staged workspace. Existing applications are never overlaid. */
|
|
9
|
-
export async function composeStack(root, options, registry) {
|
|
10
|
-
const context = createRecipeContext(root, options);
|
|
11
|
-
for (const item of registry.items)
|
|
12
|
-
Object.assign(context.bindings, item.bindings);
|
|
13
|
-
for (const item of registry.items) {
|
|
14
|
-
if (item.installer === 'recipe')
|
|
15
|
-
await installStackItem(item, context);
|
|
16
|
-
}
|
|
17
|
-
writeStandardRoot(root, options, registry);
|
|
18
|
-
for (const item of registry.items) {
|
|
19
|
-
for (const target of item.targets) {
|
|
20
|
-
if (!existsSync(path.join(root, target)))
|
|
21
|
-
throw new Error(`Registry target missing: ${item.name} -> ${target}.`);
|
|
22
|
-
}
|
|
23
|
-
}
|
|
24
|
-
writeProjectSection(root, 'registry', {
|
|
25
|
-
...registry,
|
|
26
|
-
status: 'scaffolded',
|
|
27
|
-
workspaces: inspectWorkspaceGraph(root),
|
|
28
|
-
resourcesProvisioned: false,
|
|
29
|
-
});
|
|
30
|
-
}
|
|
@@ -1,41 +0,0 @@
|
|
|
1
|
-
import { readFileSync } from 'node:fs';
|
|
2
|
-
import path from 'node:path';
|
|
3
|
-
import { STACK_DEPENDENCIES } from '../dependencies.js';
|
|
4
|
-
import { put, patchPackage, sharedPackage } from './files.js';
|
|
5
|
-
export function scaffoldDatabase({ root }) {
|
|
6
|
-
sharedPackage(root, 'db', `import { drizzle } from 'drizzle-orm/d1';
|
|
7
|
-
import * as schema from './schema';
|
|
8
|
-
export function createDatabase(binding: Parameters<typeof drizzle>[0]) { return drizzle(binding, { schema }); }
|
|
9
|
-
`, { 'drizzle-orm': STACK_DEPENDENCIES['drizzle-orm'] });
|
|
10
|
-
put(root, 'packages/db/src/schema.ts', '// Add application tables here. Generate and review SQL before migration.\nexport {};\n');
|
|
11
|
-
put(root, 'packages/db/drizzle/.gitkeep', '');
|
|
12
|
-
put(root, 'packages/db/drizzle.config.ts', `import { fileURLToPath } from 'node:url';
|
|
13
|
-
import { relative } from 'node:path';
|
|
14
|
-
import { defineConfig } from 'drizzle-kit';
|
|
15
|
-
export default defineConfig({ dialect: 'sqlite', schema: fileURLToPath(new URL('./src/schema.ts', import.meta.url)), out: relative(process.cwd(), fileURLToPath(new URL('./drizzle/', import.meta.url))) });
|
|
16
|
-
`);
|
|
17
|
-
put(root, 'packages/db/src/migrate.ts', `import { spawnSync } from 'node:child_process';
|
|
18
|
-
import { fileURLToPath } from 'node:url';
|
|
19
|
-
const args = process.argv.slice(2);
|
|
20
|
-
if (args.length > 1 || args.some((arg) => !['--local', '--remote'].includes(arg))) throw new Error('Usage: pnpm db:migrate [--local|--remote] (defaults to local).');
|
|
21
|
-
const pnpm = process.env.npm_execpath;
|
|
22
|
-
if (!pnpm) throw new Error('Run migrations through pnpm db:migrate.');
|
|
23
|
-
const root = fileURLToPath(new URL('../../../apps/api/', import.meta.url));
|
|
24
|
-
const result = spawnSync(process.execPath, [pnpm, 'exec', 'wrangler', 'd1', 'migrations', 'apply', 'DB', args[0] ?? '--local', '--config', fileURLToPath(new URL('../../../apps/api/wrangler.jsonc', import.meta.url))], { cwd: root, stdio: 'inherit', shell: false });
|
|
25
|
-
if (result.error) throw result.error;
|
|
26
|
-
process.exitCode = result.status ?? 1;
|
|
27
|
-
`);
|
|
28
|
-
patchPackage(root, 'packages/db/package.json', {
|
|
29
|
-
exports: { '.': './src/index.ts', './schema': './src/schema.ts' },
|
|
30
|
-
devDependencies: {
|
|
31
|
-
'drizzle-kit': STACK_DEPENDENCIES['drizzle-kit'],
|
|
32
|
-
tsx: STACK_DEPENDENCIES.tsx,
|
|
33
|
-
wrangler: STACK_DEPENDENCIES.wrangler,
|
|
34
|
-
},
|
|
35
|
-
scripts: { 'db:generate': 'drizzle-kit generate', 'db:migrate': 'tsx src/migrate.ts' },
|
|
36
|
-
});
|
|
37
|
-
patchPackage(root, 'apps/api/package.json', { dependencies: { '@workspace/db': 'workspace:*' } });
|
|
38
|
-
const source = readFileSync(path.join(root, 'apps/api/src/index.ts'), 'utf8');
|
|
39
|
-
put(root, 'apps/api/src/index.ts', "import { createDatabase } from '@workspace/db';\n" +
|
|
40
|
-
source.replace('const app = new OpenAPIHono<{ Bindings: Env }>();', "const app = new OpenAPIHono<{ Bindings: Env; Variables: { database: () => ReturnType<typeof createDatabase> } }>();\napp.use('*', async (c, next) => { c.set('database', () => createDatabase(c.env.DB)); await next(); });"));
|
|
41
|
-
}
|