@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, 04:45 UTC

main
ts 143 lines 5.37 KB
Raw
1 import { createHash } from "node:crypto";
2 import { toPath } from "alchemy/FQN";
3 import type { Input } from "alchemy/Input";
4 import * as Namespace from "alchemy/Namespace";
5 import * as Output from "alchemy/Output";
6 import { Stack } from "alchemy/Stack";
7 import { Stage } from "alchemy/Stage";
8 import * as Effect from "effect/Effect";
9 import { KvEntries } from "../CloudFront/KvEntries.ts";
10 import { KvRoutesUpdate } from "../CloudFront/KvRoutesUpdate.ts";
11 import type { WebsiteDomainProps, WebsiteRouterDomainProps } from "./shared.ts";
12
13 /**
14 * Narrow a normalized `domain` prop to its Router-attached shape.
15 * @internal
16 */
17 export const asRouterDomain = (
18 domain: WebsiteDomainProps | undefined,
19 ): WebsiteRouterDomainProps | undefined =>
20 domain && "router" in domain && domain.router ? (domain as WebsiteRouterDomainProps) : undefined;
21
22 /**
23 * Escape a host pattern into the regex form the Router's edge function
24 * matches against. Mirrors `toHostPatternRegex` in StaticSite.ts.
25 */
26 const toHostPatternRegex = (pattern: string) =>
27 pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
28
29 /**
30 * Register a **dev-mode** site with its `AWS.Website.Router`.
31 *
32 * `alchemy dev` replaces a site's S3 bucket + asset upload with the
33 * framework's own dev server, but the Router-facing subgraph stays exactly
34 * the same resource types as a live deploy — `KvRoutesUpdate` route entries
35 * (byte-identical to live) plus a `KvEntries` metadata blob. Only the
36 * metadata *contents* differ: instead of an `s3` origin plus a file
37 * manifest, dev writes a `servers` origin pointing at the local dev
38 * server, which `routeSite()` in cfcode.ts already handles (every KV file
39 * lookup misses, so it falls through to `setUrlOrigin`).
40 *
41 * There is deliberately no dev-only resource type and no `ctx.dev` branch
42 * inside `Router`: switching between `alchemy dev` and `alchemy deploy`
43 * must be a `providerMode` change on the same graph, not a different graph.
44 *
45 * Must be called from inside the site's own namespace (the composites call
46 * it after `Namespace.push(id)`) so the KV namespace hash and the child
47 * resource FQNs match the live path exactly.
48 *
49 * @returns the site's URLs, computed the same way the live Router
50 * attachment computes them.
51 * @internal
52 */
53 export const registerDevRouterRoute = Effect.fn("AWS.Website.DevRouterRoute")(function* (
54 domain: WebsiteRouterDomainProps,
55 /** The local dev server's URL (e.g. `http://localhost:5173`). */
56 devUrl: Input<string | undefined>,
57 ) {
58 const router = domain.router;
59 const stack = yield* Stack;
60 const stage = yield* Stage;
61 const ns = yield* Namespace.CurrentNamespace;
62 const fqn = ns ? toPath(ns).join("/") : "";
63 const kvNamespace = createHash("md5")
64 .update(`${stack.name}-${stage}-${fqn}`)
65 .digest("hex")
66 .substring(0, 4);
67
68 const routerPathPrefix = domain.path
69 ? "/" + domain.path.replace(/^\//, "").replace(/\/$/, "")
70 : undefined;
71
72 // One KV route entry per host pattern — identical shape, ids, and
73 // ordering to the live attachment in `makeKvSite`.
74 const hostPatterns: [id: string, pattern: string | undefined][] = [
75 ["RoutesUpdate", domain.name],
76 ...(domain.aliases ?? []).map((alias, index): [string, string] => [
77 `RoutesUpdateAlias${index + 1}`,
78 alias,
79 ]),
80 ...(domain.redirects ?? []).map((redirect, index): [string, string] => [
81 `RoutesUpdateRedirect${index + 1}`,
82 redirect,
83 ]),
84 ];
85
86 yield* Effect.forEach(
87 hostPatterns,
88 ([routeId, pattern]) =>
89 KvRoutesUpdate(routeId, {
90 store: router.kvStoreArn,
91 namespace: router.kvNamespace as any,
92 key: "routes",
93 entry: [
94 "site",
95 kvNamespace,
96 pattern ? toHostPatternRegex(pattern) : "",
97 routerPathPrefix ?? "/",
98 ].join(","),
99 }),
100 { concurrency: "unbounded" },
101 );
102
103 const redirect =
104 domain.redirects?.length && domain.name
105 ? { hosts: domain.redirects, to: domain.name }
106 : undefined;
107
108 yield* KvEntries("KvEntries", {
109 store: router.kvStoreArn,
110 namespace: kvNamespace,
111 entries: {
112 metadata: Output.map(
113 Output.asOutput(devUrl as any) as Output.Output<string | undefined>,
114 (resolved) => {
115 if (!resolved) {
116 throw new Error(
117 "A Router-attached site needs a dev server URL to route to during `alchemy dev` — set `dev.url` (or make the dev command print its own localhost URL).",
118 );
119 }
120 return JSON.stringify({
121 base: routerPathPrefix && routerPathPrefix !== "/" ? routerPathPrefix : undefined,
122 // `[[host]]` — one server, no geo coordinates, so
123 // `findNearestServer` returns it unconditionally. The host
124 // carries the dev server's port; the emulated edge resolves
125 // loopback origins to a container-reachable address.
126 servers: [[new URL(resolved).host]],
127 // Dev servers speak plain HTTP. `setUrlOrigin` in cfcode.ts
128 // already threads `metadata.origin` through to
129 // `cf.updateRequestOrigin`.
130 origin: { protocol: "http" },
131 redirect,
132 });
133 },
134 ),
135 },
136 purge: true,
137 });
138
139 // The site's own `url` output stays the dev server's localhost address
140 // (the point of `alchemy dev` is the HMR server); the Router serves the
141 // same content at `router.url + domain.path`.
142 return kvNamespace;
143 });