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

main
ts 252 lines 8.82 KB
Raw
1 import type { MemoOptions } from "alchemy/Command/Memo";
2 import type { InputProps } from "alchemy/Input";
3 import { effectClass } from "alchemy/Util/effect";
4 import * as Effect from "effect/Effect";
5 import type { Providers } from "../Providers.ts";
6 import type { AssetsConfig } from "../Workers/Assets.ts";
7 import {
8 Worker,
9 type NormalizedBindings,
10 type WorkerAssetsConfig,
11 type WorkerBindingProps,
12 type WorkerProps,
13 } from "../Workers/Worker.ts";
14
15 /**
16 * The specifier of the Octane source-provider module. The package must be
17 * installed in the user's project — `loadSource` fails with a
18 * `SourceProviderError` naming it otherwise.
19 */
20 const OCTANE_SOURCE_PROVIDER = "@alchemy.run/frontend-frameworks/octane/source";
21
22 export interface OctaneProps<Bindings extends WorkerBindingProps = {}> extends Omit<
23 WorkerProps<Bindings>,
24 "vite" | "main" | "assets" | "source" | "script" | "bundle" | "rules"
25 > {
26 /**
27 * Octane project root (the directory containing `vite.config.ts` and
28 * `octane.config.ts`). Relative paths resolve from the process working
29 * directory.
30 * @default process.cwd()
31 */
32 rootDir?: string;
33 /**
34 * Controls which files are content-hashed to decide whether a rebuild is
35 * needed. By default every non-gitignored file under `rootDir` (plus the
36 * nearest package-manager lockfile) is hashed; narrow the scope with
37 * `include`/`exclude` globs when the project sits in a large repository.
38 */
39 memo?: MemoOptions;
40 /**
41 * Optional configuration for static asset routing behavior.
42 * Supports `runWorkerFirst`, `htmlHandling`, `notFoundHandling`, etc.
43 *
44 * Octane's intended routing is asset-first with SSR on miss: exact files
45 * in `dist/client` serve without invoking the Worker, and every miss
46 * reaches Octane SSR. Leave `notFoundHandling` unset (`"none"`) — both
47 * `"single-page-application"` and `"404-page"` would prevent
48 * browser-navigation misses from reaching SSR.
49 */
50 assets?: AssetsConfig;
51 }
52
53 /**
54 * A Cloudflare Worker deployed from an [OctaneJS](https://octanejs.dev)
55 * fullstack project.
56 *
57 * Alchemy preserves Octane's native compiler and client build, builds the
58 * server for Workers, and generates the Worker entry. By default,
59 * `dist/server/worker.js` deploys as the Worker script and `dist/client`
60 * deploys as static assets; custom Octane `build.outDir` values are also
61 * supported. No hosting adapter, Wrangler configuration, or separate build
62 * command is required.
63 *
64 * Requires `@alchemy.run/frontend-frameworks` alongside `octane` and
65 * `@octanejs/vite-plugin` in your project. Keep the native `octane()` plugin,
66 * Tailwind, and other Vite plugins in `vite.config.ts`, and application
67 * routes and callbacks in `octane.config.ts`. These files load without
68 * being rewritten. Existing `adapter: cloudflare()` declarations from
69 * `@octanejs/adapter-cloudflare` remain supported but are optional; adapters
70 * for other hosting targets are rejected.
71 *
72 * Input files are content-hashed (respecting `.gitignore` by default) so
73 * unchanged projects skip the build and deploy entirely.
74 *
75 * Octane's server runtime needs synchronous SHA-256 and
76 * `AsyncLocalStorage`, so the `nodejs_compat` compatibility flag (enabled
77 * by default for every Worker) is required.
78 *
79 * A client-only Octane SPA (no `octane.config.ts` routes) is a plain Vite
80 * project — deploy it with {@link Vite | Cloudflare.Website.Vite} instead,
81 * where the `octane()` compiler plugin composes with the injected
82 * Cloudflare Vite plugin.
83 *
84 *
85 * ### Deploying an Octane App
86 * A single call builds and deploys the app — server-rendered routes,
87 * server (API) routes, and client assets included. Define the app's routes
88 * in `octane.config.ts`; `Cloudflare.Website.Octane` selects the Worker build:
89 *
90 * **Example:** octane.config.ts
91 * ```typescript
92 * import { defineConfig, RenderRoute } from "@octanejs/vite-plugin";
93 *
94 * export default defineConfig({
95 * router: {
96 * routes: [new RenderRoute({ path: "/", entry: ["App", "/src/App.tsx"] })],
97 * },
98 * });
99 * ```
100 *
101 * **Example:** alchemy.run.ts
102 * ```typescript
103 * const site = yield* Cloudflare.Website.Octane("Website");
104 * ```
105 *
106 * **Example:** Octane project in a subdirectory
107 * ```typescript
108 * const site = yield* Cloudflare.Website.Octane("Website", {
109 * rootDir: "apps/web",
110 * });
111 * ```
112 *
113 * ### Bindings
114 * Values passed via `env` reach Octane middleware and `ServerRoute`
115 * handlers through `context.platform`. The generated Worker entry supplies
116 * the Cloudflare `{ env, ctx }` pair, so `platform.env.MY_KV` is the live
117 * binding and `platform.ctx.waitUntil` schedules background work.
118 *
119 * **Example:** Reading a binding from a ServerRoute
120 * ```typescript
121 * // octane.config.ts route
122 * // new ServerRoute({
123 * // path: "/api/hello",
124 * // methods: ["GET"],
125 * // handler: (context) => {
126 * // const platform = context.platform as { env: { API_KEY: string } };
127 * // return Response.json({ hasKey: platform.env.API_KEY !== undefined });
128 * // },
129 * // })
130 *
131 * const site = yield* Cloudflare.Website.Octane("Website", {
132 * env: {
133 * API_KEY: Config.Redacted("API_KEY"),
134 * },
135 * });
136 * ```
137 *
138 * **Example:** Binding a KV namespace
139 * ```typescript
140 * const cache = yield* Cloudflare.KV.Namespace("Cache");
141 *
142 * const site = yield* Cloudflare.Website.Octane("Website", {
143 * env: {
144 * CACHE: cache,
145 * },
146 * });
147 * ```
148 *
149 * ### Dev
150 * `alchemy dev` runs Octane's own Vite dev server (the plugin's in-process
151 * SSR middleware — rendering, server routes, and RPC with full HMR).
152 * NOTE: Octane's dev middleware does not supply request-scoped platform
153 * bindings (`context.platform` is `undefined` in dev — an upstream
154 * limitation), so code touching `platform.env` must tolerate `undefined`
155 * during dev; bindings are live in deployed Workers.
156 *
157 * ### Custom Rebuild Scope
158 * By default, every non-gitignored file is hashed to decide whether a
159 * rebuild is needed. Use `memo` to narrow the scope when the project
160 * lives in a large repository.
161 *
162 * **Example:** Narrowing the memo scope
163 * ```typescript
164 * const site = yield* Cloudflare.Website.Octane("Website", {
165 * memo: {
166 * include: ["src/**", "public/**", "octane.config.ts", "vite.config.ts", "package.json"],
167 * },
168 * });
169 * ```
170 *
171 * ### Class Form
172 * Calling `Octane` with no arguments returns a constructor you can
173 * `extend` to declare the Worker as a named class. The class is both an
174 * `Effect` you can `yield*` to deploy and a type you can reference
175 * elsewhere — useful when other resources need to bind to this Worker.
176 *
177 * **Example:** Declaring a Worker class
178 * ```typescript
179 * class Website extends Cloudflare.Website.Octane<Website>()(
180 * "Website",
181 * ) {}
182 *
183 * const site = yield* Website;
184 * ```
185 *
186 * @resource
187 * @product Website
188 * @category Workers & Compute
189 */
190 export const Octane: {
191 <Self>(): {
192 <const Bindings extends WorkerBindingProps = {}, Req = never>(
193 id: string,
194 propsEff?:
195 | InputProps<OctaneProps<Bindings>>
196 | Effect.Effect<InputProps<OctaneProps<Bindings>>, never, Req>,
197 ): Effect.Effect<Self, never, Req | Providers> & {
198 new (): Worker<{
199 [binding in keyof NormalizedBindings<Bindings, WorkerAssetsConfig>]: NormalizedBindings<
200 Bindings,
201 WorkerAssetsConfig
202 >[binding];
203 }>;
204 };
205 };
206 <const Bindings extends WorkerBindingProps = {}, Req = never>(
207 id: string,
208 propsEff?:
209 | InputProps<OctaneProps<Bindings>>
210 | Effect.Effect<InputProps<OctaneProps<Bindings>>, never, Req>,
211 ): Effect.Effect<
212 Worker<{
213 [binding in keyof NormalizedBindings<Bindings, WorkerAssetsConfig>]: NormalizedBindings<
214 Bindings,
215 WorkerAssetsConfig
216 >[binding];
217 }>,
218 never,
219 Req | Providers
220 >;
221 } = (<const Bindings extends WorkerBindingProps = {}, Req = never>(
222 id?: string,
223 propsEff?:
224 | InputProps<OctaneProps<Bindings>>
225 | Effect.Effect<InputProps<OctaneProps<Bindings>>, never, Req>,
226 ) =>
227 id === undefined
228 ? <const Bindings extends WorkerBindingProps = {}, Req = never>(
229 id: string,
230 propsEff?:
231 | InputProps<OctaneProps<Bindings>>
232 | Effect.Effect<InputProps<OctaneProps<Bindings>>, never, Req>,
233 ) => effectClass(Octane(id, propsEff))
234 : Worker(
235 id,
236 Effect.map(Effect.isEffect(propsEff) ? propsEff : Effect.succeed(propsEff), (props) => ({
237 ...props,
238 // Octane's server bundle externalizes `node:` modules for
239 // workerd's native node-compat — `getCompatibility` already
240 // adds `nodejs_compat` to every non-python Worker.
241 main: undefined!,
242 source: {
243 provider: OCTANE_SOURCE_PROVIDER,
244 devMode: "server",
245 rootDir: props?.rootDir,
246 options: {
247 rootDir: props?.rootDir,
248 memo: props?.memo,
249 },
250 },
251 })),
252 )) as any;