@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

main
ts 976 lines 33.4 KB
Raw
1 import { createHash } from "node:crypto";
2 import { AlchemyContext } from "alchemy/AlchemyContext";
3 import * as Command from "alchemy/Command";
4 import { toPath } from "alchemy/FQN";
5 import type { Input } from "alchemy/Input";
6 import * as Namespace from "alchemy/Namespace";
7 import * as Output from "alchemy/Output";
8 import { ProviderModePolicy } from "alchemy/ProviderMode";
9 import { isResource } from "alchemy/Resource";
10 import { Stack } from "alchemy/Stack";
11 import { Stage } from "alchemy/Stage";
12 import * as Effect from "effect/Effect";
13 import type * as Redacted from "effect/Redacted";
14 import { CachePolicy } from "../CloudFront/CachePolicy.ts";
15 import { Distribution } from "../CloudFront/Distribution.ts";
16 import { Function as CloudFrontFunction } from "../CloudFront/Function.ts";
17 import { Invalidation } from "../CloudFront/Invalidation.ts";
18 import { KeyValueStore } from "../CloudFront/KeyValueStore.ts";
19 import { KvEntries } from "../CloudFront/KvEntries.ts";
20 import { KvRoutesUpdate } from "../CloudFront/KvRoutesUpdate.ts";
21 import {
22 MANAGED_ALL_VIEWER_EXCEPT_HOST_HEADER_POLICY_ID,
23 MANAGED_CACHING_OPTIMIZED_POLICY_ID,
24 } from "../CloudFront/ManagedPolicies.ts";
25 import { OriginAccessControl } from "../CloudFront/OriginAccessControl.ts";
26 import { domainCertificate, resolveDomainDns } from "../CustomDomain.ts";
27 import type { PolicyStatement } from "../IAM/Policy.ts";
28 import { Bucket } from "../S3/Bucket.ts";
29 import { AssetDeployment } from "./AssetDeployment.ts";
30 import { buildHostRedirectInjection, CF_ROUTER_INJECTION } from "./cfcode.ts";
31 import { asRouterDomain, registerDevRouterRoute } from "./DevRouterRoute.ts";
32 import {
33 normalizeWebsiteDomain,
34 type StaticSiteBuildProps,
35 type WebsiteAssetsConfig,
36 type WebsiteDomainProps,
37 type WebsiteEdgeProps,
38 type WebsiteInvalidationProps,
39 type WebsiteRouterDomainProps,
40 type WebsiteStandaloneDomainProps,
41 } from "./shared.ts";
42
43 export interface StaticSiteProps {
44 /**
45 * Path to the local site directory.
46 * @default "."
47 */
48 path?: Input<string>;
49 /**
50 * Optional build configuration executed before upload.
51 */
52 build?: StaticSiteBuildProps;
53 /**
54 * Static site asset upload configuration.
55 */
56 assets?: WebsiteAssetsConfig;
57 /**
58 * Optional custom domain. A string is shorthand for `{ name }`; `null`
59 * explicitly clears a previously set domain. Set `domain.router` to
60 * serve the site through an existing `AWS.Website.Router` instead of a
61 * standalone CloudFront distribution.
62 */
63 domain?: string | WebsiteDomainProps | null;
64 /**
65 * Serve the site at its CloudFront default domain
66 * (`https://dxxxx.cloudfront.net`). The default domain cannot be removed
67 * from a distribution, so `false` is emulated at the edge: the generated
68 * viewer-request CloudFront Function 301s requests that arrive on the
69 * default domain to `https://<domain.name>` (path and query preserved),
70 * and the default domain is excluded from the `urls` output.
71 *
72 * Requires `domain` when `false` (the site would be unreachable). Not
73 * applicable to Router-attached sites (`domain.router`) — they own no
74 * distribution.
75 * @default true
76 */
77 cloudfrontUrl?: boolean;
78 /**
79 * Additional CloudFront Function customizations.
80 */
81 edge?: WebsiteEdgeProps;
82 /**
83 * Index page served for the site root.
84 * @default "index.html"
85 */
86 indexPage?: string;
87 /**
88 * Serve this site as a single-page application: any request that does not
89 * match an uploaded file is answered with the `indexPage` and a `200`
90 * status so client-side routing can take over.
91 *
92 * This is also the fallback behavior when neither `spa` nor `errorPage`
93 * is set. Setting `spa: true` makes the intent explicit and guards
94 * against accidentally combining it with `errorPage`.
95 *
96 * Mutually exclusive with `errorPage` (a static site returns a real
97 * `404`; a SPA serves the app shell).
98 * @default false
99 */
100 spa?: boolean;
101 /**
102 * Error page returned for 403/404 requests.
103 * When set, CloudFront customErrorResponses are created and misses return
104 * a real `404` status. Mutually exclusive with `spa`.
105 */
106 errorPage?: string;
107 /**
108 * Optional deterministic S3 bucket name for newly created buckets.
109 */
110 bucketName?: string;
111 /**
112 * Whether to delete uploaded objects before destroying created buckets.
113 * @default false
114 */
115 forceDestroy?: boolean;
116 /**
117 * CloudFront invalidation behavior.
118 * @default { paths: "all", wait: false }
119 */
120 invalidation?: false | WebsiteInvalidationProps;
121 /**
122 * User-defined tags applied to created resources.
123 */
124 tags?: Record<string, string>;
125 /**
126 * Local dev configuration. When `alchemy dev` runs, the build/upload is
127 * skipped and `command` is spawned as a long-lived child process tied to
128 * the stack's scope. Alchemy does not proxy or interpret the process —
129 * the dev server's own URL (e.g. `http://localhost:5173`) is what you
130 * open in the browser.
131 *
132 * @example
133 * ```typescript
134 * AWS.Website.StaticSite("App", {
135 * path: "./app",
136 * build: { command: "npm run build", output: "dist" },
137 * dev: { command: "npm run dev" },
138 * });
139 * ```
140 */
141 dev?: {
142 /**
143 * Shell command to run as the local dev server (e.g. `npm run dev`).
144 */
145 command: string;
146 /**
147 * Working directory for {@link command}. Defaults to
148 * {@link StaticSiteProps.path} (the site directory), or
149 * `process.cwd()` if neither is set.
150 */
151 cwd?: string;
152 /**
153 * Environment variables for {@link command}, merged on top of
154 * `process.env`. `Redacted` values stay out of logs and state, so put
155 * secrets here rather than interpolating them into {@link command}.
156 */
157 env?: Record<string, string | Redacted.Redacted<string>>;
158 /**
159 * Override for the `url` output if alchemy fails to detect it from the
160 * stdout of the dev command.
161 */
162 url?: string;
163 };
164 }
165
166 /**
167 * Deploy a static website to S3 and CloudFront using KV-based edge routing.
168 *
169 * `StaticSite` uploads site files to a private S3 bucket, creates a CloudFront
170 * KeyValueStore with a file manifest for edge routing, and optionally builds
171 * the site first. Supports standalone distribution or composition with
172 * `AWS.Website.Router`.
173 * ### Basic Sites
174 * **Example:** Simple Static Site
175 * ```typescript
176 * const site = yield* StaticSite("Docs", {
177 * path: "./site",
178 * });
179 * ```
180 *
181 * ### Built Sites
182 * **Example:** Build A Vite App
183 * ```typescript
184 * const site = yield* StaticSite("Web", {
185 * path: "./frontend",
186 * build: {
187 * command: "bun run build",
188 * output: "dist",
189 * env: {
190 * VITE_API_URL: api.url,
191 * },
192 * },
193 * });
194 * ```
195 *
196 * ### Single-Page Applications
197 * **Example:** SPA With Client-Side Routing
198 * ```typescript
199 * // Misses fall back to index.html with a 200 so the client router
200 * // can handle the path.
201 * const site = yield* StaticSite("App", {
202 * path: "./app",
203 * build: {
204 * command: "bun run build",
205 * output: "dist",
206 * },
207 * spa: true,
208 * });
209 * ```
210 *
211 * ### Custom Domains
212 * **Example:** Site With A Route 53 Domain
213 * ```typescript
214 * const site = yield* StaticSite("Web", {
215 * path: "./site",
216 * domain: {
217 * name: "www.example.com",
218 * hostedZoneId: zone.hostedZoneId,
219 * },
220 * errorPage: "404.html",
221 * });
222 * ```
223 *
224 * **Example:** Site With A Cloudflare Domain
225 * ```typescript
226 * // DNS lives in Cloudflare (e.g. a Cloudflare Registrar domain): the
227 * // certificate is validated and the hostname CNAMEd to CloudFront through
228 * // the Cloudflare zone. Requires `Cloudflare.providers()` in the stack.
229 * const site = yield* StaticSite("Web", {
230 * path: "./site",
231 * domain: {
232 * name: "www.example.com",
233 * dns: Cloudflare.DNS.Adapter(),
234 * },
235 * });
236 * ```
237 *
238 * ### Router Composition
239 * **Example:** Serve Through A Router
240 * ```typescript
241 * const site = yield* StaticSite("Docs", {
242 * path: "./docs",
243 * domain: {
244 * router,
245 * path: "/docs",
246 * },
247 * });
248 * ```
249 *
250 * **Example:** Host-Matched Router Attachment
251 * ```typescript
252 * // The site serves for docs.example.com on the router. On a same-stack
253 * // router that owns a domain, this declaration alone provisions the
254 * // hostname end-to-end: the site binds it onto the router's distribution
255 * // (alias), certificate (SAN), and Route 53 record set. Wildcard
256 * // patterns and cross-stack router refs register KV host-matching only —
257 * // those hostnames must be covered by the router's own domain.
258 * const site = yield* StaticSite("Docs", {
259 * path: "./docs",
260 * domain: {
261 * name: "docs.example.com",
262 * router,
263 * },
264 * });
265 * ```
266 *
267 * @resource
268 */
269 export const StaticSite = (id: string, props: StaticSiteProps) =>
270 Effect.gen(function* () {
271 const ctx = yield* AlchemyContext;
272 const remoted = yield* ProviderModePolicy;
273 // Mirrors the Cloudflare Website composites: during `alchemy dev` with
274 // a `dev.command`, the site is the external dev server (spawned in the
275 // dev sidecar so it survives user-code HMR) and no cloud resources are
276 // declared; `Alchemy.remote()` opts back into the full live deployment.
277 const isLocal = ctx.dev && remoted !== true;
278
279 if (isLocal && props.dev) {
280 const dev = yield* Command.Dev("Dev", {
281 command: props.dev.command,
282 cwd: props.dev.cwd ?? (typeof props.path === "string" ? props.path : undefined),
283 env: props.dev.env,
284 });
285 const devUrl = Output.map(dev.url, (url) => url ?? props.dev?.url);
286 // A Router-attached site registers with the Router in dev exactly as it
287 // does live — same resource types, same ids, same route entries — with
288 // the local dev server standing in for the S3 origin.
289 const routerDomain = asRouterDomain(normalizeWebsiteDomain(props.domain));
290 const kvNamespace = routerDomain
291 ? yield* registerDevRouterRoute(routerDomain, devUrl)
292 : undefined;
293 return {
294 bucket: undefined,
295 build: undefined,
296 files: undefined,
297 distribution: undefined,
298 invalidation: undefined,
299 kvNamespace,
300 url: devUrl,
301 urls: [devUrl],
302 };
303 }
304
305 return yield* makeKvSite(id, props);
306 }).pipe(Namespace.push(id));
307
308 /**
309 * Dynamic server origin for {@link makeKvSite} — the KV metadata gains a
310 * `servers` entry so requests that match no uploaded file are forwarded to
311 * the server instead of a static fallback.
312 * @internal
313 */
314 export interface KvSiteServerOptions {
315 /**
316 * Hostname of the dynamic server origin (e.g. a Lambda Function URL
317 * host). Requests that miss the file manifest are forwarded here with
318 * `x-forwarded-host` set.
319 */
320 serverHost: Input<string>;
321 /**
322 * Optional dedicated image-optimization origin: requests whose path
323 * starts with `route` (e.g. `/_next/image`) are forwarded to `host`
324 * instead of the server origin (see `metadata.image` in cfcode.ts).
325 */
326 image?: {
327 route: string;
328 host: Input<string>;
329 };
330 }
331
332 /**
333 * Shared implementation behind `StaticSite` and the SSR framework
334 * composites (`AWS.Website.Nuxt`, ...): S3 + CloudFront + KV-manifest edge
335 * routing, optionally with a dynamic server origin for misses.
336 * @internal
337 */
338 export const makeKvSite = Effect.fn("AWS.Website.KvSite")(function* (
339 id: string,
340 props: StaticSiteProps,
341 server?: KvSiteServerOptions,
342 ) {
343 const domain = normalizeWebsiteDomain(props.domain);
344 const routerDomain = domain?.router ? (domain as WebsiteRouterDomainProps) : undefined;
345 const standaloneDomain =
346 domain && !domain.router ? (domain as WebsiteStandaloneDomainProps) : undefined;
347 const sitePath = (props.path ?? ".") as string;
348 const indexPage = props.indexPage ?? "index.html";
349 const assetPrefix = normalizePrefix(props.assets?.path);
350 const assetRoutes = [...(props.assets?.routes ?? [])]
351 .map((value) => value.trim())
352 .filter(Boolean)
353 .map(normalizeRoutePath);
354 const invalidationProps =
355 props.invalidation !== undefined ? props.invalidation : { paths: "all" as const, wait: false };
356
357 if (routerDomain && props.edge) {
358 return yield* Effect.die(
359 `Cannot provide both "edge" and "domain.router". Use the "edge" prop on the Router component.`,
360 );
361 }
362 if (routerDomain && props.cloudfrontUrl !== undefined) {
363 return yield* Effect.die(
364 `"cloudfrontUrl" does not apply to a Router-attached site ("domain.router" is set): the site owns no distribution. Set "cloudfrontUrl" on the Router instead.`,
365 );
366 }
367 if (props.cloudfrontUrl === false && !standaloneDomain) {
368 return yield* Effect.die(
369 `"cloudfrontUrl: false" requires a "domain" — without one the site would be unreachable (the CloudFront default domain is its only URL).`,
370 );
371 }
372 if (routerDomain?.aliases?.length && !routerDomain.name) {
373 return yield* Effect.die(`"domain.aliases" requires "domain.name" on a Router-attached site.`);
374 }
375 if (routerDomain?.redirects?.length && (!routerDomain.name || routerDomain.name.includes("*"))) {
376 return yield* Effect.die(
377 `"domain.redirects" requires a concrete (non-wildcard) "domain.name" to redirect to.`,
378 );
379 }
380 if (standaloneDomain?.redirects?.length && standaloneDomain.name.includes("*")) {
381 return yield* Effect.die(
382 `"domain.redirects" requires a concrete (non-wildcard) "domain.name" to redirect to.`,
383 );
384 }
385 if (props.spa && props.errorPage) {
386 return yield* Effect.die(
387 `Cannot provide both "spa" and "errorPage". A SPA answers misses with the index page (200); "errorPage" answers them with a real 404.`,
388 );
389 }
390 if (server && (props.spa || props.errorPage)) {
391 return yield* Effect.die(
392 `A site with a server origin routes misses to the server; "spa" and "errorPage" do not apply.`,
393 );
394 }
395
396 const build = props.build
397 ? yield* Command.Build("Build", {
398 command: props.build.command,
399 cwd: sitePath,
400 memo: {
401 include: props.build.include,
402 exclude: props.build.exclude,
403 lockfile: props.build.lockfile,
404 },
405 outdir: props.build.output,
406 env: props.build.env,
407 })
408 : undefined;
409
410 const uploadSourcePath = (build?.outdir ?? sitePath) as string;
411
412 const providedBucket = props.assets?.bucket;
413 const bucket =
414 providedBucket ??
415 (yield* Bucket("Bucket", {
416 bucketName: props.bucketName,
417 forceDestroy: props.forceDestroy,
418 tags: props.tags,
419 }));
420
421 const routerPathPrefix = routerDomain?.path
422 ? "/" + routerDomain.path.replace(/^\//, "").replace(/\/$/, "")
423 : undefined;
424
425 const files = yield* AssetDeployment("Files", {
426 bucket: bucket,
427 sourcePath: uploadSourcePath,
428 prefix: normalizeUploadPrefix(assetPrefix, routerPathPrefix),
429 purge: props.assets?.purge ?? true,
430 fileOptions: props.assets?.fileOptions,
431 textEncoding: props.assets?.textEncoding,
432 });
433
434 const stack = yield* Stack;
435 const stage = yield* Stage;
436 const ns = yield* Namespace.CurrentNamespace;
437 const fqn = ns ? toPath(ns).join("/") : id;
438 const kvNamespace = createHash("md5")
439 .update(`${stack.name}-${stage}-${fqn}`)
440 .digest("hex")
441 .substring(0, 4);
442
443 // Standalone distributions carry the asset prefix as the default
444 // origin's `originPath` (so error-page fetches that bypass the edge
445 // function still resolve); router-attached sites prefix at the edge via
446 // the KV metadata instead.
447 const s3MetadataDir = routerDomain && assetPrefix ? "/" + assetPrefix : "";
448
449 const kvEntries = buildKvEntries({
450 files,
451 bucketDomain: bucket.bucketRegionalDomainName as Input<string>,
452 s3Dir: s3MetadataDir,
453 assetRoutes,
454 indexPage,
455 errorPage: props.errorPage,
456 routerPathPrefix,
457 redirect:
458 routerDomain?.redirects?.length && routerDomain.name
459 ? { hosts: routerDomain.redirects, to: routerDomain.name }
460 : undefined,
461 serverHost: server?.serverHost,
462 imageRoute: server?.image?.route,
463 imageHost: server?.image?.host,
464 });
465
466 let distributionId: Input<string>;
467 let kvStoreArn: Input<string>;
468 let distribution: Distribution | undefined;
469 let urls: Input<string>[];
470
471 if (routerDomain) {
472 const routerRef = routerDomain.router;
473 kvStoreArn = routerRef.kvStoreArn;
474 distributionId = routerRef.distributionId;
475 // One KV route entry per host pattern: the canonical name (or the
476 // match-any-host "" pattern), each alias, and each redirect hostname
477 // (so redirected requests still match this site's route — the edge
478 // function then 301s them from the site's KV metadata).
479 const hostPatterns: [id: string, pattern: string | undefined][] = [
480 ["RoutesUpdate", routerDomain.name],
481 ...(routerDomain.aliases ?? []).map((alias, index): [string, string] => [
482 `RoutesUpdateAlias${index + 1}`,
483 alias,
484 ]),
485 ...(routerDomain.redirects ?? []).map((redirect, index): [string, string] => [
486 `RoutesUpdateRedirect${index + 1}`,
487 redirect,
488 ]),
489 ];
490 yield* Effect.forEach(
491 hostPatterns,
492 ([routeId, pattern]) =>
493 KvRoutesUpdate(routeId, {
494 store: kvStoreArn,
495 namespace: routerRef.kvNamespace as any,
496 key: "routes",
497 entry: [
498 "site",
499 kvNamespace,
500 pattern ? toHostPatternRegex(pattern) : "",
501 routerPathPrefix ?? "/",
502 ].join(","),
503 }),
504 { concurrency: "unbounded" },
505 );
506 // Site→Router hostname binding: this site's concrete hostnames are
507 // bound onto the Router's distribution (alias), managed certificate
508 // (SAN — a change replaces the certificate create-first), and Route 53
509 // record set, so the declaration here alone fully provisions the
510 // hostname. Wildcard patterns bind nothing concrete, and cross-stack
511 // Router refs carry no `bindTargets` (bindings are same-stack) — in
512 // both cases the site registers KV host-matching only and the
513 // hostname must be covered by the Router's own `domain`.
514 const concreteHostnames = [
515 ...(routerDomain.name && !routerDomain.name.includes("*") ? [routerDomain.name] : []),
516 ...(routerDomain.aliases ?? []).filter((alias) => !alias.includes("*")),
517 ...(routerDomain.redirects ?? []),
518 ];
519 const bindTargets = routerRef.bindTargets;
520 if (bindTargets && concreteHostnames.length > 0) {
521 if (bindTargets.distribution && isResource(bindTargets.distribution)) {
522 yield* bindTargets.distribution.bind`AWS.Website.Site(${fqn})`({
523 aliases: concreteHostnames,
524 });
525 }
526 if (bindTargets.certificate && isResource(bindTargets.certificate)) {
527 yield* bindTargets.certificate.bind`AWS.Website.Site(${fqn})`({
528 subjectAlternativeNames: concreteHostnames,
529 });
530 }
531 if (bindTargets.records && isResource(bindTargets.records)) {
532 yield* bindTargets.records.bind`AWS.Website.Site(${fqn})`({
533 names: concreteHostnames,
534 });
535 }
536 }
537 // Host-matched attachment: the site's own hostnames (the router's
538 // CloudFront URL never serves it — KV host-match). Path-only
539 // attachment: derived from the router's primary URL, inheriting the
540 // router's precedence (including its `cloudfrontUrl` choice).
541 urls = routerDomain.name
542 ? [
543 `https://${routerDomain.name}${routerPathPrefix ?? ""}`,
544 ...(routerDomain.aliases ?? []).map(
545 (alias) => `https://${alias}${routerPathPrefix ?? ""}`,
546 ),
547 ]
548 : [Output.interpolate`${routerRef.url}${routerPathPrefix ?? ""}`];
549 } else {
550 const domain = standaloneDomain;
551 if (domain && !domain.cert && !domain.hostedZoneId && domain.dns === false) {
552 return yield* Effect.die(
553 "StaticSite domain configuration with `dns: false` requires `cert`.",
554 );
555 }
556
557 const managed =
558 domain && !domain.cert
559 ? yield* domainCertificate(
560 "Certificate",
561 {
562 domainName: domain.name,
563 subjectAlternativeNames: [...(domain.aliases ?? []), ...(domain.redirects ?? [])],
564 hostedZoneId: domain.hostedZoneId,
565 tags: props.tags,
566 },
567 domain.dns,
568 )
569 : undefined;
570 // Resolves once the certificate is issued (see `domainCertificate`).
571 const viewerCertificateArn = managed?.certificateArn ?? domain?.cert;
572
573 const kvStore = yield* KeyValueStore("KvStore", {});
574 kvStoreArn = kvStore.keyValueStoreArn;
575
576 const viewerRequest = yield* CloudFrontFunction("ViewerRequest", {
577 comment: `${id} viewer request`,
578 code: buildRequestFunctionCode({
579 kvNamespace,
580 userInjection: props.edge?.viewerRequest?.injection,
581 hostRedirect: domain
582 ? {
583 to: domain.name,
584 hosts: domain.redirects ?? [],
585 cloudfrontDefault: props.cloudfrontUrl === false,
586 }
587 : undefined,
588 }),
589 keyValueStoreArns: [kvStore.keyValueStoreArn],
590 });
591
592 const viewerResponse = props.edge?.viewerResponse
593 ? yield* CloudFrontFunction("ViewerResponse", {
594 comment: `${id} viewer response`,
595 code: buildResponseFunctionCode(props.edge.viewerResponse.injection),
596 keyValueStoreArns: props.edge.viewerResponse.keyValueStoreArn
597 ? [props.edge.viewerResponse.keyValueStoreArn]
598 : undefined,
599 })
600 : undefined;
601
602 const functionAssociations = [
603 {
604 eventType: "viewer-request" as const,
605 functionArn: viewerRequest.functionArn,
606 },
607 ...(viewerResponse
608 ? [
609 {
610 eventType: "viewer-response" as const,
611 functionArn: viewerResponse.functionArn,
612 },
613 ]
614 : []),
615 ];
616
617 const errorPage = "/" + (props.errorPage ?? indexPage).replace(/^\//, "");
618 const customErrorResponses =
619 props.errorPage && !server
620 ? [
621 {
622 ErrorCode: 403,
623 ResponseCode: "404",
624 ResponsePagePath: errorPage,
625 ErrorCachingMinTTL: 0,
626 },
627 {
628 ErrorCode: 404,
629 ResponseCode: "404",
630 ResponsePagePath: errorPage,
631 ErrorCachingMinTTL: 0,
632 },
633 ]
634 : undefined;
635
636 // Server-backed sites share one behavior between S3 assets and the
637 // dynamic origin, so the cache policy must not cache responses that
638 // carry no Cache-Control (SSR pages) while still honoring the
639 // immutable Cache-Control the asset uploader sets. Managed
640 // CachingOptimized would cache header-less SSR responses for a day.
641 const serverCachePolicy = server
642 ? yield* CachePolicy("ServerCachePolicy", {
643 comment: `${id} server cache policy`,
644 minTTL: 0,
645 defaultTTL: 0,
646 maxTTL: "365 days",
647 parametersInCacheKeyAndForwardedToOrigin: {
648 EnableAcceptEncodingGzip: true,
649 EnableAcceptEncodingBrotli: true,
650 QueryStringsConfig: { QueryStringBehavior: "all" },
651 HeadersConfig: { HeaderBehavior: "none" },
652 CookiesConfig: { CookieBehavior: "none" },
653 },
654 })
655 : undefined;
656
657 // The default origin is real (not a placeholder): static sites point
658 // at the bucket through an OAC so requests that bypass the edge
659 // function's origin switch — CloudFront's custom-error-page fetches
660 // in particular — still resolve; server-backed sites point at the
661 // server so misses stream from it even if the function is bypassed.
662 const oac = server
663 ? undefined
664 : yield* OriginAccessControl("OriginAccessControl", {
665 originType: "s3",
666 description: `${id} origin access control`,
667 });
668
669 distribution = yield* Distribution("Distribution", {
670 aliases: domain
671 ? [domain.name, ...(domain.aliases ?? []), ...(domain.redirects ?? [])]
672 : undefined,
673 origins: [
674 server
675 ? {
676 id: "default",
677 domainName: server.serverHost,
678 customOriginConfig: {
679 httpPort: 80,
680 httpsPort: 443,
681 originProtocolPolicy: "https-only" as const,
682 originReadTimeout: "20 seconds",
683 originSslProtocols: ["TLSv1.2"],
684 },
685 }
686 : {
687 id: "default",
688 domainName: bucket.bucketRegionalDomainName,
689 s3Origin: true,
690 originAccessControlId: oac!.originAccessControlId,
691 originPath: assetPrefix ? "/" + assetPrefix : undefined,
692 },
693 ],
694 defaultCacheBehavior: {
695 targetOriginId: "default",
696 viewerProtocolPolicy: "redirect-to-https",
697 allowedMethods: ["DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT"],
698 cachedMethods: ["GET", "HEAD"],
699 compress: true,
700 cachePolicyId: serverCachePolicy
701 ? serverCachePolicy.cachePolicyId
702 : MANAGED_CACHING_OPTIMIZED_POLICY_ID,
703 originRequestPolicyId: server ? MANAGED_ALL_VIEWER_EXCEPT_HOST_HEADER_POLICY_ID : undefined,
704 functionAssociations,
705 },
706 customErrorResponses,
707 viewerCertificate: viewerCertificateArn
708 ? {
709 acmCertificateArn: viewerCertificateArn,
710 sslSupportMethod: "sni-only",
711 minimumProtocolVersion: "TLSv1.2_2021",
712 }
713 : undefined,
714 tags: props.tags,
715 });
716
717 const dist = distribution;
718 distributionId = dist.distributionId;
719
720 const dns =
721 domain && domain.dns !== false
722 ? yield* resolveDomainDns(domain.dns, domain.hostedZoneId)
723 : undefined;
724 if (domain && dns) {
725 yield* Effect.forEach(
726 [domain.name, ...(domain.aliases ?? []), ...(domain.redirects ?? [])],
727 (name, index) =>
728 // The DNS host infers the zone containing `name` unless one is
729 // pinned.
730 dns.alias(`AliasRecord${index + 1}`, {
731 name,
732 target: {
733 hostname: dist.domainName,
734 route53Alias: { hostedZoneId: dist.hostedZoneId },
735 },
736 }),
737 { concurrency: "unbounded" },
738 );
739 }
740
741 // Precedence: the canonical domain, then aliases in declaration
742 // order, then the CloudFront default domain (only while
743 // `cloudfrontUrl` is enabled). Redirect hostnames never appear.
744 //
745 // `dist.url` rather than an interpolated
746 // `https://${dist.domainName}` (same as Router): the distribution
747 // knows its own address, which is `https://{id}.cloudfront.net` on
748 // AWS and `http://localhost:{port}` under `alchemy dev`, where that
749 // AWS hostname resolves to nothing.
750 urls = domain
751 ? [
752 Output.interpolate`https://${domain.name}`,
753 ...(domain.aliases ?? []).map((alias) => `https://${alias}`),
754 ...(props.cloudfrontUrl !== false ? [dist.url] : []),
755 ]
756 : [dist.url];
757 }
758
759 // The edge router signs S3 origin requests with OAC (sigv4, see
760 // `setS3Origin` in cfcode.ts), so the bucket must allow the serving
761 // distribution — without this policy every request 403s.
762 const servingDistributionArn = routerDomain
763 ? routerDomain.router.distributionArn
764 : distribution!.distributionArn;
765 const bucketPolicy: PolicyStatement = {
766 Effect: "Allow",
767 Principal: {
768 Service: "cloudfront.amazonaws.com",
769 },
770 Action: ["s3:GetObject"],
771 Resource: [Output.interpolate`${bucket.bucketArn}/*` as any],
772 Condition: {
773 StringEquals: {
774 "AWS:SourceArn": servingDistributionArn as any,
775 },
776 },
777 };
778 yield* bucket.bind`AWS.S3.Policy(CloudFront, ${bucket})`({
779 policyStatements: [bucketPolicy],
780 });
781
782 yield* KvEntries("KvEntries", {
783 store: kvStoreArn,
784 namespace: kvNamespace,
785 entries: kvEntries,
786 purge: props.assets?.purge ?? true,
787 });
788
789 const invalidation =
790 invalidationProps === false
791 ? undefined
792 : yield* Invalidation("Invalidation", {
793 distributionId: distributionId,
794 version: files.version,
795 wait: invalidationProps?.wait,
796 paths:
797 invalidationProps?.paths === "all" || !invalidationProps?.paths
798 ? ["/*"]
799 : invalidationProps.paths === "versioned"
800 ? [`/${indexPage.replace(/^\/+/, "")}`]
801 : invalidationProps.paths,
802 });
803
804 return {
805 bucket: bucket,
806 build,
807 files,
808 distribution,
809 invalidation,
810 kvNamespace,
811 /**
812 * The most significant URL the site serves at — always `urls[0]`.
813 */
814 url: urls[0],
815 /**
816 * Every URL that serves this site, most significant first —
817 * `[https://<domain.name>?, ...aliases, <CloudFront default domain>?]`
818 * (the default domain only while `cloudfrontUrl` is enabled).
819 * Router-attached sites list their own hostnames (host-matched) or
820 * the router's URL plus `domain.path` (path-only). Redirect
821 * hostnames never appear — they serve no content.
822 */
823 urls,
824 };
825 });
826
827 /**
828 * Derive the CloudFront KV routing entries from the *uploaded* file list
829 * (the `AssetDeployment`'s `files` attribute) so the manifest always
830 * reflects exactly what landed in S3 — including build outputs that do not
831 * exist at plan time.
832 */
833 const buildKvEntries = (args: {
834 files: { files: Output.Output<string[]> };
835 bucketDomain: Input<string>;
836 s3Dir: string;
837 assetRoutes: string[];
838 indexPage: string;
839 errorPage: string | undefined;
840 routerPathPrefix: string | undefined;
841 redirect: { hosts: string[]; to: string } | undefined;
842 serverHost: Input<string> | undefined;
843 imageRoute: string | undefined;
844 imageHost: Input<string> | undefined;
845 }): Input<Record<string, string>> =>
846 Output.map(
847 ([fileList, bucketDomain, serverHost, imageHost]: [
848 string[] | undefined,
849 string,
850 string | undefined,
851 string | undefined,
852 ]) => {
853 const entries: Record<string, string> = {};
854 for (const file of fileList ?? []) {
855 entries[`/${file}`] = "s3";
856 }
857 const errorPagePath = "/" + (args.errorPage ?? args.indexPage).replace(/^\//, "");
858 const metadata: KvSiteMetadata = {
859 base:
860 args.routerPathPrefix && args.routerPathPrefix !== "/"
861 ? args.routerPathPrefix
862 : undefined,
863 custom404: serverHost !== undefined || args.errorPage ? undefined : errorPagePath,
864 errorResponseCode: serverHost === undefined && args.errorPage ? 404 : undefined,
865 s3: {
866 domain: bucketDomain,
867 dir: args.s3Dir,
868 routes: args.assetRoutes,
869 },
870 servers: serverHost !== undefined ? [[serverHost]] : undefined,
871 image:
872 args.imageRoute !== undefined && imageHost !== undefined
873 ? { route: args.imageRoute, host: imageHost }
874 : undefined,
875 redirect: args.redirect,
876 };
877 entries["metadata"] = JSON.stringify(metadata);
878 return entries;
879 },
880 )(
881 Output.all(
882 args.files.files,
883 Output.asOutput(args.bucketDomain as any),
884 Output.asOutput(args.serverHost as any),
885 Output.asOutput(args.imageHost as any),
886 ) as Output.Output<[string[] | undefined, string, string | undefined, string | undefined]>,
887 );
888
889 interface KvSiteMetadata {
890 base?: string | undefined;
891 custom404?: string | undefined;
892 errorResponseCode?: number | undefined;
893 s3: {
894 domain: string;
895 dir: string;
896 routes: string[];
897 };
898 /**
899 * Server origin hosts (`[[host, lat?, lon?], ...]`) the edge router
900 * forwards misses to — see `findNearestServer` in cfcode.ts.
901 */
902 servers?: Array<Array<string>> | undefined;
903 /**
904 * Dedicated image-optimization origin: requests whose path starts with
905 * `route` are forwarded to `host` — see `metadata.image` in cfcode.ts.
906 */
907 image?: { route: string; host: string } | undefined;
908 /**
909 * Router-attached redirect hostnames: matched requests whose `Host` is
910 * in `hosts` are 301'd to `https://<to>` (path + query preserved) — see
911 * the `metadata.redirect` check in `routeSite` in cfcode.ts.
912 */
913 redirect?: { hosts: string[]; to: string } | undefined;
914 }
915
916 const buildRequestFunctionCode = ({
917 kvNamespace,
918 userInjection,
919 hostRedirect,
920 }: {
921 kvNamespace: string;
922 userInjection?: string;
923 hostRedirect?: {
924 to: string;
925 hosts: string[];
926 cloudfrontDefault: boolean;
927 };
928 }) => `import cf from "cloudfront";
929 async function handler(event) {
930 ${userInjection ?? ""}
931 ${
932 hostRedirect
933 ? buildHostRedirectInjection({
934 to: hostRedirect.to,
935 hosts: hostRedirect.hosts,
936 cloudfrontDefault: hostRedirect.cloudfrontDefault,
937 })
938 : ""
939 }
940 ${CF_ROUTER_INJECTION}
941
942 const kvNamespace = "${kvNamespace}";
943
944 let metadata;
945 try {
946 const v = await cf.kvs().get(kvNamespace + ":metadata");
947 metadata = JSON.parse(v);
948 } catch (e) {}
949
950 const response = await routeSite(kvNamespace, metadata);
951 return response || event.request;
952 }`;
953
954 const buildResponseFunctionCode = (userInjection?: string) => `import cf from "cloudfront";
955 async function handler(event) {
956 ${userInjection ?? ""}
957 return event.response;
958 }`;
959
960 const normalizePrefix = (prefix: string | undefined) =>
961 prefix ? prefix.replace(/^\/+|\/+$/g, "") : "";
962
963 const normalizeUploadPrefix = (assetPrefix: string, routerPathPrefix: string | undefined) => {
964 const parts = [assetPrefix, routerPathPrefix?.replace(/^\//, "")].filter(Boolean);
965 return parts.join("/") || "";
966 };
967
968 const normalizeRoutePath = (value: string) => `/${value.replace(/^\/+|\/+$/g, "")}`;
969
970 /**
971 * Convert a host pattern (`docs.example.com`, `*.example.com`) into the
972 * escaped regex fragment stored in the Router's KV route table (matched by
973 * the router's edge function).
974 */
975 const toHostPatternRegex = (pattern: string) =>
976 pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");