The best way to control Claude Code, Codex and more from any computer or phone

main
ts 173 lines 6.8 KB
Raw
1 /**
2 * `@alchemy.run/frontend-frameworks/octane/node` — the Node container deploy
3 * target for the Octane integration.
4 *
5 * Node-hosted `Website.Octane` resources select this target, which
6 * automatically wraps Octane's default native Node output. No adapter is
7 * required in `octane.config.ts`: the project's own `vite build` emits
8 * `dist/server/entry.js`, a self-contained Node ESM bundle exporting a
9 * web-standard fetch `handler`.
10 * The finishing pass writes a Node HTTP program that serves
11 * `clientDirectory` first, then falls through to that handler on `PORT`
12 * (default 3000), and answers `GET /health`. It re-reads `dist/server`
13 * so runtime inputs — notably the SSR `index.html` the entry reads via
14 * `join(__dirname, "./index.html")` — stay in the output. Container
15 * FrameworkSites extraFile that template to dest `"index.html"` next to
16 * the bundled `index.mjs` (not into `dist/`, or NodeServe would serve
17 * the unrendered shell at `GET /`). The finish pass also disables
18 * Octane's `isMainModule` auto-listen so rolldown flattening `entry.js`
19 * into `index.mjs` cannot bind `PORT` before the generated serve entry.
20 *
21 * - **`adapterName` / `adapterPackage`** — identify the optional legacy Node
22 * marker adapter, still accepted for existing projects.
23 * - **`serverEntryFileName`** — `entry.js`, Octane's emitted node entry.
24 * - **`bundle`** — Node resolve conditions (no `workerd`, no `@aws-sdk/`).
25 */
26 import * as Effect from "effect/Effect";
27 import * as FileSystem from "effect/FileSystem";
28 import * as Path from "effect/Path";
29 import { runBuildChild } from "../core/BuildChild.ts";
30 import {
31 DeployTargetError,
32 makeDeployTarget,
33 readServerModulesFromDisk,
34 sortServerModules,
35 } from "../core/index.ts";
36 import {
37 NODE_BUNDLE_CONDITIONS,
38 NODE_SERVE_ENTRY_FILE_NAME,
39 relativeClientDirExpression,
40 writeNodeServeEntry,
41 } from "../core/NodeServe.ts";
42 import { make, type OctaneTarget, type OctaneTargetConfig } from "./Octane.ts";
43
44 /** The `adapter.name` the Node marker adapter declares. */
45 export const ADAPTER_NAME = "node";
46
47 /** The optional legacy Node marker adapter module for existing configs. */
48 export const ADAPTER_PACKAGE = "@alchemy.run/frontend-frameworks/octane/node-adapter";
49
50 /** Octane's emitted node server entry within the server output directory. */
51 export const SERVER_ENTRY_FILE_NAME = "entry.js";
52
53 export interface OctaneNodeTargetConfig extends OctaneTargetConfig {}
54
55 const fail = (message: string, cause?: unknown) =>
56 new DeployTargetError({ platform: "node", message, cause });
57
58 /**
59 * Octane's node `entry.js` auto-listens when `import.meta.url` is the
60 * process entry. Container hosts rolldown that file into `index.mjs`,
61 * which would start a second HTTP server on `PORT` (EADDRINUSE) and
62 * crash. Replace the guard with `false` so only the generated serve
63 * entry binds the port.
64 */
65 const neutralizeAutoListen = (source: string): string =>
66 source
67 .replaceAll("fileURLToPath(import.meta.url) === resolve(process.argv[1])", "false")
68 .replaceAll("fileURLToPath(import.meta.url)===resolve(process.argv[1])", "false");
69
70 const makeNodeAdapterTarget = (config: OctaneNodeTargetConfig = {}): OctaneTarget =>
71 makeDeployTarget({
72 platform: "node",
73 config,
74 bundle: {
75 conditions: [...NODE_BUNDLE_CONDITIONS],
76 },
77 adapterName: ADAPTER_NAME,
78 adapterPackage: ADAPTER_PACKAGE,
79 serverEntryFileName: SERVER_ENTRY_FILE_NAME,
80 finish: (output, context) =>
81 Effect.gen(function* () {
82 const fs = yield* FileSystem.FileSystem;
83 const path = yield* Path.Path;
84 if (context.entry === undefined) {
85 return yield* fail("The Octane build produced no on-disk server entry to finish");
86 }
87 if (output.clientDirectory === undefined) {
88 return yield* fail(
89 "The Octane build produced no client directory for the Node serve entry",
90 );
91 }
92 const serverDir = path.dirname(context.entry);
93 const entrySource = yield* fs
94 .readFileString(context.entry)
95 .pipe(Effect.mapError((error) => fail("Failed to read dist/server/entry.js", error)));
96 const neutralized = neutralizeAutoListen(entrySource);
97 if (neutralized !== entrySource) {
98 yield* fs
99 .writeFileString(context.entry, neutralized)
100 .pipe(
101 Effect.mapError((error) =>
102 fail("Failed to disable Octane auto-listen in dist/server/entry.js", error),
103 ),
104 );
105 }
106 yield* fs
107 .writeFileString(path.join(serverDir, "package.json"), '{"type":"module"}\n')
108 .pipe(
109 Effect.mapError((error) => fail("Failed to write dist/server/package.json", error)),
110 );
111 const servePath = path.join(serverDir, NODE_SERVE_ENTRY_FILE_NAME);
112 const serveModuleName = path
113 .join("server", NODE_SERVE_ENTRY_FILE_NAME)
114 .replaceAll("\\", "/");
115 const withServe = yield* writeNodeServeEntry({
116 output,
117 servePath,
118 serveModuleName,
119 clientDirExpression: relativeClientDirExpression(servePath, output.clientDirectory),
120 handler: {
121 kind: "fetch",
122 imports: `import { handler } from ${JSON.stringify(`./${SERVER_ENTRY_FILE_NAME}`)};`,
123 expr: "handler",
124 },
125 platform: "node",
126 });
127 // Re-read so the SSR `index.html` the entry reads beside itself is
128 // part of the output (same as the AWS finishing pass).
129 const modules = yield* readServerModulesFromDisk({
130 directory: serverDir,
131 prefix: "server",
132 }).pipe(Effect.mapError((error) => fail(error.message, error.cause)));
133 return {
134 ...withServe,
135 serverModules: sortServerModules(modules, serveModuleName),
136 };
137 }),
138 });
139
140 export interface OctaneNodeBuildChildConfig {
141 readonly rootDir: string;
142 readonly config: OctaneNodeTargetConfig;
143 }
144
145 export const buildInChild = (config: OctaneNodeBuildChildConfig) =>
146 Effect.gen(function* () {
147 const framework = yield* make({
148 root: config.rootDir,
149 target: makeNodeAdapterTarget(config.config),
150 compatibilityDate: config.config.compatibilityDate,
151 compatibilityFlags: config.config.compatibilityFlags,
152 });
153 return yield* framework.build({ root: config.rootDir });
154 });
155
156 export const makeNodeTarget = (config: OctaneNodeTargetConfig = {}): OctaneTarget => ({
157 ...makeNodeAdapterTarget(config),
158 build: (context) =>
159 runBuildChild({
160 module: import.meta.url,
161 rootDir: context.root,
162 env: context.env,
163 framework: "octane",
164 config: {
165 rootDir: context.root,
166 config,
167 } satisfies OctaneNodeBuildChildConfig,
168 }).pipe(Effect.mapError((error) => fail(error.message, error.cause))),
169 });
170
171 export const target = makeNodeTarget;
172
173 export default makeNodeTarget;