@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 228 lines 7.12 KB
Raw
1 import { AlchemyContext } from "alchemy/AlchemyContext";
2 import * as Command from "alchemy/Command";
3 import type { MemoOptions } from "alchemy/Command/Memo";
4 import * as Namespace from "alchemy/Namespace";
5 import * as Output from "alchemy/Output";
6 import { ProviderModePolicy } from "alchemy/ProviderMode";
7 import { initialCwd } from "alchemy/Util/Node";
8 import { loadFrontendCore } from "alchemy/Website/FrontendCore";
9 import * as Effect from "effect/Effect";
10 import * as Path from "effect/Path";
11 import type * as Redacted from "effect/Redacted";
12 import { Service } from "../Run/Service.ts";
13 import {
14 type FrameworkSite,
15 type WebsiteAssetsProps,
16 type WebsiteServiceProps,
17 staticConfigFromAssets,
18 websiteServiceProps,
19 } from "./FrameworkSite.ts";
20
21 export interface StaticSiteProps extends WebsiteServiceProps {
22 /**
23 * Path to the local site directory (working directory for
24 * {@link build.command}).
25 * @default "."
26 */
27 path?: string;
28 /**
29 * Build executed before deploy.
30 */
31 build: {
32 /** Shell command that produces the site (e.g. `"hugo --minify"`). */
33 command: string;
34 /** Directory the command writes, relative to {@link path}. */
35 output: string;
36 /** Environment variables for the build command. */
37 env?: Record<string, string | Redacted.Redacted<string>>;
38 };
39 /**
40 * Controls which files are hashed to decide whether the build re-runs.
41 * @default true
42 */
43 memo?: MemoOptions | boolean;
44 /**
45 * Process environment for the hosted static server.
46 */
47 env?: Record<string, string | Redacted.Redacted<string>>;
48 /**
49 * Miss handling for the generated file server.
50 */
51 assets?: WebsiteAssetsProps;
52 /**
53 * Local dev configuration. When `alchemy dev` runs with `dev.command`,
54 * the build is skipped and `command` is spawned as a long-lived child.
55 */
56 dev?: {
57 /**
58 * Shell command to run as the local dev server (e.g. `npm run dev`).
59 */
60 command: string;
61 /**
62 * Working directory for {@link command}. Defaults to {@link path}.
63 */
64 cwd?: string;
65 /**
66 * Environment variables for {@link command}.
67 */
68 env?: Record<string, string | Redacted.Redacted<string>>;
69 /**
70 * Override for the `url` output if alchemy fails to detect it from
71 * stdout of the dev command.
72 */
73 url?: string;
74 };
75 }
76
77 /**
78 * Deploy a static site built by a shell command to Cloud Run.
79 *
80 * `StaticSite` runs a build command (e.g. `npm run build` / `hugo`),
81 * content-hashes the output directory, and deploys a Cloud Run service
82 * whose image is a tiny Node file server over those files (plus
83 * `/health`). Use this when the site has its own build step — Hugo, Zola,
84 * Eleventy, or any custom pipeline.
85 *
86 * For Vite-based projects, prefer `GCP.Website.Vite`. For a bucket-backed
87 * site behind a CDN, compose `GCP.Storage.Bucket` with a load balancer
88 * instead (see the `gcp-static-site` example).
89 *
90 * `Build` / `Dev` use constant logical ids under `Namespace.push(id)`.
91 * The Cloud Run service stays in the caller namespace.
92 *
93 *
94 * ### Basic Usage
95 * **Example:** Deploying a Hugo site
96 * ```typescript
97 * const site = yield* GCP.Website.StaticSite("Blog", {
98 * build: { command: "hugo --minify", output: "public" },
99 * });
100 * ```
101 *
102 * **Example:** SPA-style routing
103 * ```typescript
104 * const site = yield* GCP.Website.StaticSite("App", {
105 * build: { command: "npm run build", output: "dist" },
106 * assets: { notFoundHandling: "single-page-application" },
107 * });
108 * ```
109 *
110 * ### Building from a Subdirectory
111 * **Example:** Building a frontend in a monorepo
112 * ```typescript
113 * const site = yield* GCP.Website.StaticSite("Web", {
114 * path: "apps/web",
115 * build: { command: "npm run build", output: "dist" },
116 * });
117 * ```
118 *
119 * ### Cloud Run Settings
120 * **Example:** Private site with a warm instance
121 * ```typescript
122 * const site = yield* GCP.Website.StaticSite("Internal", {
123 * build: { command: "npm run build", output: "dist" },
124 * public: false,
125 * scaling: { minInstanceCount: 1 },
126 * });
127 * ```
128 *
129 * ### Local Development
130 * **Example:** External dev command
131 * ```typescript
132 * const site = yield* GCP.Website.StaticSite("App", {
133 * build: { command: "npm run build", output: "dist" },
134 * dev: { command: "npm run dev" },
135 * });
136 * ```
137 *
138 * @resource
139 * @product Website
140 */
141 export const StaticSite = (id: string, props: StaticSiteProps) =>
142 Effect.gen(function* () {
143 const ctx = yield* AlchemyContext;
144 const remoted = yield* ProviderModePolicy;
145 const isLocal = ctx.dev && remoted !== true;
146 const path = yield* Path.Path;
147
148 if (isLocal && props.dev) {
149 const dev = yield* Command.Dev("Dev", {
150 command: props.dev.command,
151 cwd: props.dev.cwd ?? props.path,
152 env: props.dev.env ?? props.env,
153 }).pipe(Namespace.push(id));
154 const url = Output.map(dev.url, (value) => value ?? props.dev?.url);
155 return { url, service: undefined } satisfies FrameworkSite;
156 }
157
158 const build = yield* Command.Build("Build", {
159 command: props.build.command,
160 cwd: props.path,
161 memo: props.memo,
162 outdir: props.build.output,
163 env: props.build.env ?? props.env,
164 }).pipe(Namespace.push(id));
165
166 const cwd = path.resolve(initialCwd, props.path ?? ".");
167 const outdir = path.resolve(cwd, props.build.output);
168 const internal = staticConfigFromAssets(props.assets);
169 const notFoundHandling =
170 internal.errorPage !== undefined
171 ? ("404-page" as const)
172 : internal.spa === true
173 ? ("spa" as const)
174 : ("none" as const);
175
176 const { NODE_SERVE_ENTRY_FILE_NAME, relativeClientDirExpression, writeNodeServeEntry } =
177 yield* loadFrontendCore;
178 const servePath = path.join(path.dirname(outdir), NODE_SERVE_ENTRY_FILE_NAME);
179 yield* writeNodeServeEntry({
180 output: {
181 clientDirectory: outdir,
182 serverModules: [],
183 externalWorkspaces: new Set<string>(),
184 },
185 servePath,
186 serveModuleName: NODE_SERVE_ENTRY_FILE_NAME,
187 clientDirExpression: relativeClientDirExpression(servePath, outdir),
188 notFoundHandling,
189 printUrl: isLocal,
190 platform: "node",
191 });
192
193 if (isLocal) {
194 const runtime = yield* Effect.sync(() => process.execPath);
195 const dev = yield* Command.Dev("Dev", {
196 command: `${runtime} ${servePath}`,
197 cwd: path.dirname(servePath),
198 env: {
199 ...props.env,
200 PORT: "0",
201 HOST: "127.0.0.1",
202 ALCHEMY_BUILD_HASH: build.hash.output as unknown as string,
203 },
204 }).pipe(Namespace.push(id));
205 return {
206 url: Output.map(dev.url, (value) => value),
207 service: undefined,
208 } satisfies FrameworkSite;
209 }
210
211 const service = yield* Service(
212 id,
213 websiteServiceProps(props, {
214 main: servePath,
215 extraFiles: [
216 {
217 // Keep the build dependency so planning cannot hash the previous artifact.
218 source: Output.map(build.outdir, (dir) =>
219 path.resolve(initialCwd, dir),
220 ) as unknown as string,
221 dest: path.basename(outdir),
222 },
223 ],
224 }),
225 );
226
227 return { url: service.uri, service } satisfies FrameworkSite;
228 }).pipe(Effect.orDie);