@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 410 lines 15.1 KB
Raw
1 import * as NodeServices from "@effect/platform-node/NodeServices";
2 import * as Effect from "effect/Effect";
3 import * as FileSystem from "effect/FileSystem";
4 import * as Path from "effect/Path";
5 import type * as Scope from "effect/Scope";
6 import { describe, expect, it } from "vitest";
7 import {
8 generateLambdaEntry,
9 LAMBDA_ADAPTER_FILE_NAME,
10 LAMBDA_ENTRY_FILE_NAME,
11 makeAwsTarget,
12 SERVER_ENTRY_FILE_NAME,
13 } from "../aws.ts";
14 import { fromHarnessOptions } from "../index.ts";
15 import {
16 DEFAULT_BUILD_DIRECTORY,
17 DEFAULT_SERVER_BUILD_FILE,
18 DEFAULT_TARGET_SPECIFIER,
19 inlineClientBuildConfig,
20 inlineServerBuildConfig,
21 make,
22 REACT_ROUTER_SERVER_BUILD_ID,
23 readReactRouterOutput,
24 selectServerEntryName,
25 SERVER_ENTRY_ID,
26 serverEntryPlugin,
27 serverEntrySource,
28 type ReactRouterTarget,
29 } from "../ReactRouter.ts";
30
31 const runWithNode = <A, E>(
32 effect: Effect.Effect<A, E, FileSystem.FileSystem | Path.Path | Scope.Scope>,
33 ): Promise<A> =>
34 Effect.runPromise(
35 Effect.scoped(effect).pipe(Effect.provide(NodeServices.layer)) as Effect.Effect<A, E>,
36 );
37
38 describe("readReactRouterOutput", () => {
39 it("maps a build tree onto the BuildOutput contract, entry first", async () => {
40 const output = await runWithNode(
41 Effect.gen(function* () {
42 const fs = yield* FileSystem.FileSystem;
43 const path = yield* Path.Path;
44 const dir = yield* fs.makeTempDirectoryScoped({
45 prefix: "react-router-output-",
46 });
47 const serverDir = path.join(dir, "server");
48 const clientDir = path.join(dir, "client");
49 yield* fs.makeDirectory(path.join(serverDir, "assets"), {
50 recursive: true,
51 });
52 yield* fs.makeDirectory(clientDir, { recursive: true });
53 // alphabetically before index.js, to prove entry-first sorting
54 yield* fs.writeFileString(
55 path.join(serverDir, "assets", "chunk-abc.js"),
56 "export const a = 1;",
57 );
58 yield* fs.writeFileString(
59 path.join(serverDir, DEFAULT_SERVER_BUILD_FILE),
60 "export const entry = {};",
61 );
62 yield* fs.writeFileString(path.join(clientDir, "robots.txt"), "User-agent: *\n");
63 return yield* readReactRouterOutput({ dir, serverDir, clientDir });
64 }),
65 );
66 expect(output.serverModules?.map((module) => module.name)).toEqual([
67 "server/index.js",
68 "server/assets/chunk-abc.js",
69 ]);
70 expect(output.serverModules?.[0]?.hash).toMatch(/^[0-9a-f]{64}$/);
71 expect(output.clientDirectory?.endsWith("client")).toBe(true);
72 expect(output.distDirectory).toBeDefined();
73 expect(output.externalWorkspaces.size).toBe(0);
74 });
75
76 it("honors a serverBuildFile override", async () => {
77 const output = await runWithNode(
78 Effect.gen(function* () {
79 const fs = yield* FileSystem.FileSystem;
80 const path = yield* Path.Path;
81 const dir = yield* fs.makeTempDirectoryScoped({
82 prefix: "react-router-output-",
83 });
84 const serverDir = path.join(dir, "server");
85 yield* fs.makeDirectory(serverDir, { recursive: true });
86 yield* fs.writeFileString(path.join(serverDir, "app.js"), "export const entry = {};");
87 yield* fs.writeFileString(path.join(serverDir, "index.js"), "export const other = {};");
88 return yield* readReactRouterOutput({
89 dir,
90 serverDir,
91 clientDir: path.join(dir, "client"),
92 serverEntryFileName: "app.js",
93 });
94 }),
95 );
96 expect(output.serverModules?.[0]?.name).toBe("server/app.js");
97 });
98
99 it("falls back to the single top-level module when the entry is renamed", async () => {
100 const output = await runWithNode(
101 Effect.gen(function* () {
102 const fs = yield* FileSystem.FileSystem;
103 const path = yield* Path.Path;
104 const dir = yield* fs.makeTempDirectoryScoped({
105 prefix: "react-router-output-",
106 });
107 const serverDir = path.join(dir, "server");
108 yield* fs.makeDirectory(path.join(serverDir, "assets"), {
109 recursive: true,
110 });
111 yield* fs.writeFileString(
112 path.join(serverDir, "assets", "chunk-abc.js"),
113 "export const a = 1;",
114 );
115 yield* fs.writeFileString(path.join(serverDir, "server.js"), "export const entry = {};");
116 return yield* readReactRouterOutput({
117 dir,
118 serverDir,
119 clientDir: path.join(dir, "client"),
120 });
121 }),
122 );
123 expect(output.serverModules?.[0]?.name).toBe("server/server.js");
124 });
125
126 it("names RSC / multi-environment builds as the unsupported case", async () => {
127 const error = await runWithNode(
128 Effect.gen(function* () {
129 const fs = yield* FileSystem.FileSystem;
130 const path = yield* Path.Path;
131 const dir = yield* fs.makeTempDirectoryScoped({
132 prefix: "react-router-output-",
133 });
134 const serverDir = path.join(dir, "server");
135 yield* fs.makeDirectory(serverDir, { recursive: true });
136 yield* fs.writeFileString(path.join(serverDir, "rsc.js"), "export const a = 1;");
137 yield* fs.writeFileString(path.join(serverDir, "ssr.js"), "export const b = 1;");
138 return yield* readReactRouterOutput({
139 dir,
140 serverDir,
141 clientDir: path.join(dir, "client"),
142 }).pipe(Effect.flip);
143 }),
144 );
145 expect(error._tag).toBe("FrameworkError");
146 expect(error.message).toContain('no "server/index.js" entry');
147 expect(error.message).toContain("React Server Components");
148 });
149
150 it("fails when the build produced no server modules", async () => {
151 const error = await runWithNode(
152 Effect.gen(function* () {
153 const fs = yield* FileSystem.FileSystem;
154 const path = yield* Path.Path;
155 const dir = yield* fs.makeTempDirectoryScoped({
156 prefix: "react-router-output-",
157 });
158 const serverDir = path.join(dir, "server");
159 yield* fs.makeDirectory(serverDir, { recursive: true });
160 return yield* readReactRouterOutput({
161 dir,
162 serverDir,
163 clientDir: path.join(dir, "client"),
164 }).pipe(Effect.flip);
165 }),
166 );
167 expect(error.message).toContain("no server modules");
168 });
169 });
170
171 describe("selectServerEntryName", () => {
172 it("prefers the expected name over a lone sibling", () => {
173 expect(selectServerEntryName(["server/index.js", "server/other.js"], "server/index.js")).toBe(
174 "server/index.js",
175 );
176 });
177
178 it("ignores nested chunks when counting top-level modules", () => {
179 expect(
180 selectServerEntryName(
181 ["server/assets/a.js", "server/assets/b.js", "server/app.js"],
182 "server/index.js",
183 ),
184 ).toBe("server/app.js");
185 });
186
187 it("is undefined when the choice is ambiguous", () => {
188 expect(
189 selectServerEntryName(["server/a.js", "server/b.js"], "server/index.js"),
190 ).toBeUndefined();
191 });
192 });
193
194 describe("serverEntrySource", () => {
195 it("turns the ServerBuild manifest into a fetch handler", () => {
196 const source = serverEntrySource();
197 // React Router's server build is a manifest with no default export;
198 // `createRequestHandler` is what makes it callable.
199 expect(source).toContain(`import * as build from "${REACT_ROUTER_SERVER_BUILD_ID}"`);
200 expect(source).toContain('import { createRequestHandler } from "react-router"');
201 expect(source).toContain('createRequestHandler(build, "production")');
202 expect(source).toContain("export default {");
203 });
204
205 it("forwards the build mode", () => {
206 expect(serverEntrySource("development")).toContain(
207 'createRequestHandler(build, "development")',
208 );
209 });
210 });
211
212 describe("serverEntryPlugin", () => {
213 it("resolves and loads the virtual entry, and nothing else", () => {
214 const plugin = serverEntryPlugin();
215 expect(plugin.enforce).toBe("pre");
216 const resolved = plugin.resolveId!(SERVER_ENTRY_ID);
217 expect(resolved).toBe(`\0${SERVER_ENTRY_ID}`);
218 expect(plugin.resolveId!("react-router")).toBeUndefined();
219 expect(plugin.load!(resolved!)).toContain("createRequestHandler");
220 expect(plugin.load!(SERVER_ENTRY_ID)).toBeUndefined();
221 });
222 });
223
224 describe("inlineServerBuildConfig", () => {
225 it("selects the server environment and replaces its rollup input", () => {
226 const config = inlineServerBuildConfig("/app", []) as {
227 build: { ssr: boolean; rollupOptions: { input: string } };
228 ssr: { noExternal: boolean };
229 environments: { ssr: { resolve: { noExternal: boolean } } };
230 root: string;
231 };
232 // `build.ssr` is the flag React Router's plugin branches on; the input
233 // swap is honored verbatim by its server-environment resolver.
234 expect(config.build.ssr).toBe(true);
235 expect(config.build.rollupOptions.input).toBe(SERVER_ENTRY_ID);
236 // Vite externalizes node_modules from SSR bundles by default; a Lambda
237 // ships the server directory alone, so it must be self-contained.
238 expect(config.ssr.noExternal).toBe(true);
239 expect(config.environments.ssr.resolve.noExternal).toBe(true);
240 expect(config.root).toBe("/app");
241 });
242 });
243
244 describe("inlineClientBuildConfig", () => {
245 it("builds the client environment without SSR overrides", () => {
246 const config = inlineClientBuildConfig("/app", []) as {
247 root: string;
248 build?: unknown;
249 ssr?: unknown;
250 };
251 expect(config.root).toBe("/app");
252 expect(config.build).toBeUndefined();
253 expect(config.ssr).toBeUndefined();
254 });
255 });
256
257 describe("generateLambdaEntry", () => {
258 it("wraps the server entry's fetch handler for streaming by default", () => {
259 const source = generateLambdaEntry({
260 streaming: true,
261 serverEntryFileName: SERVER_ENTRY_FILE_NAME,
262 });
263 expect(source).toContain(`import * as serverEntry from "./index.js"`);
264 expect(source).toContain(`import { toLambdaHandler } from "./${LAMBDA_ADAPTER_FILE_NAME}"`);
265 expect(source).toContain("export const handler = toLambdaHandler(");
266 // A project entry may default-export the bare fetch function.
267 expect(source).toContain('typeof entry === "function"');
268 });
269
270 it("emits the buffered wrapper when streaming is disabled", () => {
271 const source = generateLambdaEntry({
272 streaming: false,
273 serverEntryFileName: "app.js",
274 });
275 expect(source).toContain("toBufferedLambdaHandler");
276 expect(source).not.toContain("toLambdaHandler(fetchHandler)");
277 expect(source).toContain(`from "./app.js"`);
278 });
279 });
280
281 describe("makeAwsTarget", () => {
282 it("declares the Lambda packaging seams", () => {
283 const target = makeAwsTarget();
284 expect(target.platform).toBe("aws");
285 expect(target.serverEntryFileName).toBe(DEFAULT_SERVER_BUILD_FILE);
286 expect(target.bundle?.conditions).toEqual(["node", "import", "module"]);
287 expect(target.bundle?.external).toEqual(["@aws-sdk/"]);
288 expect(typeof target.finish).toBe("function");
289 // The wholesale build hook runs the build in a disposable child process.
290 expect(typeof target.build).toBe("function");
291 });
292
293 it("carries the buildDirectory and streaming overrides on its config", () => {
294 const config = makeAwsTarget({
295 buildDirectory: "dist",
296 streaming: false,
297 }).config;
298 expect(config.buildDirectory).toBe("dist");
299 expect(config.streaming).toBe(false);
300 });
301 });
302
303 describe("finish", () => {
304 it("emits the Lambda entry, the ESM marker, and the adapter copy", async () => {
305 const output = await runWithNode(
306 Effect.gen(function* () {
307 const fs = yield* FileSystem.FileSystem;
308 const path = yield* Path.Path;
309 const dir = yield* fs.makeTempDirectoryScoped({
310 prefix: "react-router-finish-",
311 });
312 const serverDir = path.join(dir, "server");
313 yield* fs.makeDirectory(serverDir, { recursive: true });
314 yield* fs.writeFileString(
315 path.join(serverDir, SERVER_ENTRY_FILE_NAME),
316 "export default { fetch() {} };",
317 );
318 const target = makeAwsTarget();
319 return yield* target.finish!(
320 {
321 distDirectory: dir,
322 clientDirectory: path.join(dir, "client"),
323 serverModules: [],
324 externalWorkspaces: new Set<string>(),
325 },
326 {
327 root: dir,
328 framework: "react-router",
329 entry: path.join(serverDir, SERVER_ENTRY_FILE_NAME),
330 },
331 );
332 }),
333 );
334 const names = output.serverModules?.map((module) => module.name) ?? [];
335 // The Lambda entry sorts first — it becomes the deployed handler module.
336 expect(names[0]).toBe(`server/${LAMBDA_ENTRY_FILE_NAME}`);
337 expect(names).toContain("server/package.json");
338 expect(names).toContain(`server/${LAMBDA_ADAPTER_FILE_NAME}`);
339 // `lambda.mjs`, not `index.mjs`: the server build already owns index.js.
340 expect(names).toContain(`server/${SERVER_ENTRY_FILE_NAME}`);
341 const manifest = output.serverModules?.find((module) => module.name === "server/package.json");
342 expect(String(manifest?.content)).toContain('"type":"module"');
343 });
344
345 it("fails when the framework produced no on-disk entry", async () => {
346 const error = await runWithNode(
347 Effect.gen(function* () {
348 const target = makeAwsTarget();
349 return yield* target.finish!(
350 {
351 distDirectory: "/tmp",
352 clientDirectory: undefined,
353 serverModules: [],
354 externalWorkspaces: new Set<string>(),
355 },
356 { root: "/tmp", framework: "react-router" },
357 ).pipe(Effect.flip);
358 }),
359 );
360 expect(error._tag).toBe("DeployTargetError");
361 expect(error.message).toContain("no on-disk server entry");
362 });
363 });
364
365 describe("make", () => {
366 it("defaults to this package's AWS deploy target", () => {
367 expect(DEFAULT_TARGET_SPECIFIER).toBe("@alchemy.run/frontend-frameworks/react-router/aws");
368 expect(DEFAULT_BUILD_DIRECTORY).toBe("build");
369 });
370
371 it("build fails with a descriptive FrameworkError outside a Vite project", async () => {
372 // /tmp has no vite install: loading the project's Vite is the first step
373 // after the target resolves and must surface a FrameworkError.
374 const result = await runWithNode(
375 Effect.gen(function* () {
376 const framework = yield* make({
377 root: "/tmp/does-not-matter",
378 target: finishOnly(makeAwsTarget()),
379 });
380 return yield* Effect.result(framework.build({ root: "/tmp/does-not-matter" }));
381 }),
382 );
383 expect(result._tag).toBe("Failure");
384 if (result._tag === "Failure") {
385 expect(result.failure._tag).toBe("FrameworkError");
386 expect(result.failure.framework).toBe("react-router");
387 }
388 });
389
390 it("exposes the framework contract (build + dev)", async () => {
391 const framework = await runWithNode(make({ root: "/tmp/does-not-matter" }));
392 expect(typeof framework.build).toBe("function");
393 expect(typeof framework.dev).toBe("function");
394 });
395 });
396
397 describe("fromHarnessOptions", () => {
398 it("forwards the harness's buildDirectory override", () => {
399 expect(fromHarnessOptions({ reactRouter: { buildDirectory: "dist" } }).buildDirectory).toBe(
400 "dist",
401 );
402 expect(fromHarnessOptions({}).buildDirectory).toBeUndefined();
403 });
404 });
405
406 /** Drop the wholesale `build` hook so the in-process pipeline runs. */
407 const finishOnly = (target: ReactRouterTarget): ReactRouterTarget => {
408 const { build: _build, ...rest } = target;
409 return rest;
410 };