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
| 1 | import { spawn } from "node:child_process"; |
| 2 | import { once } from "node:events"; |
| 3 | import * as fs from "node:fs/promises"; |
| 4 | import * as os from "node:os"; |
| 5 | import * as path from "node:path"; |
| 6 | import { pathToFileURL } from "node:url"; |
| 7 | import * as NodeServices from "@effect/platform-node/NodeServices"; |
| 8 | import * as Effect from "effect/Effect"; |
| 9 | import type * as FileSystem from "effect/FileSystem"; |
| 10 | import type * as Path from "effect/Path"; |
| 11 | import { afterEach, describe, expect, it } from "vitest"; |
| 12 | import { makeNeonServeEntrySource } from "../../core/NeonServe.ts"; |
| 13 | import { makeNodeServeEntrySource } from "../../core/NodeServe.ts"; |
| 14 | import { makeAwsTarget } from "../aws.ts"; |
| 15 | import { make, metadataReader, readFoldkitOutput, type BuildMetadata } from "../Foldkit.ts"; |
| 16 | import { target as makeNeonTarget } from "../neon.ts"; |
| 17 | import { makeNodeTarget } from "../node.ts"; |
| 18 | |
| 19 | const run = <A, E>(effect: Effect.Effect<A, E, FileSystem.FileSystem | Path.Path>) => |
| 20 | Effect.runPromise(effect.pipe(Effect.provide(NodeServices.layer))); |
| 21 | const roots: string[] = []; |
| 22 | afterEach(async () => { |
| 23 | await Promise.all(roots.splice(0).map((root) => fs.rm(root, { recursive: true, force: true }))); |
| 24 | }); |
| 25 | const fixture = async () => { |
| 26 | const root = await fs.mkdtemp(path.join(os.tmpdir(), "foldkit-target-")); |
| 27 | roots.push(root); |
| 28 | // Independent output directories and a nested entry exercise the metadata contract. |
| 29 | const clientDirectory = path.join(root, "public-output"); |
| 30 | const serverDirectory = path.join(root, "backend-output"); |
| 31 | const serverEntry = path.join(serverDirectory, "nested", "fetch.js"); |
| 32 | await fs.mkdir(path.join(clientDirectory, "about"), { recursive: true }); |
| 33 | await fs.mkdir(path.dirname(serverEntry), { recursive: true }); |
| 34 | await fs.writeFile(path.join(clientDirectory, "index.html"), "prerendered home"); |
| 35 | await fs.writeFile(path.join(clientDirectory, "about", "index.html"), "prerendered about"); |
| 36 | await fs.writeFile(path.join(clientDirectory, "asset.txt"), "asset"); |
| 37 | await fs.writeFile( |
| 38 | serverEntry, |
| 39 | `export default { async fetch(request) { |
| 40 | const url = new URL(request.url); |
| 41 | return new Response(request.method + ":" + url.pathname + url.search + ":" + await request.text(), { status: url.pathname.endsWith(".js") ? 404 : 200 }); |
| 42 | } };`, |
| 43 | ); |
| 44 | const metadata: BuildMetadata = { |
| 45 | root, |
| 46 | clientDirectory, |
| 47 | serverDirectory, |
| 48 | serverEntry, |
| 49 | manifest: { |
| 50 | schemaVersion: 1, |
| 51 | client: "public-output", |
| 52 | server: "backend-output", |
| 53 | serverEntry: "nested/fetch.js", |
| 54 | prerendered: ["/", "/about"], |
| 55 | }, |
| 56 | }; |
| 57 | return metadata; |
| 58 | }; |
| 59 | |
| 60 | const assertRouting = async ( |
| 61 | fetcher: (pathname: string, init?: RequestInit) => Promise<Response>, |
| 62 | base = "", |
| 63 | ) => { |
| 64 | const fetchAt = (pathname: string, init?: RequestInit) => fetcher(base + pathname, init); |
| 65 | expect(await (await fetchAt("/")).text()).toBe("prerendered home"); |
| 66 | expect(await (await fetchAt("/about?count=7")).text()).toBe("prerendered about"); |
| 67 | expect(await (await fetchAt("/dynamic?count=7")).text()).toBe( |
| 68 | "GET:" + base + "/dynamic?count=7:", |
| 69 | ); |
| 70 | expect(await (await fetchAt("/asset.txt")).text()).toBe("asset"); |
| 71 | expect((await fetchAt("/missing.js")).status).toBe(404); |
| 72 | expect(await (await fetchAt("/about", { method: "POST", body: "payload" })).text()).toBe( |
| 73 | "POST:" + base + "/about:payload", |
| 74 | ); |
| 75 | for (const pathname of ["/", "/about", "/dynamic"]) { |
| 76 | const response = await fetchAt(pathname, { method: "HEAD" }); |
| 77 | expect(response.status).toBe(200); |
| 78 | expect(await response.text()).toBe(""); |
| 79 | } |
| 80 | if (base) { |
| 81 | for (const pathname of ["/asset.txt", "/about", base + "lication/asset.txt"]) { |
| 82 | expect(await (await fetcher(pathname)).text()).toBe("GET:" + pathname + ":"); |
| 83 | } |
| 84 | } |
| 85 | }; |
| 86 | |
| 87 | describe("Foldkit deployment targets", () => { |
| 88 | it("packages only client/server artifacts with a portable, entry-first layout", async () => { |
| 89 | const metadata = await fixture(); |
| 90 | await fs.writeFile(path.join(metadata.root, ".env"), "PRIVATE=not-deployed"); |
| 91 | const { output, entry } = await run( |
| 92 | readFoldkitOutput(metadata.root, metadata.clientDirectory, metadata), |
| 93 | ); |
| 94 | expect(await fs.readdir(output.distDirectory!)).toEqual(["client", "server"]); |
| 95 | expect(output.serverModules?.[0]?.name).toBe("server/nested/fetch.js"); |
| 96 | expect(entry).toBe(path.join(output.distDirectory!, "server", "nested", "fetch.js")); |
| 97 | expect(await fs.readFile(path.join(output.clientDirectory!, "about/index.html"), "utf8")).toBe( |
| 98 | "prerendered about", |
| 99 | ); |
| 100 | const spa = await run(readFoldkitOutput(metadata.root, metadata.clientDirectory)); |
| 101 | expect(spa.output.serverModules).toBeUndefined(); |
| 102 | expect(await fs.readdir(spa.output.distDirectory!)).toEqual(["client"]); |
| 103 | }); |
| 104 | |
| 105 | it("rejects mismatched AWS topology and keeps static SSG assets only", async () => { |
| 106 | const metadata = await fixture(); |
| 107 | await expect( |
| 108 | run(readFoldkitOutput(metadata.root, metadata.clientDirectory, metadata, "spa")), |
| 109 | ).rejects.toThrow('Set output: "server"'); |
| 110 | await expect( |
| 111 | run(readFoldkitOutput(metadata.root, metadata.clientDirectory, undefined, "server")), |
| 112 | ).rejects.toThrow("no server handler"); |
| 113 | await expect( |
| 114 | run( |
| 115 | readFoldkitOutput( |
| 116 | metadata.root, |
| 117 | metadata.clientDirectory, |
| 118 | { ...metadata, manifest: { ...metadata.manifest, prerendered: [] } }, |
| 119 | "static", |
| 120 | ), |
| 121 | ), |
| 122 | ).rejects.toThrow("requires prerendered pages"); |
| 123 | const { output } = await run( |
| 124 | readFoldkitOutput(metadata.root, metadata.clientDirectory, metadata, "static"), |
| 125 | ); |
| 126 | expect(output.serverModules).toBeUndefined(); |
| 127 | expect(await fs.readdir(output.distDirectory!)).toEqual(["client"]); |
| 128 | expect( |
| 129 | await run( |
| 130 | makeAwsTarget().finish!(output, { |
| 131 | root: metadata.root, |
| 132 | framework: "foldkit", |
| 133 | }), |
| 134 | ), |
| 135 | ).toBe(output); |
| 136 | }); |
| 137 | |
| 138 | it.each([ |
| 139 | { base: "", ssr: true }, |
| 140 | { base: "/app", ssr: true }, |
| 141 | { base: "/app", ssr: false }, |
| 142 | ])( |
| 143 | "serves Node assets at $base (SSR: $ssr) without changing handler URLs", |
| 144 | async ({ base, ssr }) => { |
| 145 | const metadata = await fixture(); |
| 146 | const { output, entry } = await run( |
| 147 | readFoldkitOutput(metadata.root, metadata.clientDirectory, ssr ? metadata : undefined), |
| 148 | ); |
| 149 | const finished = await run( |
| 150 | makeNodeTarget().finish!(output, { |
| 151 | root: metadata.root, |
| 152 | framework: "foldkit", |
| 153 | entry, |
| 154 | assetBasePath: base + "/", |
| 155 | }), |
| 156 | ); |
| 157 | const servePath = path.join(finished.distDirectory!, finished.serverModules![0]!.name); |
| 158 | // Add only a readiness notification, leaving the generated request handling intact. |
| 159 | await fs.appendFile( |
| 160 | servePath, |
| 161 | '\nserver.on("listening", () => console.log(server.address().port));\n', |
| 162 | ); |
| 163 | const child = spawn(process.execPath, [servePath], { |
| 164 | env: { ...process.env, PORT: "0", HOST: "127.0.0.1" }, |
| 165 | stdio: ["ignore", "pipe", "pipe"], |
| 166 | }); |
| 167 | let errors = ""; |
| 168 | child.stderr.on("data", (chunk) => { |
| 169 | errors += String(chunk); |
| 170 | }); |
| 171 | try { |
| 172 | const port = await new Promise<number>((resolve, reject) => { |
| 173 | const timer = setTimeout( |
| 174 | () => reject(new Error("Node entry readiness timed out: " + errors)), |
| 175 | 5000, |
| 176 | ); |
| 177 | child.stdout.once("data", (chunk) => { |
| 178 | clearTimeout(timer); |
| 179 | resolve(Number(String(chunk).trim())); |
| 180 | }); |
| 181 | child.once("error", (error) => { |
| 182 | clearTimeout(timer); |
| 183 | reject(error); |
| 184 | }); |
| 185 | child.once("exit", (code) => { |
| 186 | clearTimeout(timer); |
| 187 | reject(new Error("Node entry exited: " + code + errors)); |
| 188 | }); |
| 189 | }); |
| 190 | const fetchAt = (pathname: string, init?: RequestInit) => |
| 191 | fetch(`http://127.0.0.1:${port}${pathname}`, init); |
| 192 | if (ssr) { |
| 193 | await assertRouting(fetchAt, base); |
| 194 | } else { |
| 195 | expect(await (await fetchAt(base + "/asset.txt")).text()).toBe("asset"); |
| 196 | expect(await (await fetchAt(base + "/deep/link")).text()).toBe("prerendered home"); |
| 197 | expect(await (await fetchAt(base + "/deep/link", { method: "HEAD" })).text()).toBe(""); |
| 198 | expect((await fetchAt(base + "/deep/link", { method: "POST" })).status).toBe(404); |
| 199 | expect((await fetchAt("/asset.txt")).status).toBe(404); |
| 200 | expect((await fetchAt("/deep/link")).status).toBe(404); |
| 201 | expect((await fetchAt(base + "lication/deep/link")).status).toBe(404); |
| 202 | } |
| 203 | } finally { |
| 204 | if (child.exitCode === null) { |
| 205 | const exited = once(child, "exit"); |
| 206 | child.kill(); |
| 207 | await exited; |
| 208 | } |
| 209 | } |
| 210 | }, |
| 211 | ); |
| 212 | |
| 213 | it.each(["", "/app"])("preserves routing at base %j in Neon's Fetch module", async (base) => { |
| 214 | const metadata = await fixture(); |
| 215 | const { output, entry } = await run( |
| 216 | readFoldkitOutput(metadata.root, metadata.clientDirectory, metadata), |
| 217 | ); |
| 218 | const finished = await run( |
| 219 | makeNeonTarget().finish!(output, { |
| 220 | root: metadata.root, |
| 221 | framework: "foldkit", |
| 222 | entry, |
| 223 | assetBasePath: base + "/", |
| 224 | }), |
| 225 | ); |
| 226 | const module = await import( |
| 227 | pathToFileURL(path.join(finished.distDirectory!, finished.serverModules![0]!.name)).href |
| 228 | ); |
| 229 | await assertRouting( |
| 230 | (pathname, init) => module.default.fetch(new Request("http://example.test" + pathname, init)), |
| 231 | base, |
| 232 | ); |
| 233 | }); |
| 234 | |
| 235 | it("preserves SPA fallback and explicit 404 overrides without a Foldkit handler", async () => { |
| 236 | for (const notFoundHandling of [undefined, "none"] as const) { |
| 237 | const metadata = await fixture(); |
| 238 | const { output } = await run(readFoldkitOutput(metadata.root, metadata.clientDirectory)); |
| 239 | const finished = await run( |
| 240 | makeNeonTarget({ notFoundHandling }).finish!(output, { |
| 241 | root: metadata.root, |
| 242 | framework: "foldkit", |
| 243 | }), |
| 244 | ); |
| 245 | const module = await import( |
| 246 | pathToFileURL(path.join(finished.distDirectory!, finished.serverModules![0]!.name)).href |
| 247 | ); |
| 248 | const response = await module.default.fetch(new Request("http://example.test/deep/link")); |
| 249 | expect(response.status).toBe(notFoundHandling ? 404 : 200); |
| 250 | if (!notFoundHandling) expect(await response.text()).toBe("prerendered home"); |
| 251 | } |
| 252 | }); |
| 253 | |
| 254 | it.each([undefined, "/override/"])( |
| 255 | "mounts SPA assets using the resolved Vite base (override %j)", |
| 256 | async (base) => { |
| 257 | const root = await fs.mkdtemp(path.join(os.tmpdir(), "foldkit-base-")); |
| 258 | roots.push(root); |
| 259 | await fs.writeFile(path.join(root, "package.json"), '{"type":"module"}'); |
| 260 | await fs.writeFile(path.join(root, "vite.config.js"), 'export default { base: "/app/" };'); |
| 261 | await fs.writeFile( |
| 262 | path.join(root, "index.html"), |
| 263 | '<html><body><script type="module" src="/entry.js"></script></body></html>', |
| 264 | ); |
| 265 | await fs.writeFile(path.join(root, "entry.js"), 'globalThis.assetMountExample = "mounted";'); |
| 266 | const target = { ...makeNeonTarget(), build: undefined }; |
| 267 | const output = await run( |
| 268 | Effect.gen(function* () { |
| 269 | const framework = yield* make({ root, target, vite: base ? { base } : undefined }); |
| 270 | return yield* framework.build({ root }); |
| 271 | }), |
| 272 | ); |
| 273 | expect(output.nodeServe?.assetBasePath).toBe(base ?? "/app/"); |
| 274 | const module = await import( |
| 275 | pathToFileURL(path.join(output.distDirectory!, output.serverModules![0]!.name)).href |
| 276 | ); |
| 277 | const fetchAt = (pathname: string) => |
| 278 | module.default.fetch(new Request("http://example.test" + pathname)) as Promise<Response>; |
| 279 | const mount = base ?? "/app/"; |
| 280 | const home = await (await fetchAt(mount)).text(); |
| 281 | expect(await (await fetchAt(mount + "deep/link")).text()).toBe(home); |
| 282 | const script = home.match(/src="([^"]+)"/)![1]!; |
| 283 | expect(script.startsWith(mount + "assets/")).toBe(true); |
| 284 | expect(await (await fetchAt(script)).text()).toContain("mounted"); |
| 285 | expect((await fetchAt("/deep/link")).status).toBe(404); |
| 286 | expect((await fetchAt(script.slice(mount.length - 1))).status).toBe(404); |
| 287 | }, |
| 288 | ); |
| 289 | |
| 290 | it("adapts Foldkit's nested fetch entry to a buffered Lambda handler", async () => { |
| 291 | const metadata = await fixture(); |
| 292 | const { output, entry } = await run( |
| 293 | readFoldkitOutput(metadata.root, metadata.clientDirectory, metadata), |
| 294 | ); |
| 295 | const finished = await run( |
| 296 | makeAwsTarget({ streaming: false }).finish!(output, { |
| 297 | root: metadata.root, |
| 298 | framework: "foldkit", |
| 299 | entry, |
| 300 | }), |
| 301 | ); |
| 302 | const module = await import( |
| 303 | pathToFileURL(path.join(finished.distDirectory!, finished.serverModules![0]!.name)).href |
| 304 | ); |
| 305 | const response = await module.handler({ |
| 306 | version: "2.0", |
| 307 | rawPath: "/dynamic", |
| 308 | rawQueryString: "count=7", |
| 309 | headers: { host: "example.test" }, |
| 310 | requestContext: { http: { method: "POST" } }, |
| 311 | body: "payload", |
| 312 | isBase64Encoded: false, |
| 313 | }); |
| 314 | expect(response.statusCode).toBe(200); |
| 315 | expect(response.body).toBe("POST:/dynamic?count=7:payload"); |
| 316 | }); |
| 317 | }); |
| 318 | |
| 319 | describe("Foldkit plugin metadata", () => { |
| 320 | it("reads only after completion and rejects absent APIs or unknown schema versions", async () => { |
| 321 | const data = await fixture(); |
| 322 | let complete = false; |
| 323 | const read = metadataReader([ |
| 324 | { |
| 325 | name: "foldkit:build", |
| 326 | api: { |
| 327 | getBuildMetadata() { |
| 328 | if (!complete) throw new Error("incomplete"); |
| 329 | return data; |
| 330 | }, |
| 331 | }, |
| 332 | }, |
| 333 | ]); |
| 334 | expect(() => read!()).toThrow("incomplete"); |
| 335 | complete = true; |
| 336 | expect(read!()).toEqual(data); |
| 337 | expect(metadataReader([])).toBeUndefined(); |
| 338 | expect(() => metadataReader([{ name: "foldkit:build" }])).toThrow("0.25.0"); |
| 339 | expect(() => |
| 340 | metadataReader([ |
| 341 | { |
| 342 | name: "foldkit:build", |
| 343 | api: { |
| 344 | getBuildMetadata: () => ({ |
| 345 | ...data, |
| 346 | manifest: { ...data.manifest, schemaVersion: 2 }, |
| 347 | }), |
| 348 | }, |
| 349 | }, |
| 350 | ])!(), |
| 351 | ).toThrow(); |
| 352 | }); |
| 353 | |
| 354 | it("leaves other frameworks' root-template bypass unchanged", () => { |
| 355 | const options = { |
| 356 | clientDirExpression: '"/client"', |
| 357 | handler: { kind: "fetch" as const, imports: "", expr: "handler" }, |
| 358 | }; |
| 359 | expect(makeNodeServeEntrySource(options)).toContain( |
| 360 | 'const isRoot = (urlPath === "/" || urlPath === "");', |
| 361 | ); |
| 362 | expect(makeNeonServeEntrySource(options)).toContain( |
| 363 | 'handle === undefined || staticPath !== "/"', |
| 364 | ); |
| 365 | expect(makeNodeServeEntrySource({ ...options, serveRootIndex: true })).toContain( |
| 366 | "const isRoot = false;", |
| 367 | ); |
| 368 | expect(makeNeonServeEntrySource({ ...options, serveRootIndex: true })).toContain( |
| 369 | "lookup(staticPath, true)", |
| 370 | ); |
| 371 | }); |
| 372 | }); |