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

main
ts 644 lines 27.1 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import { flociServices } from "@alchemy.run/aws/Local/FlociServices";
3 import { assert, describe, expect } from "@alchemy.run/test";
4 import * as Test from "@alchemy.run/test/Alchemy";
5 import * as cloudfront from "@distilled.cloud/aws/cloudfront";
6 import * as s3 from "@distilled.cloud/aws/s3";
7 import * as Output from "alchemy/Output";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as FileSystem from "effect/FileSystem";
11 import * as HttpClient from "effect/http/HttpClient";
12 import * as Path from "effect/Path";
13 import * as Redacted from "effect/Redacted";
14 import * as Schedule from "effect/Schedule";
15 import * as pathe from "pathe";
16 import { cloneFixture } from "../../Cloudflare/Utils/Fixture.ts";
17
18 // `dev: true` runs local providers behind the RPC sidecar proxy by default,
19 // matching the process topology of the real `alchemy dev` command.
20 //
21 // These cases need floci's emulated CloudFront edge, which arrives with the
22 // next `DEFAULT_FLOCI_IMAGE` pin bump. Until then, run them against a locally
23 // built emulator: `ALCHEMY_FLOCI_IMAGE=floci:cf-edge pnpm test …`.
24 const { test } = Test.make({ providers: AWS.providers(), dev: true });
25
26 const fixtureDir = pathe.resolve(import.meta.dirname, "fixtures", "staticsite-dev");
27 const viteFixtureDir = pathe.resolve(import.meta.dirname, "fixtures", "vite-app");
28 // Clone under the alchemy package so `vite` resolves from the workspace's
29 // hoisted node_modules (the fixture has no node_modules of its own).
30 const tempRoot = pathe.resolve(import.meta.dirname, "../../../.tmp");
31
32 const htmlPage = (marker: string) => `<!doctype html>
33 <html>
34 <head><title>${marker}</title></head>
35 <body><h1>${marker}</h1></body>
36 </html>
37 `;
38
39 /**
40 * Fetch the Router the way a developer does: open its URL.
41 *
42 * No Host header, no emulator endpoint, no TLS exception — `router.url` under
43 * `alchemy dev` is a plain `http://localhost:<port>` the emulated distribution
44 * is served on, so a browser (and this test) can just GET it. Needing anything
45 * else here would mean the dev URL is not really usable.
46 */
47 const fetchRouter = Effect.fn("fetchRouter")(function* (routerUrl: string, path: string) {
48 const client = yield* HttpClient.HttpClient;
49 return yield* client
50 .get(`${routerUrl}${path}`)
51 .pipe(Effect.retry({ schedule: Schedule.exponential("500 millis"), times: 6 }));
52 });
53
54 /**
55 * Build one Router-attached dev site: a cloned fixture whose long-lived dev
56 * server serves `site/<prefix>/index.html`, so the site behaves like a real
57 * static host mounted under the Router's path prefix.
58 */
59 const makeSiteFixture = Effect.fn("makeSiteFixture")(function* (prefix: string, marker: string) {
60 const fs = yield* FileSystem.FileSystem;
61 const path = yield* Path.Path;
62 const cwd = yield* cloneFixture(fixtureDir, {
63 prefix: `alchemy-aws-router-dev-${prefix}-`,
64 tempRoot,
65 entries: ["serve.mjs", "site"],
66 });
67 yield* fs.makeDirectory(path.join(cwd, "site", prefix), { recursive: true });
68 yield* fs.writeFileString(path.join(cwd, "site", prefix, "index.html"), htmlPage(marker));
69 return cwd;
70 });
71
72 /**
73 * What the Router answered with, when it isn't what the test expected.
74 *
75 * A typed failure (rather than an `expect` throw) so the assertion can be
76 * retried: the dev server behind the mount may still be warming up, and a
77 * live edit becomes visible one file-watcher tick after the write.
78 */
79 class RouterBodyMismatch extends Data.TaggedError("RouterBodyMismatch")<{
80 url: string;
81 status: number;
82 problem: string;
83 bodyExcerpt: string;
84 }> {}
85
86 /**
87 * GET `path` through the Router and assert what came back — status, markers
88 * that must be present, and markers that must NOT be (the negative half is
89 * what pins longest-prefix routing: a body is only proof if it could have
90 * come from the *wrong* origin and didn't).
91 */
92 const expectRouterBody = Effect.fn("expectRouterBody")(function* (
93 routerUrl: string,
94 path: string,
95 options: {
96 readonly includes?: ReadonlyArray<string>;
97 readonly excludes?: ReadonlyArray<string>;
98 readonly status?: number;
99 },
100 ) {
101 const client = yield* HttpClient.HttpClient;
102 const url = `${routerUrl}${path}`;
103 const status = options.status ?? 200;
104 return yield* Effect.gen(function* () {
105 const response = yield* client.get(url);
106 const body = yield* response.text;
107 const missing = (options.includes ?? []).filter((m) => !body.includes(m));
108 const present = (options.excludes ?? []).filter((m) => body.includes(m));
109 if (response.status !== status || missing.length > 0 || present.length > 0) {
110 return yield* Effect.fail(
111 new RouterBodyMismatch({
112 url,
113 status: response.status,
114 problem: [
115 response.status !== status ? `expected status ${status}` : undefined,
116 missing.length > 0 ? `missing ${missing.join(", ")}` : undefined,
117 present.length > 0 ? `unexpectedly present ${present.join(", ")}` : undefined,
118 ]
119 .filter(Boolean)
120 .join("; "),
121 bodyExcerpt: body.slice(0, 240),
122 }),
123 );
124 }
125 return body;
126 }).pipe(
127 Effect.retry({ schedule: Schedule.exponential("400 millis", 1.4), times: 8 }),
128 Effect.tapError((error) => Effect.logError(`expectRouterBody(${path}) failed`, error)),
129 );
130 });
131
132 /**
133 * Clone the plain-Vite fixture and stamp per-site markers into it, so a body
134 * served through the Router identifies WHICH dev server produced it.
135 *
136 * Returns the paths of the two files the live-edit assertions rewrite.
137 */
138 const makeViteFixture = Effect.fn("makeViteFixture")(function* (slug: string, marker: string) {
139 const fs = yield* FileSystem.FileSystem;
140 const path = yield* Path.Path;
141 const cwd = yield* cloneFixture(viteFixtureDir, {
142 prefix: `alchemy-aws-router-vite-${slug}-`,
143 tempRoot,
144 entries: [".gitignore", "package.json", "index.html", "src", "public"],
145 });
146 const indexPath = path.join(cwd, "index.html");
147 const mainPath = path.join(cwd, "src", "main.ts");
148 const index = yield* fs.readFileString(indexPath);
149 yield* fs.writeFileString(indexPath, index.replaceAll("VITE_AWS_PAGE_MARKER", `${marker}_PAGE`));
150 const main = yield* fs.readFileString(mainPath);
151 yield* fs.writeFileString(
152 mainPath,
153 main.replaceAll("VITE_AWS_MODULE_MARKER", `${marker}_MODULE`),
154 );
155 return { cwd, indexPath, mainPath };
156 });
157
158 describe("AWS.Website.Router local", { tags: ["provider:aws", "provider:aws:website"] }, () => {
159 test.provider(
160 "inline URL and bucket routes serve their own origins",
161 (stack) =>
162 Effect.gen(function* () {
163 yield* stack.destroy();
164
165 const cwd = yield* makeSiteFixture("api", "router-inline-url");
166 const deployed = yield* stack.deploy(
167 Effect.gen(function* () {
168 const origin = yield* AWS.Website.StaticSite("Origin", {
169 path: cwd,
170 dev: { command: "bun serve.mjs" },
171 });
172 const bucket = yield* AWS.S3.Bucket("Assets", {
173 forceDestroy: true,
174 });
175 const router = yield* AWS.Website.Router("InlineRouter", {
176 routes: {
177 // An Output url, as in the Router JSDoc (`api.functionUrl`).
178 // An `http://` url stays on http without an `origin` override.
179 "/api/*": { url: Output.interpolate`${origin.url}` },
180 "/assets/*": { bucket },
181 },
182 });
183 return { routerUrl: router.url, bucketName: bucket.bucketName };
184 }),
185 );
186
187 yield* s3
188 .putObject({
189 Bucket: deployed.bucketName,
190 Key: "assets/marker.txt",
191 Body: "router-inline-bucket",
192 ContentType: "text/plain",
193 })
194 .pipe(Effect.provide(flociServices()));
195
196 const routerUrl = deployed.routerUrl;
197 assert(typeof routerUrl === "string");
198 expect(routerUrl).toMatch(/^http:\/\/localhost:\d+$/);
199 yield* expectRouterBody(routerUrl, "/api/", {
200 includes: ["router-inline-url"],
201 excludes: ["router-inline-bucket"],
202 });
203 yield* expectRouterBody(routerUrl, "/assets/marker.txt", {
204 includes: ["router-inline-bucket"],
205 excludes: ["router-inline-url"],
206 });
207
208 yield* stack.destroy();
209 }),
210 { tags: ["local"], timeout: 120_000 },
211 );
212
213 /**
214 * The whole point of the local Router: two sites, one Router, real HTTP
215 * through the emulated CloudFront distribution, each path prefix reaching
216 * its own dev server. No CloudFront deploy — the distribution, its KV
217 * store, its viewer-request function and the routing all run in floci.
218 */
219 test.provider(
220 "two dev sites route through one emulated distribution",
221 (stack) =>
222 Effect.gen(function* () {
223 yield* stack.destroy();
224
225 const cwdA = yield* makeSiteFixture("site-a", "router-dev-site-a");
226 const cwdB = yield* makeSiteFixture("site-b", "router-dev-site-b");
227
228 const deployed = yield* stack.deploy(
229 Effect.gen(function* () {
230 const router = yield* AWS.Website.Router("DevRouter", {});
231 const siteA = yield* AWS.Website.StaticSite("SiteA", {
232 path: cwdA,
233 dev: { command: "bun serve.mjs", env: { DEV_MARKER: "site-a" } },
234 domain: { router, path: "/site-a" },
235 });
236 const siteB = yield* AWS.Website.StaticSite("SiteB", {
237 path: cwdB,
238 dev: { command: "bun serve.mjs", env: { DEV_MARKER: "site-b" } },
239 domain: { router, path: "/site-b" },
240 });
241 return {
242 routerUrl: router.url,
243 distributionId: router.distributionId,
244 kvNamespace: router.kvNamespace,
245 siteA: { url: siteA.url, kvNamespace: siteA.kvNamespace },
246 siteB: { url: siteB.url, kvNamespace: siteB.kvNamespace },
247 };
248 }),
249 );
250
251 const routerUrl = deployed.routerUrl as string;
252 // The Router is a real (emulated) CloudFront distribution — the same
253 // resource graph a deploy produces, not a dev-only substitute — served
254 // on a local port of its own, because `E….cloudfront.net` resolves to
255 // nothing on a developer's machine.
256 expect(routerUrl).toMatch(/^http:\/\/localhost:\d+$/);
257 // Each site kept its own dev server as its `url` (HMR is the point of
258 // dev) while still registering with the Router.
259 expect(deployed.siteA.url).toMatch(/^http:\/\/localhost:\d+/);
260 expect(deployed.siteB.url).toMatch(/^http:\/\/localhost:\d+/);
261 expect(deployed.siteA.url).not.toBe(deployed.siteB.url);
262 expect(deployed.siteA.kvNamespace).toBeDefined();
263 expect(deployed.siteB.kvNamespace).not.toBe(deployed.siteA.kvNamespace);
264
265 // ── Routing: each prefix reaches its own dev server ────────────────
266 const a = yield* fetchRouter(routerUrl, "/site-a/");
267 expect(a.status).toBe(200);
268 expect(yield* a.text).toContain("router-dev-site-a");
269
270 const b = yield* fetchRouter(routerUrl, "/site-b/");
271 expect(b.status).toBe(200);
272 expect(yield* b.text).toContain("router-dev-site-b");
273
274 // A mount is a path SEGMENT prefix, not a string prefix: `/site-a-x`
275 // shares seven characters with `/site-a` and must not be routed to it.
276 const neighbour = yield* fetchRouter(routerUrl, "/site-a-x");
277 expect(yield* neighbour.text).not.toContain("router-dev-site-a");
278
279 // ── The origin received the request CloudFront would have sent ─────
280 const echo = yield* fetchRouter(routerUrl, "/site-a/__echo");
281 expect(echo.status).toBe(200);
282 const echoed = (yield* echo.json) as {
283 marker: string;
284 path: string;
285 headers: Record<string, string>;
286 };
287 expect(echoed.marker).toBe("site-a");
288 expect(echoed.path).toBe("/site-a/__echo");
289 // `routeSite` sets x-forwarded-host to the viewer's Host before it
290 // rewrites the origin — the site's dev server sees the hostname the
291 // request arrived on, exactly as a deployed server origin would.
292 expect(echoed.headers["x-forwarded-host"]).toBe(new URL(routerUrl).host);
293
294 // ── Live edit: the dev server reads from disk per request, so the
295 // next edge request serves the new content without re-applying ─────
296 const fs = yield* FileSystem.FileSystem;
297 const path = yield* Path.Path;
298 yield* fs.writeFileString(
299 path.join(cwdA, "site", "site-a", "index.html"),
300 htmlPage("router-dev-site-a-v2"),
301 );
302 const edited = yield* fetchRouter(routerUrl, "/site-a/");
303 expect(yield* edited.text).toContain("router-dev-site-a-v2");
304
305 yield* stack.destroy();
306 }),
307 { tags: ["local"], timeout: 300_000 },
308 );
309
310 /**
311 * The framework path — the one a real `alchemy dev` user is on.
312 *
313 * A framework dev server is not a hand-written fixture: it binds where the
314 * framework decides (Vite picks `[::1]`), serves modules the HTML it
315 * generated points at, and rewrites those URLs by `base`. The emulated edge
316 * runs in a container and reaches the host through its gateway, so a
317 * loopback-only listener answers nothing and every request through the
318 * Router 502s.
319 *
320 * So this case is deliberately end-to-end through `router.url` only: the
321 * HTML shell, the module URLs that HTML actually references, and a live
322 * edit landing on a later request. Nothing here inspects the bind address
323 * (not portable) — the route working IS the proof.
324 */
325 test.provider(
326 "a Vite dev server serves its whole mount through the Router",
327 (stack) =>
328 Effect.gen(function* () {
329 const fs = yield* FileSystem.FileSystem;
330
331 yield* stack.destroy();
332
333 const root = yield* makeViteFixture("root", "ROUTER_VITE_ROOT");
334 const app = yield* makeViteFixture("app", "ROUTER_VITE_APP");
335
336 const deployed = yield* stack.deploy(
337 Effect.gen(function* () {
338 const router = yield* AWS.Website.Router("ViteRouter", {});
339 const rootSite = yield* AWS.Website.Vite("RootSite", {
340 rootDir: root.cwd,
341 domain: { router },
342 });
343 const appSite = yield* AWS.Website.Vite("AppSite", {
344 rootDir: app.cwd,
345 domain: { router, path: "/app" },
346 // The Router forwards the FULL uri to the origin — it never
347 // strips the mount prefix — so the dev server has to serve at
348 // the prefix. `vite.base` is what makes Vite do that, for both
349 // the module URLs it writes into the HTML and the requests it
350 // then has to answer. Passed as the deploy-time override bag
351 // (merged over the fixture's config file, which has none).
352 vite: { base: "/app/" },
353 });
354 return { routerUrl: router.url, rootUrl: rootSite.url, appUrl: appSite.url };
355 }),
356 );
357
358 const routerUrl = deployed.routerUrl as string;
359 expect(routerUrl).toMatch(/^http:\/\/localhost:\d+$/);
360 // Each site's own `url` is still its dev server (HMR is the point).
361 expect(deployed.rootUrl).toMatch(/^http:\/\/localhost:\d+/);
362 expect(deployed.appUrl).toMatch(/^http:\/\/localhost:\d+/);
363 expect(deployed.appUrl).not.toBe(deployed.rootUrl);
364
365 // ── The HTML shell at each mount, from its own dev server ──────────
366 const rootHtml = yield* expectRouterBody(routerUrl, "/", {
367 includes: ["ROUTER_VITE_ROOT_PAGE"],
368 excludes: ["ROUTER_VITE_APP_PAGE"],
369 });
370 const appHtml = yield* expectRouterBody(routerUrl, "/app/", {
371 includes: ["ROUTER_VITE_APP_PAGE"],
372 excludes: ["ROUTER_VITE_ROOT_PAGE"],
373 });
374
375 // Vite rewrote the asset URLs by `base`, so the browser's next hops
376 // are the prefixed ones. Assert that BEFORE fetching them — otherwise
377 // the fetches below could pass against URLs no real browser requests.
378 expect(appHtml).toContain('src="/app/src/main.ts"');
379 expect(appHtml).toContain("/app/@vite/client");
380 expect(rootHtml).toContain('src="/src/main.ts"');
381 expect(rootHtml).toContain("/@vite/client");
382
383 // ── The assets that HTML points at, through the Router ─────────────
384 // A mount only works if its sub-resources resolve; an index page that
385 // renders while its modules 404 is a broken site.
386 yield* expectRouterBody(routerUrl, "/app/src/main.ts", {
387 includes: ["ROUTER_VITE_APP_MODULE"],
388 excludes: ["ROUTER_VITE_ROOT_MODULE"],
389 });
390 yield* expectRouterBody(routerUrl, "/app/@vite/client", { includes: ["export"] });
391 yield* expectRouterBody(routerUrl, "/src/main.ts", {
392 includes: ["ROUTER_VITE_ROOT_MODULE"],
393 excludes: ["ROUTER_VITE_APP_MODULE"],
394 });
395 yield* expectRouterBody(routerUrl, "/@vite/client", { includes: ["export"] });
396
397 // ── Longest-prefix routing: neither mount answers the other's ──────
398 // The root site matches `/` and would happily serve `/app/...` if the
399 // longer prefix didn't win; the app site must not leak out of `/app`.
400 yield* expectRouterBody(routerUrl, "/app/src/main.ts", {
401 excludes: ["ROUTER_VITE_ROOT_MODULE"],
402 });
403 // `/app-other` shares a string prefix with `/app` but is NOT under the
404 // mount — it belongs to the root site (whose SPA fallback answers it).
405 yield* expectRouterBody(routerUrl, "/app-other", {
406 includes: ["ROUTER_VITE_ROOT_PAGE"],
407 excludes: ["ROUTER_VITE_APP_PAGE"],
408 });
409
410 // ── Live edit: the origin is a RUNNING dev server, not a copy ──────
411 // Nothing is re-applied; the next request through the edge has to
412 // show the new bytes. `?v=2` also defeats any cache in between.
413 const editedMain = (yield* fs.readFileString(app.mainPath)).replace(
414 "ROUTER_VITE_APP_MODULE",
415 "ROUTER_VITE_APP_MODULE_V2",
416 );
417 yield* fs.writeFileString(app.mainPath, editedMain);
418 yield* expectRouterBody(routerUrl, "/app/src/main.ts?v=2", {
419 includes: ["ROUTER_VITE_APP_MODULE_V2"],
420 });
421
422 const editedIndex = (yield* fs.readFileString(root.indexPath)).replace(
423 "ROUTER_VITE_ROOT_PAGE",
424 "ROUTER_VITE_ROOT_PAGE_V2",
425 );
426 yield* fs.writeFileString(root.indexPath, editedIndex);
427 yield* expectRouterBody(routerUrl, "/?v=2", { includes: ["ROUTER_VITE_ROOT_PAGE_V2"] });
428
429 yield* stack.destroy();
430 }),
431 // 300s like the sibling cases: fixture clone + `bun install` + vite dev
432 // boot through the emulated edge stack up under whole-suite concurrency
433 // (the test itself runs in ~6s in isolation).
434 { tags: ["local"], timeout: 300_000 },
435 );
436
437 /**
438 * The emulated runtime must be at least as restrictive as CloudFront's.
439 * CloudFront Functions are not Node: there is no `fetch`. Code that reaches
440 * for one has to fail locally, or `alchemy dev` becomes a way to ship
441 * broken edge code.
442 */
443 test.provider(
444 "edge code that reaches outside the CloudFront runtime fails locally",
445 (stack) =>
446 Effect.gen(function* () {
447 yield* stack.destroy();
448
449 const deployed = yield* stack.deploy(
450 Effect.gen(function* () {
451 const router = yield* AWS.Website.Router("SandboxRouter", {
452 edge: { viewerRequest: { injection: `await fetch("https://example.com/");` } },
453 });
454 return { routerUrl: router.url };
455 }),
456 );
457
458 const response = yield* fetchRouter(deployed.routerUrl as string, "/anything");
459 expect(response.status).toBe(502);
460 const body = yield* response.text;
461 expect(body).toContain("fetch is not defined");
462 expect(body).toContain("not Node.js");
463
464 yield* stack.destroy();
465 }),
466 { tags: ["local"], timeout: 180_000 },
467 );
468
469 /**
470 * `TestFunction` and the edge are backed by the same runtime, so the request
471 * object the API reports is the request the origin actually received. That
472 * is what makes a local result comparable to the same call against real AWS
473 * (which runs the function in AWS's own engine against the DEVELOPMENT
474 * stage — seconds, no distribution deploy).
475 */
476 test.provider(
477 "TestFunction agrees with the edge",
478 (stack) =>
479 Effect.gen(function* () {
480 yield* stack.destroy();
481
482 const cwd = yield* makeSiteFixture("docs", "router-parity-docs");
483
484 const deployed = yield* stack.deploy(
485 Effect.gen(function* () {
486 const router = yield* AWS.Website.Router("ParityRouter", {});
487 yield* AWS.Website.StaticSite("Docs", {
488 path: cwd,
489 dev: { command: "bun serve.mjs", env: { DEV_MARKER: "docs" } },
490 domain: { router, path: "/docs" },
491 });
492 return { routerUrl: router.url };
493 }),
494 );
495
496 const routerUrl = deployed.routerUrl as string;
497 const host = new URL(routerUrl).host;
498
499 // What the edge produced, as observed by the origin itself.
500 const echo = yield* fetchRouter(routerUrl, "/docs/__echo?q=1");
501 const echoed = (yield* echo.json) as { path: string; headers: Record<string, string> };
502
503 // The same event, through the TestFunction API. The out-of-band SDK
504 // calls are pinned to the emulator explicitly — the test process's
505 // own distilled clients otherwise point at the real account.
506 const result = yield* Effect.gen(function* () {
507 const functions = yield* cloudfront.listFunctions({});
508 const summary = functions.FunctionList?.Items?.find(
509 (item) => item.FunctionConfig.Comment === "ParityRouter viewer request",
510 );
511 expect(summary).toBeDefined();
512 const described = yield* cloudfront.describeFunction({
513 Name: summary!.Name,
514 Stage: "DEVELOPMENT",
515 });
516 return yield* cloudfront.testFunction({
517 Name: summary!.Name,
518 IfMatch: described.ETag!,
519 Stage: "DEVELOPMENT",
520 EventObject: new TextEncoder().encode(
521 JSON.stringify({
522 version: "1.0",
523 context: { eventType: "viewer-request" },
524 viewer: { ip: "127.0.0.1" },
525 request: {
526 method: "GET",
527 uri: "/docs/__echo",
528 querystring: { q: { value: "1" } },
529 headers: { host: { value: host } },
530 cookies: {},
531 },
532 }),
533 ),
534 });
535 }).pipe(Effect.provide(flociServices()));
536
537 expect(result.TestResult?.FunctionErrorMessage).toBeUndefined();
538 // `FunctionOutput` is modelled as a sensitive string, so it arrives
539 // wrapped — unwrap before parsing.
540 const rawOutput = result.TestResult?.FunctionOutput;
541 const output = JSON.parse(
542 rawOutput === undefined
543 ? "{}"
544 : typeof rawOutput === "string"
545 ? rawOutput
546 : Redacted.value(rawOutput),
547 ) as { request?: { uri: string; headers: Record<string, any> } };
548 expect(output.request?.uri).toBe(echoed.path);
549 expect(output.request?.headers["x-forwarded-host"]?.value).toBe(
550 echoed.headers["x-forwarded-host"],
551 );
552
553 yield* stack.destroy();
554 }),
555 { tags: ["provider:aws:cloudfront", "local"], timeout: 300_000 },
556 );
557
558 /**
559 * The oracle for everything above: run the same function through AWS's own
560 * engine and compare. `TestFunction` executes against the `DEVELOPMENT`
561 * stage, so this costs seconds and never touches a distribution.
562 *
563 * Needs real credentials (it is tagged `live`, so it runs in the live plan
564 * with `--profile testing`); opt out with `AWS_TEST_CLOUDFRONT_FUNCTION=0`.
565 */
566 test.provider.skipIf(process.env.AWS_TEST_CLOUDFRONT_FUNCTION === "0")(
567 "the emulated runtime agrees with the real CloudFront runtime",
568 () =>
569 Effect.gen(function* () {
570 const name = "alchemy-cf-runtime-parity";
571 const event = new TextEncoder().encode(
572 JSON.stringify({
573 version: "1.0",
574 context: { eventType: "viewer-request" },
575 viewer: { ip: "127.0.0.1" },
576 request: {
577 method: "GET",
578 uri: "/docs",
579 querystring: { q: { value: "1" } },
580 headers: { host: { value: "example.cloudfront.net" } },
581 cookies: {},
582 },
583 }),
584 );
585
586 /** Create, test, and delete a function against whichever endpoint is in scope. */
587 const runThere = Effect.fn("runThere")(function* (suffix: string, code: string) {
588 const created = yield* cloudfront.createFunction({
589 Name: `${name}-${suffix}`,
590 FunctionConfig: { Comment: "parity", Runtime: "cloudfront-js-2.0" },
591 FunctionCode: new TextEncoder().encode(code),
592 });
593 // Always delete the scratch function, even when the test call fails,
594 // so a failed run never leaves a function behind (or blocks a rerun
595 // with FunctionAlreadyExists).
596 const result = yield* cloudfront
597 .testFunction({
598 Name: `${name}-${suffix}`,
599 IfMatch: created.ETag!,
600 Stage: "DEVELOPMENT",
601 EventObject: event,
602 })
603 .pipe(
604 Effect.ensuring(
605 cloudfront
606 .deleteFunction({ Name: `${name}-${suffix}`, IfMatch: created.ETag! })
607 .pipe(Effect.ignore),
608 ),
609 );
610 const raw = result.TestResult?.FunctionOutput;
611 return {
612 error: result.TestResult?.FunctionErrorMessage,
613 output:
614 raw === undefined ? undefined : typeof raw === "string" ? raw : Redacted.value(raw),
615 };
616 });
617
618 // A well-behaved function: both engines must produce the same request.
619 const wellBehaved = `async function handler(event) {
620 event.request.headers["x-forwarded-host"] = event.request.headers.host;
621 event.request.uri = event.request.uri + "/index.html";
622 return event.request;
623 }`;
624 const local = yield* runThere("ok", wellBehaved).pipe(Effect.provide(flociServices()));
625 const real = yield* runThere("ok", wellBehaved);
626 expect(local.error).toBeUndefined();
627 expect(real.error).toBeUndefined();
628 expect(JSON.parse(local.output!)).toEqual(JSON.parse(real.output!));
629
630 // Reaching outside the runtime: both engines must report an error.
631 const escaping = `async function handler(event) {
632 await fetch("https://example.com/");
633 return event.request;
634 }`;
635 const localError = yield* runThere("escape", escaping).pipe(
636 Effect.provide(flociServices()),
637 );
638 const realError = yield* runThere("escape", escaping);
639 expect(localError.error).toBeDefined();
640 expect(realError.error).toBeDefined();
641 }),
642 { tags: ["provider:aws:cloudfront", "live"], timeout: 180_000 },
643 );
644 });