@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 251 lines 9.54 KB
Raw
1 /**
2 * `@alchemy.run/frontend-frameworks/astro/node` — the Node container deploy
3 * target for the Astro integration.
4 *
5 * Astro's Node story is a plain Node SSR bundle behind a long-running HTTP
6 * server: the adapter integration pins this package's `node-server`
7 * entrypoint (which exports `App.render` as a fetch handler) as the build's
8 * server entry, and forces the server build to be **self-contained**
9 * (`vite.ssr.noExternal: true`). The finishing pass writes a Node HTTP
10 * program that serves `clientDirectory` first, then falls through to that
11 * handler on `PORT` (default 3000), and answers `GET /health`.
12 *
13 * - **`integration`** — the adapter integration: registers itself via
14 * `setAdapter` at `astro:config:done` (rejecting a user-declared adapter
15 * with an actionable error) and pins the `node-server` entrypoint.
16 * - **`finish`** — a fully-static build (`output: "static"`) writes the
17 * same Node static serve entry Vite uses. Otherwise writes the HTTP
18 * serve entry (static files then the Astro fetch handler) and pins it
19 * as `serverModules[0]`.
20 * - **`selectServerEntry`** — pins the adapter's entry chunk as
21 * `serverModules[0]` before the finishing pass wraps it.
22 * - **`bundle`** — Node resolve conditions (no `workerd`, no `@aws-sdk/`).
23 */
24 import type { AstroInlineConfig, AstroIntegration } from "astro";
25 import * as Effect from "effect/Effect";
26 import * as Path from "effect/Path";
27 import { runBuildChild } from "../core/BuildChild.ts";
28 import { DeployTargetError, makeDeployTarget, type ServerEntryChunk } from "../core/index.ts";
29 import {
30 NODE_BUNDLE_CONDITIONS,
31 NODE_SERVE_ENTRY_FILE_NAME,
32 relativeClientDirExpression,
33 writeNodeServeEntry,
34 type NodeServeHtmlHandling,
35 type NodeServeNotFoundHandling,
36 } from "../core/NodeServe.ts";
37 import { make } from "./Astro.ts";
38 import type { AstroTarget, AstroTargetBuildContext } from "./Target.ts";
39
40 /**
41 * The importable specifier of this package's Node server entrypoint — the
42 * module the adapter pins as `serverEntrypoint`. It exports a fetch
43 * `handler`.
44 */
45 export const SERVER_ENTRYPOINT = "@alchemy.run/frontend-frameworks/astro/entrypoints/node-server";
46
47 /** Node-specific target configuration. */
48 export interface AstroNodeConfig {
49 readonly htmlHandling?: NodeServeHtmlHandling;
50 readonly notFoundHandling?: NodeServeNotFoundHandling;
51 }
52
53 export interface AstroNodeTarget extends AstroTarget<AstroNodeConfig> {}
54
55 /** Options for {@link distilledNode} (the adapter integration). */
56 export interface DistilledNodeOptions {
57 /**
58 * Reports the resolved build output mode (`astro:config:done`'s
59 * `buildOutput`): `"static"` when every route is prerendered, `"server"`
60 * when any route renders on demand. The target's `finish` pass uses it to
61 * strip `serverModules` from a fully-static build so the deploy is
62 * assets-only.
63 * @internal
64 */
65 readonly onBuildOutput?: ((buildOutput: "static" | "server") => void) | undefined;
66 /**
67 * Reports the resolved server-entry file name (`config.build.serverEntry`,
68 * `entry.mjs` by default) so the entry chunk can be pinned as
69 * `serverModules[0]` before the serve wrap.
70 * @internal
71 */
72 readonly onServerEntryName?: ((name: string) => void) | undefined;
73 }
74
75 /**
76 * The Node adapter integration for Astro. Injected via `integrations`
77 * (after the user's) rather than `adapter`: it registers itself as the
78 * adapter at `astro:config:done`, where it also rejects a user-declared
79 * adapter with an actionable error.
80 */
81 export const distilledNode = (options: DistilledNodeOptions = {}): AstroIntegration => {
82 let injectedAdapterMarker = false;
83 return {
84 name: "@alchemy.run/frontend-frameworks/astro-node",
85 hooks: {
86 "astro:config:setup": ({ config, updateConfig }) => {
87 if (config.adapter === undefined) {
88 injectedAdapterMarker = true;
89 updateConfig({
90 adapter: {
91 name: "@alchemy.run/frontend-frameworks/astro-node",
92 hooks: {},
93 },
94 });
95 }
96 },
97 "astro:config:done": ({ setAdapter, config, buildOutput }) => {
98 if (config.adapter !== undefined && !injectedAdapterMarker) {
99 throw new Error(
100 `@alchemy.run/frontend-frameworks/astro/node: the Astro config declares the adapter "${config.adapter.name}", ` +
101 "but the deploy target already provides the Node adapter. " +
102 "Remove `adapter` from your astro.config file — user integrations " +
103 "(react, mdx, tailwind, ...) are honored, and the adapter is injected by the toolchain.",
104 );
105 }
106 options.onBuildOutput?.(buildOutput);
107 options.onServerEntryName?.(config.build.serverEntry);
108 setAdapter({
109 name: "@alchemy.run/frontend-frameworks/astro-node",
110 entrypointResolution: "auto",
111 serverEntrypoint: SERVER_ENTRYPOINT,
112 adapterFeatures: {
113 buildOutput,
114 middlewareMode: "classic",
115 preserveBuildClientDir: true,
116 preserveBuildServerDir: true,
117 },
118 supportedAstroFeatures: {
119 serverOutput: "stable",
120 hybridOutput: "stable",
121 staticOutput: "stable",
122 i18nDomains: "experimental",
123 envGetSecret: "stable",
124 sharpImageService: {
125 support: "limited",
126 message:
127 "sharp is not shipped with the Node server bundle; install it as a project dependency to optimize images at build time",
128 },
129 },
130 });
131 },
132 "astro:build:setup": ({ vite: viteConfig, target }) => {
133 if (target === "server") {
134 viteConfig.ssr ||= {};
135 viteConfig.ssr.noExternal = true;
136 }
137 },
138 },
139 };
140 };
141
142 const fail = (message: string, cause?: unknown) =>
143 new DeployTargetError({ platform: "node", message, cause });
144
145 const makeNodeAdapterTarget = (config: AstroNodeConfig = {}): AstroNodeTarget => {
146 let buildOutput: "static" | "server" | undefined;
147 let serverEntryName: string | undefined;
148 return makeDeployTarget({
149 platform: "node",
150 config,
151 bundle: {
152 conditions: [...NODE_BUNDLE_CONDITIONS],
153 },
154 integration: () =>
155 distilledNode({
156 onBuildOutput: (mode) => {
157 buildOutput = mode;
158 },
159 onServerEntryName: (name) => {
160 serverEntryName = name;
161 },
162 }),
163 selectServerEntry: (chunk: ServerEntryChunk): boolean =>
164 chunk.fileName === (serverEntryName ?? "entry.mjs") ||
165 (chunk.facadeModuleId !== null &&
166 /\/entrypoints\/node-server\.(?:ts|js|mjs)$/.test(
167 chunk.facadeModuleId.replaceAll("\\", "/"),
168 )),
169 finish: (output) =>
170 Effect.gen(function* () {
171 const path = yield* Path.Path;
172 if (buildOutput === "static") {
173 if (output.clientDirectory === undefined) {
174 return yield* fail(
175 "The Astro static build produced no client directory for the Node serve entry",
176 );
177 }
178 const servePath = path.join(output.clientDirectory, NODE_SERVE_ENTRY_FILE_NAME);
179 return yield* writeNodeServeEntry({
180 output: { ...output, distDirectory: output.clientDirectory },
181 servePath,
182 serveModuleName: NODE_SERVE_ENTRY_FILE_NAME,
183 clientDirExpression: `fileURLToPath(new URL("./", import.meta.url))`,
184 notFoundHandling: config.notFoundHandling ?? "spa",
185 htmlHandling: config.htmlHandling,
186 platform: "node",
187 });
188 }
189 if (output.distDirectory === undefined || output.clientDirectory === undefined) {
190 return yield* fail(
191 "The Astro build produced no dist/client directories for the Node serve entry",
192 );
193 }
194 const entryName = serverEntryName ?? "entry.mjs";
195 const servePath = path.join(output.distDirectory, "server", NODE_SERVE_ENTRY_FILE_NAME);
196 return yield* writeNodeServeEntry({
197 output,
198 servePath,
199 serveModuleName: path.join("server", NODE_SERVE_ENTRY_FILE_NAME).replaceAll("\\", "/"),
200 clientDirExpression: relativeClientDirExpression(servePath, output.clientDirectory),
201 handler: {
202 kind: "fetch",
203 imports: `import { handler } from ${JSON.stringify(`./${entryName}`)};`,
204 expr: "handler",
205 },
206 notFoundHandling: config.notFoundHandling,
207 htmlHandling: config.htmlHandling,
208 platform: "node",
209 });
210 }),
211 });
212 };
213
214 export interface AstroNodeBuildChildConfig {
215 readonly rootDir: string;
216 readonly config: AstroNodeConfig;
217 readonly astro: AstroInlineConfig | undefined;
218 }
219
220 export const buildInChild = (config: AstroNodeBuildChildConfig) =>
221 Effect.gen(function* () {
222 const framework = yield* make({
223 root: config.rootDir,
224 target: makeNodeAdapterTarget(config.config),
225 astro: config.astro,
226 });
227 return yield* framework.build({ root: config.rootDir });
228 });
229
230 /**
231 * Build the Node {@link AstroTarget}. See the module doc for the seams.
232 */
233 export const makeNodeTarget = (config: AstroNodeConfig = {}): AstroNodeTarget => ({
234 ...makeNodeAdapterTarget(config),
235 build: (context: AstroTargetBuildContext) =>
236 runBuildChild({
237 module: import.meta.url,
238 rootDir: context.root,
239 env: context.env,
240 framework: "astro",
241 config: {
242 rootDir: context.root,
243 config,
244 astro: context.astro,
245 } satisfies AstroNodeBuildChildConfig,
246 }).pipe(Effect.mapError((error) => fail(error.message, error.cause))),
247 });
248
249 export const target = makeNodeTarget;
250
251 export default makeNodeTarget;