The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 06:00 UTC
| 1 | import { createHash } from "node:crypto"; |
| 2 | import { AlchemyContext } from "alchemy/AlchemyContext"; |
| 3 | import type { MemoOptions } from "alchemy/Command/Memo"; |
| 4 | import type { Input, InputProps } from "alchemy/Input"; |
| 5 | import * as Output from "alchemy/Output"; |
| 6 | import { ProviderModePolicy } from "alchemy/ProviderMode"; |
| 7 | import { Server, type ServerDevProps } from "alchemy/Website/Server"; |
| 8 | import * as Data from "effect/Data"; |
| 9 | import * as Duration from "effect/Duration"; |
| 10 | import * as Effect from "effect/Effect"; |
| 11 | import { Function as LambdaFunction, type FunctionProps } from "../Lambda/Function.ts"; |
| 12 | import { WebFunction } from "../Lambda/WebFunction.ts"; |
| 13 | import { WebFunctionEndpoint } from "../Lambda/WebFunctionEndpoint.ts"; |
| 14 | import { asRouterDomain, registerDevRouterRoute } from "./DevRouterRoute.ts"; |
| 15 | import { |
| 16 | normalizeWebsiteDomain, |
| 17 | type WebsiteAssetsConfig, |
| 18 | type WebsiteDomainProps, |
| 19 | type WebsiteEdgeProps, |
| 20 | type WebsiteInvalidationProps, |
| 21 | } from "./shared.ts"; |
| 22 | import { makeKvSite, type StaticSiteProps } from "./StaticSite.ts"; |
| 23 | |
| 24 | /** Props shared by every framework website, whatever runs its server. */ |
| 25 | export interface FrameworkSiteBaseProps { |
| 26 | /** |
| 27 | * Project root directory (the directory containing `package.json`). |
| 28 | * @default "." |
| 29 | */ |
| 30 | rootDir?: string; |
| 31 | /** |
| 32 | * Controls which files are hashed to decide whether the build re-runs. |
| 33 | * @default true |
| 34 | */ |
| 35 | memo?: MemoOptions | boolean; |
| 36 | /** |
| 37 | * Environment variables for the SSR server (Lambda environment). |
| 38 | * Values accept `Output`s (e.g. `API_URL: api.url`). |
| 39 | */ |
| 40 | env?: Record<string, any>; |
| 41 | /** |
| 42 | * Maximum server request duration. |
| 43 | * @default 30 seconds |
| 44 | */ |
| 45 | timeout?: Duration.Duration; |
| 46 | /** |
| 47 | * Static asset upload configuration. |
| 48 | */ |
| 49 | assets?: WebsiteAssetsConfig; |
| 50 | /** |
| 51 | * Options for the local dev server that runs this site under |
| 52 | * `alchemy dev`. |
| 53 | */ |
| 54 | dev?: ServerDevProps; |
| 55 | /** |
| 56 | * Optional custom domain. A string is shorthand for `{ name }`; `null` |
| 57 | * explicitly clears a previously set domain. Set `domain.router` to |
| 58 | * serve the site through an existing `AWS.Website.Router` instead of a |
| 59 | * standalone CloudFront distribution. |
| 60 | */ |
| 61 | domain?: string | WebsiteDomainProps | null; |
| 62 | /** |
| 63 | * Serve the site at its CloudFront default domain |
| 64 | * (`https://dxxxx.cloudfront.net`). `false` 301s default-domain requests |
| 65 | * to `https://<domain.name>` at the edge and excludes the default domain |
| 66 | * from the `urls` output. Requires `domain`; not applicable when |
| 67 | * `domain.router` is set. |
| 68 | * @default true |
| 69 | */ |
| 70 | cloudfrontUrl?: boolean; |
| 71 | /** |
| 72 | * Additional CloudFront Function customizations. |
| 73 | */ |
| 74 | edge?: WebsiteEdgeProps; |
| 75 | /** |
| 76 | * Optional deterministic S3 bucket name for the asset bucket. |
| 77 | */ |
| 78 | bucketName?: string; |
| 79 | /** |
| 80 | * Whether to delete uploaded objects when the bucket is destroyed. |
| 81 | * @default false |
| 82 | */ |
| 83 | forceDestroy?: boolean; |
| 84 | /** |
| 85 | * CloudFront invalidation behavior. |
| 86 | * @default { paths: "all", wait: false } |
| 87 | */ |
| 88 | invalidation?: false | WebsiteInvalidationProps; |
| 89 | /** |
| 90 | * User-defined tags applied to created resources. |
| 91 | */ |
| 92 | tags?: Record<string, string>; |
| 93 | } |
| 94 | |
| 95 | /** The SSR server on a Lambda Web Function (the default). */ |
| 96 | export interface WebFunctionServerProps { |
| 97 | /** |
| 98 | * What runs the SSR server: a Lambda Web Function, where the |
| 99 | * framework's Node server handles many requests per environment and |
| 100 | * streams responses. Set `"function"` for a Lambda Function instead. |
| 101 | * @default "web-function" |
| 102 | */ |
| 103 | server?: "web-function"; |
| 104 | /** |
| 105 | * Requests one Web Function environment serves at once (1–128). |
| 106 | * @default 64 |
| 107 | */ |
| 108 | maxConcurrencyPerEnvironment?: number; |
| 109 | /** |
| 110 | * Maximum Web Function environments per Region (2–10,000). |
| 111 | */ |
| 112 | maxEnvironments?: number; |
| 113 | /** |
| 114 | * Additional AWS Regions to serve the SSR server from. The server's Web |
| 115 | * Function gets one global domain that routes each request to the |
| 116 | * nearest Region, and CloudFront forwards to it. Changing it gives the |
| 117 | * server a new domain; the site's URL stays the same. |
| 118 | */ |
| 119 | regions?: string[]; |
| 120 | } |
| 121 | |
| 122 | /** |
| 123 | * The SSR server on a Lambda Function behind a streaming Function URL: for |
| 124 | * servers that need more than 2 GB of memory or x86_64, or Regions without |
| 125 | * Web Functions. |
| 126 | */ |
| 127 | export interface FunctionServerProps { |
| 128 | /** Run the SSR server on a Lambda Function behind a streaming Function URL. */ |
| 129 | server: "function"; |
| 130 | /** |
| 131 | * Memory allocated to the server function, in MB. |
| 132 | * @default 1024 |
| 133 | */ |
| 134 | memorySize?: number; |
| 135 | /** |
| 136 | * Server instruction set architecture. |
| 137 | * @default "x86_64" |
| 138 | */ |
| 139 | architecture?: "x86_64" | "arm64"; |
| 140 | /** |
| 141 | * Lambda runtime for the server function. |
| 142 | * @default "nodejs24.x" |
| 143 | */ |
| 144 | runtime?: FunctionProps["runtime"]; |
| 145 | } |
| 146 | |
| 147 | /** |
| 148 | * Props of every framework website composite (SvelteKit, Nuxt, Waku, |
| 149 | * Octane, Astro, ...): the shared props, the framework's own (`Framework`, |
| 150 | * kept FLAT — the composite is the framework, so its keys need no |
| 151 | * namespace), and the props of the chosen `server`. |
| 152 | */ |
| 153 | export type FrameworkSiteProps<Framework = {}> = FrameworkSiteBaseProps & |
| 154 | Framework & |
| 155 | (WebFunctionServerProps | FunctionServerProps); |
| 156 | |
| 157 | /** `regions` serves a Web Function from several Regions; a Lambda Function can't. */ |
| 158 | export class WebsiteRegionsRequireWebFunction extends Data.TaggedError( |
| 159 | "WebsiteRegionsRequireWebFunction", |
| 160 | )<{ site: string; message: string }> {} |
| 161 | |
| 162 | /** Fail at plan when `regions` is combined with `server: "function"`. */ |
| 163 | export const checkWebsiteRegions = ( |
| 164 | site: string, |
| 165 | props: { server?: "web-function" | "function"; regions?: string[] }, |
| 166 | ) => |
| 167 | props.server === "function" && props.regions !== undefined && props.regions.length > 0 |
| 168 | ? Effect.die( |
| 169 | new WebsiteRegionsRequireWebFunction({ |
| 170 | site, |
| 171 | message: `"${site}": regions needs the Web Function server. Remove server: "function", or remove regions.`, |
| 172 | }), |
| 173 | ) |
| 174 | : Effect.void; |
| 175 | |
| 176 | /** |
| 177 | * The endpoint CloudFront reaches a Web Function server through. Without |
| 178 | * `regions` that is the function's own endpoint. With them it is a |
| 179 | * `WebFunctionEndpoint` whose name follows the Region set: an endpoint's |
| 180 | * Regions can't change in place, so a new set is a new endpoint, created |
| 181 | * before CloudFront moves to it and deleted only after. |
| 182 | */ |
| 183 | export const siteEndpoint = Effect.fn(function* ( |
| 184 | id: string, |
| 185 | server: WebFunction, |
| 186 | props: { regions?: string[]; maxEnvironments?: number }, |
| 187 | ) { |
| 188 | if (props.regions === undefined || props.regions.length === 0) { |
| 189 | return { domainName: server.domainName, url: server.url }; |
| 190 | } |
| 191 | const key = yield* Effect.sync(() => |
| 192 | createHash("sha256") |
| 193 | .update([...new Set(props.regions)].sort().join(",")) |
| 194 | .digest("hex") |
| 195 | .slice(0, 8), |
| 196 | ); |
| 197 | const endpoint = yield* WebFunctionEndpoint(id, { |
| 198 | function: server, |
| 199 | endpointName: `edge-${key}`, |
| 200 | authType: "ApplicationManaged", |
| 201 | regions: props.regions, |
| 202 | maxEnvironments: props.maxEnvironments, |
| 203 | }); |
| 204 | return { domainName: endpoint.domainName, url: endpoint.url }; |
| 205 | }); |
| 206 | |
| 207 | /** Per-framework wiring for {@link makeFrameworkSite}. */ |
| 208 | export interface FrameworkSiteConfig { |
| 209 | /** Display name used in error messages (e.g. `"SvelteKit"`). */ |
| 210 | name: string; |
| 211 | /** Framework-integration module specifier. */ |
| 212 | framework: string; |
| 213 | /** AWS Lambda deploy-target module specifier (`server: "function"`). */ |
| 214 | target: string; |
| 215 | /** |
| 216 | * Node deploy-target module specifier (`server: "web-function"`). Its |
| 217 | * serve entry listens on `AWS_LAMBDA_HTTP_ENDPOINT`. Without one the |
| 218 | * site always uses a Lambda Function. |
| 219 | */ |
| 220 | webTarget?: string; |
| 221 | /** |
| 222 | * Packages installed into the Web Function instead of bundled (the |
| 223 | * framework's runtime when its server can't be bundled). |
| 224 | */ |
| 225 | install?: ReadonlyArray<string>; |
| 226 | /** |
| 227 | * Build options for `server: "web-function"`, merged over `options`. |
| 228 | */ |
| 229 | webOptions?: Record<string, unknown>; |
| 230 | /** |
| 231 | * Deploy the Node target's server directory as-is instead of bundling |
| 232 | * its serve entry, for servers that read files beside themselves at |
| 233 | * runtime (Octane's SSR `index.html`). |
| 234 | */ |
| 235 | webPrebuilt?: boolean; |
| 236 | /** |
| 237 | * Framework-specific build options forwarded to the integration (e.g. |
| 238 | * `{ kit }`, `{ nuxt }`, `{ astro }`). Must be JSON-serializable. |
| 239 | */ |
| 240 | options?: Record<string, unknown> | undefined; |
| 241 | /** |
| 242 | * Assets-only mode: every page was prerendered at build time, so no |
| 243 | * server function is created and misses resolve to the error page (or |
| 244 | * the index page for SPAs). Set by composites whose framework supports |
| 245 | * a fully static output (Astro's `output: "static"`). |
| 246 | */ |
| 247 | static?: { spa?: boolean; errorPage?: string } | undefined; |
| 248 | } |
| 249 | |
| 250 | /** |
| 251 | * The shared implementation behind the framework website composites: |
| 252 | * build the framework through its AWS deploy target, then deploy the |
| 253 | * server output on a streaming Lambda Function URL with static assets in |
| 254 | * S3 behind a CloudFront distribution (or attach to a shared Router). |
| 255 | * |
| 256 | * During `alchemy dev` the site is the framework's own dev server (native |
| 257 | * HMR) and no cloud resources are declared; `Alchemy.remote()` opts back |
| 258 | * into the full live deployment. |
| 259 | * |
| 260 | * Callers pipe `Namespace.push(id)` themselves (the composites do), so |
| 261 | * resource FQNs are identical to the previous per-framework |
| 262 | * implementations. |
| 263 | */ |
| 264 | export const makeFrameworkSite = Effect.fn("AWS.Website.FrameworkSite")(function* ( |
| 265 | id: string, |
| 266 | propsIn: InputProps<FrameworkSiteProps, "server">, |
| 267 | config: FrameworkSiteConfig, |
| 268 | ) { |
| 269 | // Props accept `Input<T>` throughout (matching the Cloudflare |
| 270 | // composites); values flow into the resources below, which resolve |
| 271 | // them at reconcile time. The plan-time reads in this function |
| 272 | // (domain-shape branching, dev wiring, the build's rootDir/memo) |
| 273 | // need concrete values — passing an `Output` for those specific |
| 274 | // fields is unsupported, same as on the Cloudflare side. |
| 275 | const props = propsIn as FrameworkSiteProps; |
| 276 | yield* checkWebsiteRegions(`AWS.Website.${config.name} "${id}"`, props); |
| 277 | const ctx = yield* AlchemyContext; |
| 278 | const remoted = yield* ProviderModePolicy; |
| 279 | const isLocal = ctx.dev && remoted !== true; |
| 280 | |
| 281 | const routerDomain = asRouterDomain(normalizeWebsiteDomain(props.domain)); |
| 282 | |
| 283 | // A Router-attached dev server is an ORIGIN for the emulated CloudFront |
| 284 | // edge, which runs in a container and reaches the host through its |
| 285 | // gateway address — it cannot open a connection to the host's loopback. |
| 286 | // Frameworks bind loopback by default (Vite picks `[::1]`), so the edge |
| 287 | // would get a refused connection and answer 502. Bind all interfaces |
| 288 | // unless the caller asked for a specific host. Standalone dev sites, and |
| 289 | // `mode: "external"` (we start nothing), keep the framework's default. |
| 290 | const dev: ServerDevProps | undefined = |
| 291 | isLocal && routerDomain && props.dev?.mode !== "external" |
| 292 | ? { ...props.dev, host: props.dev?.host ?? "0.0.0.0" } |
| 293 | : props.dev; |
| 294 | |
| 295 | const onWebFunction = |
| 296 | config.webTarget !== undefined && (props.server ?? "web-function") === "web-function"; |
| 297 | const build = yield* Server("Build", { |
| 298 | framework: config.framework, |
| 299 | target: onWebFunction ? config.webTarget! : config.target, |
| 300 | root: props.rootDir, |
| 301 | env: props.env, |
| 302 | options: onWebFunction ? { ...config.options, ...config.webOptions } : config.options, |
| 303 | memo: props.memo, |
| 304 | dev, |
| 305 | }); |
| 306 | |
| 307 | if (isLocal) { |
| 308 | // Router-attached sites register with the Router in dev exactly as they |
| 309 | // do live — same resource types and ids — with the framework's dev |
| 310 | // server standing in for the S3 + Lambda origins. |
| 311 | const kvNamespace = routerDomain |
| 312 | ? yield* registerDevRouterRoute(routerDomain, build.url) |
| 313 | : undefined; |
| 314 | return { |
| 315 | bucket: undefined, |
| 316 | build, |
| 317 | files: undefined, |
| 318 | distribution: undefined, |
| 319 | invalidation: undefined, |
| 320 | kvNamespace, |
| 321 | server: undefined, |
| 322 | serverUrl: undefined, |
| 323 | url: build.url, |
| 324 | urls: [build.url], |
| 325 | }; |
| 326 | } |
| 327 | |
| 328 | const siteProps: StaticSiteProps = { |
| 329 | path: build.clientDir as unknown as string, |
| 330 | assets: props.assets, |
| 331 | domain: props.domain, |
| 332 | cloudfrontUrl: props.cloudfrontUrl, |
| 333 | edge: props.edge, |
| 334 | bucketName: props.bucketName, |
| 335 | forceDestroy: props.forceDestroy, |
| 336 | invalidation: props.invalidation, |
| 337 | tags: props.tags, |
| 338 | }; |
| 339 | |
| 340 | if (config.static) { |
| 341 | const site = yield* makeKvSite(id, { |
| 342 | ...siteProps, |
| 343 | errorPage: config.static.errorPage, |
| 344 | spa: config.static.spa, |
| 345 | }); |
| 346 | return { |
| 347 | ...site, |
| 348 | build, |
| 349 | server: undefined, |
| 350 | serverUrl: undefined, |
| 351 | }; |
| 352 | } |
| 353 | |
| 354 | if (onWebFunction) { |
| 355 | // The Node deploy target writes a complete server program |
| 356 | // (`serve-node.mjs`) that listens where Lambda says; bundle it like any |
| 357 | // async Web Function. Assets stay in S3 behind the edge router. |
| 358 | const server = yield* WebFunction("WebServer", { |
| 359 | main: build.serverEntry as unknown as string, |
| 360 | ...(config.webPrebuilt ? { bundle: false as const } : {}), |
| 361 | authType: "ApplicationManaged", |
| 362 | env: props.env, |
| 363 | timeout: props.timeout ?? Duration.seconds(30), |
| 364 | ...(props.server === "function" |
| 365 | ? {} |
| 366 | : { |
| 367 | maxConcurrencyPerEnvironment: props.maxConcurrencyPerEnvironment, |
| 368 | maxEnvironments: props.maxEnvironments, |
| 369 | }), |
| 370 | build: |
| 371 | config.install !== undefined && config.install.length > 0 |
| 372 | ? { install: [...config.install] } |
| 373 | : undefined, |
| 374 | }); |
| 375 | const endpoint = yield* siteEndpoint( |
| 376 | "ServerEndpoint", |
| 377 | server, |
| 378 | props.server === "function" ? {} : props, |
| 379 | ); |
| 380 | const site = yield* makeKvSite(id, siteProps, { serverHost: endpoint.domainName }); |
| 381 | return { |
| 382 | ...site, |
| 383 | build, |
| 384 | server, |
| 385 | serverUrl: endpoint.url, |
| 386 | }; |
| 387 | } |
| 388 | |
| 389 | const server = yield* LambdaFunction("Server", { |
| 390 | main: build.serverEntry as unknown as string, |
| 391 | handler: "handler", |
| 392 | isExternal: true, |
| 393 | // The AWS deploy target's finishing pass writes the server directory |
| 394 | // as a complete Node deployment unit (entry + chunks) — ship it |
| 395 | // as-is. |
| 396 | bundle: false, |
| 397 | runtime: (props.server === "function" ? props.runtime : undefined) ?? "nodejs24.x", |
| 398 | architecture: props.server === "function" ? props.architecture : undefined, |
| 399 | memorySize: (props.server === "function" ? props.memorySize : undefined) ?? 1024, |
| 400 | timeout: props.timeout ?? Duration.seconds(30), |
| 401 | env: props.env, |
| 402 | functionUrl: { |
| 403 | authType: "NONE", |
| 404 | invokeMode: "RESPONSE_STREAM", |
| 405 | }, |
| 406 | }); |
| 407 | |
| 408 | const serverHost = Output.map((url: string | undefined) => { |
| 409 | if (!url) { |
| 410 | throw new Error(`The ${config.name} server function did not produce a Function URL.`); |
| 411 | } |
| 412 | return new URL(url).hostname; |
| 413 | })(server.functionUrl as any) as Input<string>; |
| 414 | |
| 415 | const site = yield* makeKvSite(id, siteProps, { serverHost }); |
| 416 | |
| 417 | return { |
| 418 | ...site, |
| 419 | build, |
| 420 | server, |
| 421 | serverUrl: server.functionUrl, |
| 422 | }; |
| 423 | }); |