@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, 06:00 UTC

main
ts 3,139 lines 131 KB
Raw
1 import { pathToFileURL } from "node:url";
2 import * as Cloudflare from "@alchemy.run/cloudflare";
3 import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment";
4 import * as R2 from "@alchemy.run/cloudflare/R2";
5 import { describe, expect } from "@alchemy.run/test";
6 import * as Test from "@alchemy.run/test/Alchemy";
7 import * as workers from "@distilled.cloud/cloudflare/workers";
8 import * as wfp from "@distilled.cloud/cloudflare/workers_for_platforms";
9 import { adopt, OwnedBySomeoneElse } from "alchemy/AdoptPolicy";
10 import { AlchemyContext } from "alchemy/AlchemyContext";
11 import * as Command from "alchemy/Command";
12 import * as Drift from "alchemy/Drift";
13 import * as Output from "alchemy/Output";
14 import * as Provider from "alchemy/Provider";
15 import { Stack } from "alchemy/Stack";
16 import { State } from "alchemy/State";
17 import { isResourceState } from "alchemy/State/State";
18 import { initialCwd } from "alchemy/Util/Node";
19 import * as ConfigProvider from "effect/ConfigProvider";
20 import * as Effect from "effect/Effect";
21 import * as Fiber from "effect/Fiber";
22 import * as FileSystem from "effect/FileSystem";
23 import * as FetchHttpClient from "effect/http/FetchHttpClient";
24 import * as HttpClient from "effect/http/HttpClient";
25 import * as HttpClientResponse from "effect/http/HttpClientResponse";
26 import * as Layer from "effect/Layer";
27 import * as Path from "effect/Path";
28 import * as Redacted from "effect/Redacted";
29 import { MinimumLogLevel } from "effect/References";
30 import * as Schedule from "effect/Schedule";
31 import * as pathe from "pathe";
32 import { stageSuffix, testName } from "../../names.ts";
33 import { cloneFixture } from "../Utils/Fixture.ts";
34 import { expectUrlContains } from "../Utils/Http.ts";
35 import {
36 expectWorkerExists,
37 expectWorkersDevPreviews,
38 expectWorkersDevSubdomain,
39 findWorker,
40 getWorkerTags,
41 waitForWorkerToBeDeleted,
42 } from "../Utils/Worker.ts";
43 import type { Counter, Meter } from "./fixtures/do-counter-worker.ts";
44 import InitConfigWorker from "./fixtures/init-config-worker.ts";
45 import InternalWorker from "./fixtures/internal-worker.ts";
46 import OldCompatEffectWorker from "./fixtures/old-compat-effect-worker.ts";
47 import TerminalEffectWorker from "./fixtures/terminal-effect-worker.ts";
48
49 const { test } = Test.make({ providers: Cloudflare.providers() });
50 const { test: devTest } = Test.make({ providers: Cloudflare.providers(), dev: true });
51
52 // #1296: after precreate registers a Worker's Durable Object classes,
53 // reconcile's script-settings read can 404 "has no versions" under load, and
54 // migration planning then re-sends `new_sqlite_classes`, which Cloudflare
55 // rejects. The race isn't reproducible on demand, so this file-scoped
56 // provider stack forwards every call to the real API except the two
57 // settings reads after the precreated class is first observed.
58 const precreateRace = { hostPath: undefined as string | undefined, injected: 0 };
59 const settingsPath = /\/workers\/scripts\/[^/]+\/settings$/;
60 const precreateRaceFetch = async (
61 input: Parameters<typeof fetch>[0],
62 init?: Parameters<typeof fetch>[1],
63 ) => {
64 const request = input instanceof Request ? input : new Request(input, init);
65 const path = new URL(request.url).pathname;
66 if (request.method !== "GET" || !settingsPath.test(path)) {
67 return fetch(input, init);
68 }
69 // Only the Durable Object host's own settings reads race.
70 if (path === precreateRace.hostPath && precreateRace.injected < 2) {
71 precreateRace.injected++;
72 return new Response(
73 JSON.stringify({
74 success: false,
75 errors: [{ code: 10007, message: "Worker has no versions" }],
76 messages: [],
77 result: null,
78 }),
79 { status: 404, headers: { "content-type": "application/json" } },
80 );
81 }
82 const response = await fetch(input, init);
83 if (
84 precreateRace.hostPath === undefined &&
85 response.status === 200 &&
86 (await response.clone().text()).includes('"namespace_id"')
87 ) {
88 precreateRace.hostPath = path;
89 }
90 return response;
91 };
92 const { test: precreateRaceTest } = Test.make({
93 providers: Cloudflare.providers().pipe(
94 Layer.provideMerge(
95 Layer.fresh(FetchHttpClient.layer).pipe(
96 Layer.provide(
97 Layer.succeed(FetchHttpClient.Fetch, precreateRaceFetch as typeof globalThis.fetch),
98 ),
99 ),
100 ),
101 ),
102 });
103
104 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
105
106 const main = pathe.resolve(import.meta.dirname, "fixtures/worker.ts");
107 const doMain = pathe.resolve(import.meta.dirname, "fixtures/do-counter-worker.ts");
108
109 describe.concurrent(
110 "Cloudflare.Worker",
111 { tags: ["provider:cloudflare", "provider:cloudflare:worker"] },
112 () => {
113 test.provider(
114 "create, update, delete worker",
115 (stack) =>
116 Effect.gen(function* () {
117 const { accountId } = yield* yield* CloudflareEnvironment;
118 const s = yield* Stack;
119
120 yield* stack.destroy();
121
122 const worker = yield* stack.deploy(
123 Effect.gen(function* () {
124 yield* R2.Bucket("Bucket", { forceDestroy: true, storageClass: "Standard" });
125
126 const worker = yield* Cloudflare.Worker("TestWorker", {
127 main,
128 workersDev: true,
129 compatibility: { date: "2024-01-01" },
130 });
131
132 return worker;
133 }),
134 );
135
136 const actualWorker = yield* findWorker(worker.workerName, accountId);
137 expect(actualWorker?.scriptName).toEqual(worker.workerName);
138 expect(yield* getWorkerTags(worker.workerName, accountId)).toContain(
139 `alchemy:stack:${s.name}`,
140 );
141 expect(yield* getWorkerTags(worker.workerName, accountId)).toContain(
142 `alchemy:stage:${s.stage}`,
143 );
144 expect(yield* getWorkerTags(worker.workerName, accountId)).toContain(
145 "alchemy:id:TestWorker",
146 );
147
148 // The bundle that shipped is kept for inspection in the Worker's own
149 // directory under `.alchemy/bundles`, named after stack, stage, and FQN.
150 const fs = yield* FileSystem.FileSystem;
151 const { dotAlchemy } = yield* AlchemyContext;
152 const bundled = yield* fs.readDirectory(
153 pathe.join(dotAlchemy, "bundles", `${s.name}-${s.stage}-TestWorker`),
154 );
155 expect(bundled.some((file) => file.endsWith(".js"))).toBe(true);
156
157 // Verify the workers.dev subdomain is enabled on Cloudflare
158 // (rather than just trusting the resource's output attributes).
159 expect(worker.url).toBeDefined();
160 const initialSubdomain = yield* workers.getScriptSubdomain({
161 accountId,
162 scriptName: worker.workerName,
163 });
164 expect(initialSubdomain).toEqual({ enabled: true, previewsEnabled: true });
165
166 // Update the worker
167 const updatedWorker = yield* stack.deploy(
168 Effect.gen(function* () {
169 return yield* Cloudflare.Worker("TestWorker", {
170 main,
171 workersDev: true,
172 compatibility: { date: "2024-01-01" },
173 });
174 }),
175 );
176
177 const actualUpdatedWorker = yield* findWorker(updatedWorker.workerName, accountId);
178 expect(actualUpdatedWorker?.scriptName).toEqual(updatedWorker.workerName);
179 const actualUpdatedSubdomain = yield* workers.getScriptSubdomain({
180 accountId,
181 scriptName: updatedWorker.workerName,
182 });
183 expect(actualUpdatedSubdomain).toEqual({ enabled: true, previewsEnabled: true });
184
185 yield* stack.destroy();
186
187 yield* waitForWorkerToBeDeleted(worker.workerName, accountId);
188 }).pipe(logLevel),
189 { tags: ["provider:cloudflare:r2", "live"] },
190 );
191
192 test.provider(
193 "zero-traffic upload receipts do not cause drift or hide live changes",
194 (stack) =>
195 Effect.gen(function* () {
196 const { accountId } = yield* yield* CloudflareEnvironment;
197
198 yield* stack.destroy();
199
200 const program = (marker: string, traffic?: number) =>
201 Cloudflare.Worker("ReceiptWorker", {
202 script: `export default { fetch() { return new Response(${JSON.stringify(marker)}); } };`,
203 workersDev: false,
204 version: traffic === undefined ? undefined : { traffic },
205 });
206
207 // Establish a compatible live deployment before uploading the
208 // candidate; a greenfield gradual rollout takes 100% of traffic.
209 const stable = yield* stack.deploy(program("stable"));
210 const beforeUpload = yield* workers.listScriptDeployments({
211 accountId,
212 scriptName: stable.workerName,
213 });
214 expect(beforeUpload.deployments[0]).toBeDefined();
215
216 const candidate = yield* stack.deploy(program("candidate", 0));
217 expect(candidate.workerName).toEqual(stable.workerName);
218 expect(candidate.versionId).toBeDefined();
219 expect(candidate.deploymentId).toBeUndefined();
220 const uploaded = yield* workers.getScriptVersion({
221 accountId,
222 scriptName: candidate.workerName,
223 versionId: candidate.versionId!,
224 });
225 expect(uploaded.id).toEqual(candidate.versionId);
226
227 const detectDrift = () => Drift.detect(stack).pipe(Effect.provide(stack.state));
228 const unchanged = yield* detectDrift();
229 expect(unchanged.resources.ReceiptWorker?.action).toBe("unchanged");
230 expect(unchanged.resources.ReceiptWorker?.attr.versionId).toEqual(candidate.versionId);
231
232 const afterRead = yield* workers.listScriptDeployments({
233 accountId,
234 scriptName: candidate.workerName,
235 });
236 expect(afterRead.deployments[0]).toEqual(beforeUpload.deployments[0]);
237 expect(
238 afterRead.deployments[0]?.versions.some(
239 (version) => version.versionId === candidate.versionId,
240 ),
241 ).toBe(false);
242
243 // Change real script settings outside Alchemy. Keeping the upload
244 // receipt must not mask genuine drift in the live configuration.
245 yield* workers.createScriptSubdomain({
246 accountId,
247 scriptName: candidate.workerName,
248 enabled: true,
249 previewsEnabled: false,
250 });
251 const changed = yield* detectDrift();
252 expect(changed.resources.ReceiptWorker?.action).toBe("drifted");
253 expect(changed.resources.ReceiptWorker?.attr.versionId).toEqual(candidate.versionId);
254 expect(changed.resources.ReceiptWorker?.attr.url).toBeDefined();
255
256 yield* stack.destroy();
257 yield* waitForWorkerToBeDeleted(candidate.workerName, accountId);
258 }).pipe(logLevel),
259 { tags: ["live"], timeout: 120_000 },
260 );
261
262 test.provider(
263 "a full deploy reads back its deployment and does not drift",
264 (stack) =>
265 Effect.gen(function* () {
266 const { accountId } = yield* yield* CloudflareEnvironment;
267
268 yield* stack.destroy();
269
270 const worker = yield* stack.deploy(
271 Cloudflare.Worker("DeploymentWorker", {
272 script: `export default { fetch() { return new Response("ok"); } };`,
273 workersDev: false,
274 }),
275 );
276 const { deployments } = yield* workers.listScriptDeployments({
277 accountId,
278 scriptName: worker.workerName,
279 });
280 expect(worker.deploymentId).toEqual(deployments[0]?.id);
281
282 // `read` must return the recorded deployment, or every deployed
283 // Worker compares unequal to state and reads as drifted.
284 const detected = yield* Drift.detect(stack).pipe(Effect.provide(stack.state));
285 expect(detected.resources.DeploymentWorker?.action).toBe("unchanged");
286 expect(detected.resources.DeploymentWorker?.attr.deploymentId).toEqual(
287 worker.deploymentId,
288 );
289
290 yield* stack.destroy();
291 yield* waitForWorkerToBeDeleted(worker.workerName, accountId);
292 }).pipe(logLevel),
293 { tags: ["live"], timeout: 120_000 },
294 );
295
296 // #1827: drift repair rebuilds the bundle from the `main` stored in
297 // state. Deploy from one checkout with an absolute `main`
298 // (`import.meta.url`), delete that checkout, then repair drift from
299 // another checkout of the same code.
300 test.provider(
301 "drift repair rebuilds a Worker after the checkout that deployed it is gone",
302 (stack) =>
303 Effect.gen(function* () {
304 const { accountId } = yield* yield* CloudflareEnvironment;
305 const fs = yield* FileSystem.FileSystem;
306 // Real path: on macOS the temp dir is a symlink, and `cwd` is real.
307 const tempRoot = yield* fs.realPath(
308 yield* fs.makeTempDirectoryScoped({ prefix: "alchemy-moved-checkout-" }),
309 );
310 const writeCheckout = (dir: string) =>
311 Effect.gen(function* () {
312 yield* fs.makeDirectory(pathe.join(dir, "src"), { recursive: true });
313 yield* fs.writeFileString(
314 pathe.join(dir, "package.json"),
315 JSON.stringify({ name: "moved-checkout", private: true, type: "module" }),
316 );
317 yield* fs.writeFileString(
318 pathe.join(dir, "src", "worker.ts"),
319 `export default { fetch() { return new Response("moved-checkout"); } };\n`,
320 );
321 });
322 const checkoutA = pathe.join(tempRoot, "checkout-a");
323 const checkoutB = pathe.join(tempRoot, "checkout-b");
324 yield* writeCheckout(checkoutA);
325 const mainUrl = yield* Effect.sync(
326 () => pathToFileURL(pathe.join(checkoutA, "src", "worker.ts")).href,
327 );
328 const originalCwd = yield* Effect.sync(() => process.cwd());
329
330 yield* stack.destroy();
331
332 const workerName = yield* Effect.gen(function* () {
333 yield* Effect.sync(() => process.chdir(checkoutA));
334 const worker = yield* stack.deploy(
335 Cloudflare.Worker("MovedCheckoutWorker", { main: mainUrl, workersDev: true }),
336 );
337
338 // State keeps `main` relative to the deploying checkout.
339 const row = yield* Effect.gen(function* () {
340 const state = yield* yield* State;
341 return yield* state.get({
342 stack: stack.name,
343 stage: stack.stage,
344 fqn: "MovedCheckoutWorker",
345 });
346 }).pipe(Effect.provide(stack.state));
347 expect((row as { props?: { main?: unknown } } | undefined)?.props?.main).toEqual(
348 pathe.join("src", "worker.ts"),
349 );
350
351 // The deploying checkout is gone; another checkout repairs.
352 yield* writeCheckout(checkoutB);
353 yield* fs.remove(checkoutA, { recursive: true });
354 yield* Effect.sync(() => process.chdir(checkoutB));
355
356 yield* workers.createScriptSubdomain({
357 accountId,
358 scriptName: worker.workerName,
359 enabled: false,
360 previewsEnabled: false,
361 });
362 const repaired = yield* Drift.repair({ name: stack.name, stage: stack.stage }).pipe(
363 Effect.provide(stack.state),
364 );
365 expect(repaired.resources.MovedCheckoutWorker).toMatchObject({ action: "repaired" });
366 const subdomain = yield* workers.getScriptSubdomain({
367 accountId,
368 scriptName: worker.workerName,
369 });
370 expect(subdomain.enabled).toBe(true);
371 return worker.workerName;
372 }).pipe(Effect.ensuring(Effect.sync(() => process.chdir(originalCwd))));
373
374 yield* stack.destroy();
375 yield* waitForWorkerToBeDeleted(workerName, accountId);
376 }).pipe(Effect.scoped, logLevel),
377 // mutates process-global cwd
378 { tags: ["live"], timeout: 180_000, exclusive: true },
379 );
380
381 test.provider(
382 "create, update, delete worker with assets",
383 (stack) =>
384 Effect.gen(function* () {
385 const { accountId } = yield* yield* CloudflareEnvironment;
386 const s = yield* Stack;
387
388 yield* stack.destroy();
389
390 const worker = yield* stack.deploy(
391 Effect.gen(function* () {
392 return yield* Cloudflare.Worker("TestWorkerWithAssets", {
393 main,
394 assets: pathe.resolve(import.meta.dirname, "assets"),
395 workersDev: true,
396 compatibility: { date: "2024-01-01" },
397 });
398 }),
399 );
400
401 const actualWorker = yield* findWorker(worker.workerName, accountId);
402 expect(actualWorker?.scriptName).toEqual(worker.workerName);
403 expect(yield* getWorkerTags(worker.workerName, accountId)).toContain(
404 `alchemy:stack:${s.name}`,
405 );
406 expect(yield* getWorkerTags(worker.workerName, accountId)).toContain(
407 `alchemy:stage:${s.stage}`,
408 );
409 expect(yield* getWorkerTags(worker.workerName, accountId)).toContain(
410 "alchemy:id:TestWorkerWithAssets",
411 );
412
413 // Verify the worker has assets
414 expect(worker.hash?.assets).toBeDefined();
415
416 // Verify the workers.dev subdomain is enabled on Cloudflare
417 // (rather than just trusting the resource's output attributes).
418 expect(worker.url).toBeDefined();
419 const assetsWorkerSubdomain = yield* workers.getScriptSubdomain({
420 accountId,
421 scriptName: worker.workerName,
422 });
423 expect(assetsWorkerSubdomain).toEqual({ enabled: true, previewsEnabled: true });
424
425 // Update the worker
426 const updatedWorker = yield* stack.deploy(
427 Effect.gen(function* () {
428 return yield* Cloudflare.Worker("TestWorkerWithAssets", {
429 main,
430 assets: pathe.resolve(import.meta.dirname, "assets"),
431 workersDev: true,
432 compatibility: { date: "2024-01-01" },
433 });
434 }),
435 );
436
437 const actualUpdatedWorker = yield* findWorker(updatedWorker.workerName, accountId);
438 expect(actualUpdatedWorker?.scriptName).toEqual(updatedWorker.workerName);
439 expect(updatedWorker.hash?.assets).toBeDefined();
440
441 // Final update
442 const finalWorker = yield* stack.deploy(
443 Effect.gen(function* () {
444 return yield* Cloudflare.Worker("TestWorkerWithAssets", {
445 main,
446 workersDev: true,
447 assets: pathe.resolve(import.meta.dirname, "assets"),
448 compatibility: { date: "2024-01-01" },
449 });
450 }),
451 );
452
453 yield* stack.destroy();
454
455 yield* waitForWorkerToBeDeleted(finalWorker.workerName, accountId);
456 }).pipe(logLevel),
457 { tags: ["live"] },
458 );
459
460 // ─────────────────────────────────────────────────────────────────────
461 // Asset hashing & keepAssets behavior
462 //
463 // `hash.assets` is content-addressed: it must depend only on the bytes
464 // in the directory, not on where the directory lives. The provider
465 // uses that hash to decide whether to upload a fresh manifest or tell
466 // Cloudflare to keep the existing one (`keepAssets: true`). These
467 // tests pin down the user-visible contract:
468 //
469 // 1. Same bytes at a different path → same hash, no re-upload.
470 // 2. Different bytes (any change) → new hash, re-upload.
471 // 3. A worker-only change leaves the asset hash alone, so the
472 // script update goes out without re-walking the asset tree.
473 //
474 // The "moved path" cases also guard against the regression where state
475 // written by one machine (e.g. a CI runner) recorded an absolute path
476 // that the next machine couldn't open — the deploy used to crash with
477 // `NotFound: FileSystem.readDirectory`.
478 // ─────────────────────────────────────────────────────────────────────
479
480 const assetsFixtureDir = pathe.resolve(import.meta.dirname, "assets");
481
482 test.provider(
483 "Worker assets: relocating to a fresh path with identical bytes preserves hash and keeps assets",
484 (stack) =>
485 Effect.gen(function* () {
486 const { accountId } = yield* yield* CloudflareEnvironment;
487 const fs = yield* FileSystem.FileSystem;
488
489 yield* stack.destroy();
490
491 const dirA = yield* cloneFixture(assetsFixtureDir, {
492 prefix: "alchemy-worker-assets-a-",
493 });
494 const dirB = yield* cloneFixture(assetsFixtureDir, {
495 prefix: "alchemy-worker-assets-b-",
496 });
497
498 const deploy = (assetsDir: string) =>
499 stack.deploy(
500 Effect.gen(function* () {
501 return yield* Cloudflare.Worker("RelocatedAssets", {
502 main,
503 assets: assetsDir,
504 workersDev: true,
505 compatibility: { date: "2024-01-01" },
506 });
507 }),
508 );
509
510 const v1 = yield* deploy(dirA);
511 expect(v1.hash?.assets).toBeDefined();
512 yield* expectWorkerExists(v1.workerName, accountId);
513 yield* expectUrlContains(`${v1.url!}/index.html`, "Hello from Worker", {
514 timeout: "120 seconds",
515 label: "v1 served",
516 });
517
518 // Wipe dirA before the second deploy. If anything in the apply
519 // path still tries to read the previously-recorded directory,
520 // this is where we'd fail with NotFound.
521 yield* fs.remove(dirA, { recursive: true });
522
523 const v2 = yield* deploy(dirB);
524
525 // Identical bytes ⇒ identical asset hash ⇒ keepAssets path.
526 expect(v2.hash?.assets).toEqual(v1.hash?.assets);
527 // The script binding stayed live; the URL keeps serving.
528 yield* expectUrlContains(`${v2.url!}/index.html`, "Hello from Worker", {
529 timeout: "60 seconds",
530 label: "v2 served",
531 });
532
533 yield* stack.destroy();
534 yield* waitForWorkerToBeDeleted(v1.workerName, accountId);
535 }).pipe(logLevel),
536 { tags: ["live"], timeout: 360_000 },
537 );
538
539 test.provider(
540 "Worker assets: editing a file changes the hash and republishes the manifest",
541 (stack) =>
542 Effect.gen(function* () {
543 const { accountId } = yield* yield* CloudflareEnvironment;
544 const fs = yield* FileSystem.FileSystem;
545 const path = yield* Path.Path;
546
547 yield* stack.destroy();
548
549 const dir = yield* cloneFixture(assetsFixtureDir, {
550 prefix: "alchemy-worker-assets-edit-",
551 });
552 const indexPath = path.join(dir, "index.html");
553
554 const v1Marker = `worker-assets-v1-${Date.now()}`;
555 yield* fs.writeFileString(
556 indexPath,
557 `<!doctype html><title>${v1Marker}</title><body>${v1Marker}</body>`,
558 );
559
560 const deploy = () =>
561 stack.deploy(
562 Effect.gen(function* () {
563 return yield* Cloudflare.Worker("EditedAssets", {
564 main,
565 assets: dir,
566 workersDev: true,
567 compatibility: { date: "2024-01-01" },
568 });
569 }),
570 );
571
572 const v1 = yield* deploy();
573 expect(v1.hash?.assets).toBeDefined();
574 yield* expectUrlContains(`${v1.url!}/index.html`, v1Marker, {
575 timeout: "120 seconds",
576 label: "v1 marker",
577 });
578
579 const v2Marker = `worker-assets-v2-${Date.now()}`;
580 yield* fs.writeFileString(
581 indexPath,
582 `<!doctype html><title>${v2Marker}</title><body>${v2Marker}</body>`,
583 );
584
585 const v2 = yield* deploy();
586 expect(v2.hash?.assets).toBeDefined();
587 expect(v2.hash?.assets).not.toEqual(v1.hash?.assets);
588 yield* expectUrlContains(`${v2.url!}/index.html`, v2Marker, {
589 timeout: "60 seconds",
590 label: "v2 marker",
591 });
592
593 yield* stack.destroy();
594 yield* waitForWorkerToBeDeleted(v1.workerName, accountId);
595 }).pipe(logLevel),
596 { tags: ["live"], timeout: 360_000 },
597 );
598
599 test.provider(
600 "Worker assets: a bundle-only change keeps the asset manifest (hash.assets stable)",
601 (stack) =>
602 Effect.gen(function* () {
603 const { accountId } = yield* yield* CloudflareEnvironment;
604 const fs = yield* FileSystem.FileSystem;
605 const path = yield* Path.Path;
606
607 yield* stack.destroy();
608
609 const dir = yield* cloneFixture(assetsFixtureDir, {
610 prefix: "alchemy-worker-assets-bundle-only-",
611 });
612 // Write the worker entry into a fresh temp dir so we can edit
613 // it between deploys to force a bundle hash change without
614 // touching the assets directory.
615 const workerDir = yield* fs.makeTempDirectory({
616 prefix: "alchemy-worker-assets-bundle-only-entry-",
617 });
618 const workerPath = path.join(workerDir, "worker.ts");
619 const writeWorker = (marker: string) =>
620 fs.writeFileString(
621 workerPath,
622 `export default {
623 fetch: async () => new Response(${JSON.stringify(`Hello from BundleOnly: ${marker}`)}),
624 };
625 `,
626 );
627
628 const deploy = () =>
629 stack.deploy(
630 Effect.gen(function* () {
631 return yield* Cloudflare.Worker("BundleOnlyChange", {
632 main: workerPath,
633 assets: dir,
634 workersDev: true,
635 compatibility: { date: "2024-01-01" },
636 });
637 }),
638 );
639
640 yield* writeWorker("v1");
641 const v1 = yield* deploy();
642 expect(v1.hash?.assets).toBeDefined();
643 expect(v1.hash?.bundle).toBeDefined();
644
645 yield* writeWorker("v2");
646 const v2 = yield* deploy();
647 // Bundle changed (worker source edited) → hash.bundle moves.
648 // Assets are byte-identical → hash.assets must not move, and
649 // the keepAssets branch must keep the manifest live.
650 expect(v2.hash?.bundle).not.toEqual(v1.hash?.bundle);
651 expect(v2.hash?.assets).toEqual(v1.hash?.assets);
652 yield* expectUrlContains(`${v2.url!}/index.html`, "Hello from Worker", {
653 timeout: "60 seconds",
654 label: "assets still served after bundle-only change",
655 });
656
657 yield* stack.destroy();
658 yield* waitForWorkerToBeDeleted(v1.workerName, accountId);
659 }).pipe(logLevel),
660 { tags: ["live"], timeout: 360_000 },
661 );
662
663 test.provider(
664 "create, update, delete internal worker",
665 (stack) =>
666 Effect.gen(function* () {
667 const { accountId } = yield* yield* CloudflareEnvironment;
668 const s = yield* Stack;
669
670 yield* stack.destroy();
671
672 const worker = yield* stack.deploy(
673 Effect.gen(function* () {
674 return yield* InternalWorker;
675 }),
676 );
677
678 const actualWorker = yield* findWorker(worker.workerName, accountId);
679 expect(actualWorker?.scriptName).toEqual(worker.workerName);
680 expect(yield* getWorkerTags(worker.workerName, accountId)).toContain(
681 `alchemy:stack:${s.name}`,
682 );
683 expect(yield* getWorkerTags(worker.workerName, accountId)).toContain(
684 `alchemy:stage:${s.stage}`,
685 );
686 expect(yield* getWorkerTags(worker.workerName, accountId)).toContain(
687 "alchemy:id:InternalWorker",
688 );
689
690 const updatedWorker = yield* stack.deploy(
691 Effect.gen(function* () {
692 return yield* InternalWorker;
693 }),
694 );
695
696 expect(updatedWorker.workerName).toEqual(worker.workerName);
697
698 yield* stack.destroy();
699
700 yield* waitForWorkerToBeDeleted(worker.workerName, accountId);
701 }).pipe(logLevel),
702 { tags: ["live"] },
703 );
704
705 // ── Engine-level adoption ─────────────────────────────────────────────────
706 //
707 // The engine always calls `provider.read` when there is no prior state, and
708 // routes on the returned shape:
709 //
710 // - undefined → resource doesn't exist, drive a normal create
711 // - plain attrs → resource exists and is owned by us (Worker
712 // determines this from `alchemy:*` tags); silent
713 // adoption regardless of `--adopt`
714 // - `Unowned(attrs)` → resource exists but the tags don't identify us;
715 // the engine fails with `OwnedBySomeoneElse` unless
716 // the user opted in via `adopt(true)` / `--adopt`,
717 // in which case it's a silent takeover.
718 //
719 // The tests below use `test.provider`'s scratch state so we can wipe state
720 // mid-test while leaving the actual Cloudflare Worker in place — simulating
721 // "the user created/deployed this worker before, but this state store has
722 // never seen it" (e.g. CLI-driven first deploy on a fresh machine, or a
723 // state-store reset).
724
725 test.provider(
726 "refuses a foreign replacement without changing either Worker",
727 (stack) =>
728 Effect.gen(function* () {
729 const { accountId } = yield* yield* CloudflareEnvironment;
730 yield* stack.destroy();
731 const initial = yield* stack.deploy(
732 Effect.gen(function* () {
733 const owner = yield* Cloudflare.Worker("ReplacementOwner", {
734 main,
735 workersDev: false,
736 });
737 const replacement = yield* Cloudflare.Worker("ReplacementTarget", {
738 main,
739 workersDev: false,
740 });
741 return { owner, replacement };
742 }),
743 );
744 const snapshot = Effect.all(
745 [initial.owner, initial.replacement].map((worker) =>
746 Effect.all({
747 settings: workers.getScriptScriptAndVersionSetting({
748 accountId,
749 scriptName: worker.workerName,
750 }),
751 deployments: workers.listScriptDeployments({
752 accountId,
753 scriptName: worker.workerName,
754 }),
755 }),
756 ),
757 );
758 const before = yield* snapshot;
759 const refused = yield* stack
760 .deploy(
761 Effect.gen(function* () {
762 yield* Cloudflare.Worker("ReplacementOwner", { main, workersDev: false });
763 return yield* Cloudflare.Worker("ReplacementTarget", {
764 main,
765 workersDev: false,
766 name: initial.owner.workerName,
767 });
768 }),
769 )
770 .pipe(Effect.flip);
771 expect(refused._tag).toEqual("OwnedBySomeoneElse");
772 const after = yield* snapshot;
773 expect(after).toEqual(before);
774 // Destroy deletes ReplacementTarget's original generation and never
775 // touches ReplacementOwner's script through the refused replacement.
776 yield* stack.destroy();
777 yield* Effect.all(
778 [initial.owner, initial.replacement].map((worker) =>
779 waitForWorkerToBeDeleted(worker.workerName, accountId),
780 ),
781 );
782 }).pipe(logLevel),
783 { tags: ["live"], timeout: 120000 },
784 );
785
786 test.provider(
787 "owned worker (matching alchemy tags) is silently adopted without --adopt",
788 (stack) =>
789 Effect.gen(function* () {
790 const { accountId } = yield* yield* CloudflareEnvironment;
791
792 yield* stack.destroy();
793
794 // Phase 1: deploy normally so a real Worker exists on Cloudflare,
795 // tagged with this stack/stage/id. No explicit `name` — the engine
796 // generates a random-suffixed physical name (collision-free across
797 // concurrent runs, and alchemy-tagged so a crashed run's leftover is
798 // sweepable). The deploy output hands back the real name, which
799 // pins the worker's identity for the adoption phase below.
800 const initial = yield* stack.deploy(
801 Effect.gen(function* () {
802 return yield* Cloudflare.Worker("AdoptableWorker", {
803 main,
804 workersDev: true,
805 compatibility: { date: "2024-01-01" },
806 });
807 }),
808 );
809 const physicalName = initial.workerName;
810 expect(yield* findWorker(physicalName, accountId)).toBeDefined();
811
812 // Phase 2: wipe local state for this resource — the worker stays on
813 // Cloudflare. From the next deploy's perspective this looks like a
814 // fresh state store that has never seen this resource.
815 yield* Effect.gen(function* () {
816 const state = yield* yield* State;
817 yield* state.delete({ stack: stack.name, stage: stack.stage, fqn: "AdoptableWorker" });
818 }).pipe(Effect.provide(stack.state));
819
820 // Phase 3: redeploy *without* `adopt(true)`. The engine calls
821 // `provider.read`, the Worker's read sees its own alchemy tags and
822 // returns plain (owned) attrs, and the engine silently adopts.
823 // No `--adopt` flag is required.
824 const adopted = yield* stack.deploy(
825 Effect.gen(function* () {
826 return yield* Cloudflare.Worker("AdoptableWorker", {
827 main,
828 name: physicalName,
829 workersDev: true,
830 compatibility: { date: "2024-01-01" },
831 });
832 }),
833 );
834
835 expect(adopted.workerName).toEqual(physicalName);
836
837 const persisted = yield* Effect.gen(function* () {
838 const state = yield* yield* State;
839 return yield* state.get({
840 stack: stack.name,
841 stage: stack.stage,
842 fqn: "AdoptableWorker",
843 });
844 }).pipe(Effect.provide(stack.state));
845
846 expect(persisted?.status).toBeDefined();
847 expect((persisted as any)?.attr).toMatchObject({ workerName: physicalName });
848
849 yield* stack.destroy();
850 yield* waitForWorkerToBeDeleted(physicalName, accountId);
851 }).pipe(logLevel),
852 { tags: ["live"] },
853 );
854
855 test.provider(
856 "adopt(true) takes over a foreign-tagged worker",
857 (stack) =>
858 Effect.gen(function* () {
859 const { accountId } = yield* yield* CloudflareEnvironment;
860
861 yield* stack.destroy();
862
863 // Phase 1: deploy under logical id "Original". The Cloudflare Worker
864 // is now tagged `alchemy:id:Original` — i.e. owned by *that* logical
865 // resource. No explicit `name` — the engine generates a random-suffixed
866 // physical name (collision-free across runs); the deploy output hands
867 // back the real name, which phase 2 reuses to target the same worker.
868 const original = yield* stack.deploy(
869 Effect.gen(function* () {
870 return yield* Cloudflare.Worker("Original", {
871 main,
872 workersDev: true,
873 compatibility: { date: "2024-01-01" },
874 });
875 }),
876 );
877 const physicalName = original.workerName;
878 expect(yield* findWorker(original.workerName, accountId)).toBeDefined();
879 expect(yield* getWorkerTags(physicalName, accountId)).toContain("alchemy:id:Original");
880
881 // Wipe state for the "Original" entry; the worker stays on Cloudflare.
882 yield* Effect.gen(function* () {
883 const state = yield* yield* State;
884 yield* state.delete({ stack: stack.name, stage: stack.stage, fqn: "Original" });
885 }).pipe(Effect.provide(stack.state));
886
887 // Phase 2: redeploy under a *different* logical id with the same
888 // physical name and `adopt(true)`. `Worker.read` returns
889 // `Unowned(attrs)` because the existing tags identify a different
890 // logical id; with adopt enabled the engine takes over and the
891 // follow-up create/update rewrites the tags. (The rejection path
892 // — same scenario without `adopt(true)` — is covered by the unit
893 // tests in `plan.test.ts`.)
894 const takenOver = yield* stack
895 .deploy(
896 Effect.gen(function* () {
897 return yield* Cloudflare.Worker("Different", {
898 main,
899 name: physicalName,
900 workersDev: true,
901 compatibility: { date: "2024-01-01" },
902 });
903 }),
904 )
905 .pipe(adopt(true));
906
907 expect(takenOver.workerName).toEqual(physicalName);
908
909 const newTags = yield* getWorkerTags(physicalName, accountId);
910 expect(newTags).toContain("alchemy:id:Different");
911 expect(newTags).not.toContain("alchemy:id:Original");
912
913 yield* stack.destroy();
914 yield* waitForWorkerToBeDeleted(physicalName, accountId);
915 }).pipe(logLevel),
916 { tags: ["live"] },
917 );
918
919 // #1299: a binding to a resource created in the same deploy leaves the
920 // Worker's props unresolved at plan time. The ownership check must still
921 // run (at apply time, once props resolve) and refuse the foreign worker.
922 test.provider(
923 "refuses a foreign worker when its bindings are unresolved at plan time",
924 (stack) =>
925 Effect.gen(function* () {
926 const { accountId } = yield* yield* CloudflareEnvironment;
927
928 yield* stack.destroy();
929
930 const original = yield* stack.deploy(
931 Cloudflare.Worker("UnresolvedOriginal", {
932 main,
933 workersDev: false,
934 compatibility: { date: "2024-01-01" },
935 }),
936 );
937 const physicalName = original.workerName;
938
939 yield* Effect.gen(function* () {
940 const state = yield* yield* State;
941 yield* state.delete({
942 stack: stack.name,
943 stage: stack.stage,
944 fqn: "UnresolvedOriginal",
945 });
946 }).pipe(Effect.provide(stack.state));
947
948 const refused = yield* stack
949 .deploy(
950 Effect.gen(function* () {
951 const kv = yield* Cloudflare.KV.Namespace("UnresolvedKv");
952 return yield* Cloudflare.Worker("UnresolvedDifferent", {
953 main,
954 name: physicalName,
955 workersDev: false,
956 compatibility: { date: "2024-01-01" },
957 env: { KV: kv },
958 });
959 }),
960 )
961 .pipe(Effect.flip);
962 expect(refused._tag).toEqual("OwnedBySomeoneElse");
963
964 // The refused deploy left the foreign worker's ownership untouched.
965 const tags = yield* getWorkerTags(physicalName, accountId);
966 expect(tags).toContain("alchemy:id:UnresolvedOriginal");
967 expect(tags).not.toContain("alchemy:id:UnresolvedDifferent");
968
969 // Its tags still name `UnresolvedOriginal`, so redeploying that id
970 // adopts it back into state and the destroy below deletes it.
971 yield* stack.deploy(
972 Cloudflare.Worker("UnresolvedOriginal", {
973 main,
974 name: physicalName,
975 workersDev: false,
976 compatibility: { date: "2024-01-01" },
977 }),
978 );
979 yield* stack.destroy();
980 yield* waitForWorkerToBeDeleted(physicalName, accountId);
981 }).pipe(logLevel),
982 { tags: ["live"] },
983 );
984
985 // #2198: unresolved props bypass the plan probe, and the self-binding forces
986 // precreate. A binding-only cycle with resolved props would not test this path.
987 for (const scopedAdopt of [undefined, false]) {
988 test.provider(
989 `cyclic precreate refuses a foreign Worker with scoped adoption ${scopedAdopt}`,
990 (stack) =>
991 Effect.gen(function* () {
992 const { accountId } = yield* yield* CloudflareEnvironment;
993 yield* stack.destroy();
994 const original = yield* stack.deploy(
995 Cloudflare.Worker("CyclicOriginal", { main, workersDev: false }),
996 );
997 const request = { accountId, scriptName: original.workerName };
998 const settings = yield* workers.getScriptScriptAndVersionSetting(request);
999 const deployment = yield* workers.listScriptDeployments(request);
1000 yield* Effect.gen(function* () {
1001 const state = yield* yield* State;
1002 yield* state.delete({ stack: stack.name, stage: stack.stage, fqn: "CyclicOriginal" });
1003 }).pipe(Effect.provide(stack.state));
1004
1005 const program = Effect.gen(function* () {
1006 const kv = yield* Cloudflare.KV.Namespace("CyclicKv");
1007 const declaration = Cloudflare.Worker("CyclicDifferent", {
1008 main,
1009 name: original.workerName,
1010 workersDev: false,
1011 env: { KV: kv },
1012 });
1013 const worker = yield* scopedAdopt === undefined
1014 ? declaration
1015 : declaration.pipe(adopt(scopedAdopt));
1016 yield* worker.bind`SELF_NAME`({
1017 bindings: [{ type: "plain_text", name: "SELF_NAME", text: worker.workerName }],
1018 });
1019 return worker;
1020 });
1021 const plan = yield* stack.plan(program);
1022 expect(plan.resources.CyclicDifferent?.action).toBe("create");
1023 const refused = yield* stack.deploy(program).pipe(
1024 Effect.as(false),
1025 Effect.catchTag("OwnedBySomeoneElse", (error) => {
1026 expect(error).toBeInstanceOf(OwnedBySomeoneElse);
1027 return Effect.succeed(true);
1028 }),
1029 );
1030 expect(refused).toBe(true);
1031 const checkpoint = yield* Effect.gen(function* () {
1032 const state = yield* yield* State;
1033 return yield* state.get({
1034 stack: stack.name,
1035 stage: stack.stage,
1036 fqn: "CyclicDifferent",
1037 });
1038 }).pipe(Effect.provide(stack.state));
1039 // Refused before precreate's attributes were checkpointed.
1040 expect(checkpoint?.status).toBe("creating");
1041 if (isResourceState(checkpoint)) expect(checkpoint.attr).toBeUndefined();
1042 // Verify both configuration and active code remain unchanged, not just tags.
1043 expect(yield* workers.getScriptScriptAndVersionSetting(request)).toEqual(settings);
1044 expect(yield* workers.listScriptDeployments(request)).toEqual(deployment);
1045 yield* stack.destroy();
1046 expect(yield* workers.listScriptDeployments(request)).toEqual(deployment);
1047
1048 // Restore only the original logical owner so normal stack cleanup removes it.
1049 yield* stack.deploy(
1050 Cloudflare.Worker("CyclicOriginal", {
1051 main,
1052 name: original.workerName,
1053 workersDev: false,
1054 }),
1055 );
1056 yield* stack.destroy();
1057 yield* waitForWorkerToBeDeleted(original.workerName, accountId);
1058 }).pipe(adopt(scopedAdopt === false), logLevel),
1059 { tags: ["live"], timeout: 120_000 },
1060 );
1061 }
1062
1063 test.provider(
1064 "cyclic precreate permits resource-scoped adoption of a foreign Worker",
1065 (stack) =>
1066 Effect.gen(function* () {
1067 const { accountId } = yield* yield* CloudflareEnvironment;
1068 yield* stack.destroy();
1069 const original = yield* stack.deploy(
1070 Cloudflare.Worker("CyclicAdoptOriginal", { main, workersDev: false }),
1071 );
1072 yield* Effect.gen(function* () {
1073 const state = yield* yield* State;
1074 yield* state.delete({
1075 stack: stack.name,
1076 stage: stack.stage,
1077 fqn: "CyclicAdoptOriginal",
1078 });
1079 }).pipe(Effect.provide(stack.state));
1080 const program = Effect.gen(function* () {
1081 const kv = yield* Cloudflare.KV.Namespace("CyclicAdoptKv");
1082 const worker = yield* Cloudflare.Worker("CyclicAdoptDifferent", {
1083 main,
1084 name: original.workerName,
1085 workersDev: false,
1086 env: { KV: kv },
1087 }).pipe(adopt(true));
1088 yield* worker.bind`SELF_NAME`({
1089 bindings: [{ type: "plain_text", name: "SELF_NAME", text: worker.workerName }],
1090 });
1091 return worker;
1092 });
1093 expect((yield* stack.plan(program)).resources.CyclicAdoptDifferent?.action).toBe(
1094 "create",
1095 );
1096 const adopted = yield* stack.deploy(program);
1097 expect(adopted.workerName).toBe(original.workerName);
1098 const tags = yield* getWorkerTags(adopted.workerName, accountId);
1099 expect(tags).toContain("alchemy:id:CyclicAdoptDifferent");
1100 expect(tags).not.toContain("alchemy:id:CyclicAdoptOriginal");
1101 const settings = yield* workers.getScriptScriptAndVersionSetting({
1102 accountId,
1103 scriptName: adopted.workerName,
1104 });
1105 expect(settings.bindings).toContainEqual(
1106 expect.objectContaining({
1107 type: "plain_text",
1108 name: "SELF_NAME",
1109 text: adopted.workerName,
1110 }),
1111 );
1112 yield* stack.destroy();
1113 yield* waitForWorkerToBeDeleted(adopted.workerName, accountId);
1114 }).pipe(adopt(false), logLevel),
1115 { tags: ["live"], timeout: 120_000 },
1116 );
1117
1118 /**
1119 * A cyclic Worker named `name` in `namespace`. A KV namespace created in
1120 * the same deploy keeps its props unresolved, so `read` cannot run before
1121 * precreate; the self-binding puts it in a cycle.
1122 */
1123 const cyclicWorker = (name: string, namespace: string) =>
1124 Effect.gen(function* () {
1125 const kv = yield* Cloudflare.KV.Namespace("CyclicKv");
1126 const worker = yield* Cloudflare.Worker("CyclicDifferent", {
1127 main,
1128 name,
1129 namespace,
1130 workersDev: false,
1131 env: { KV: kv },
1132 });
1133 yield* worker.bind`SELF_NAME`({
1134 bindings: [{ type: "plain_text", name: "SELF_NAME", text: worker.workerName }],
1135 });
1136 return worker;
1137 });
1138
1139 /**
1140 * Forgets `fqn`, leaving its script owned by another logical id. Returns a
1141 * step that remembers it again, so destroy removes it through normal
1142 * stack cleanup.
1143 */
1144 const forget = Effect.fn(function* (stack: Test.ScratchStack, fqn: string) {
1145 const key = { stack: stack.name, stage: stack.stage, fqn };
1146 const row = yield* Effect.gen(function* () {
1147 const state = yield* yield* State;
1148 const value = yield* state.get(key);
1149 yield* state.delete(key);
1150 return value!;
1151 }).pipe(Effect.provide(stack.state));
1152 return Effect.gen(function* () {
1153 const state = yield* yield* State;
1154 yield* state.set({ ...key, value: row });
1155 }).pipe(Effect.provide(stack.state));
1156 });
1157
1158 const scriptName = (stack: Test.ScratchStack, suffix: string) =>
1159 `alchemy-cyclic-${suffix}-${stack.stage}`.toLowerCase().replace(/[^a-z0-9-]/g, "-");
1160
1161 // #2194: an interrupted create stores its props without the ones that were
1162 // still unresolved. A namespace stripped that way leaves `{ name }`, which
1163 // a recovery lookup resolves to the account-level script of that name.
1164 // Destroy must not delete that script: the attempt never targeted it.
1165 test.provider(
1166 "destroy never recovers an interrupted create from props missing its namespace",
1167 (stack) =>
1168 Effect.gen(function* () {
1169 const { accountId } = yield* yield* CloudflareEnvironment;
1170 yield* stack.destroy();
1171 const name = scriptName(stack, "provenance");
1172 // An account-level script tagged for `Api`, unknown to state.
1173 yield* stack.deploy(Cloudflare.Worker("Api", { main, name, workersDev: false }));
1174 const restore = yield* forget(stack, "Api");
1175 const deployments = () => workers.listScriptDeployments({ accountId, scriptName: name });
1176 const before = yield* deployments();
1177
1178 // `Api` waits on a Worker whose upload fails, so its create stops
1179 // with the namespace still unresolved and no attributes recorded.
1180 const error = yield* stack
1181 .deploy(
1182 Effect.gen(function* () {
1183 const tenant = yield* Cloudflare.WorkersForPlatforms.DispatchNamespace(
1184 "ProvenanceTenant",
1185 { name: scriptName(stack, "provenance-ns") },
1186 );
1187 const broken = yield* Cloudflare.Worker("Broken", {
1188 script: "export default {",
1189 workersDev: false,
1190 });
1191 return yield* Cloudflare.Worker("Api", {
1192 main,
1193 name,
1194 namespace: tenant.name,
1195 env: { BROKEN: broken.workerName },
1196 });
1197 }),
1198 )
1199 .pipe(Effect.flip);
1200 expect(error).toBeDefined();
1201 const checkpoint = yield* Effect.gen(function* () {
1202 const state = yield* yield* State;
1203 return yield* state.get({ stack: stack.name, stage: stack.stage, fqn: "Api" });
1204 }).pipe(Effect.provide(stack.state));
1205 expect(checkpoint).toMatchObject({ status: "creating", propsIncomplete: true });
1206 if (isResourceState(checkpoint)) {
1207 expect(checkpoint.attr).toBeUndefined();
1208 expect(checkpoint.props).not.toHaveProperty("namespace");
1209 }
1210
1211 yield* stack.destroy();
1212 // The account-level script survived the destroy, untouched.
1213 expect(yield* deployments()).toEqual(before);
1214
1215 yield* restore;
1216 yield* stack.destroy();
1217 yield* waitForWorkerToBeDeleted(name, accountId);
1218 }).pipe(logLevel),
1219 { tags: ["live"], timeout: 180_000 },
1220 );
1221
1222 test.provider(
1223 "a cyclic dispatch-namespace Worker refuses a foreign script in its namespace",
1224 (stack) =>
1225 Effect.gen(function* () {
1226 const { accountId } = yield* yield* CloudflareEnvironment;
1227 yield* stack.destroy();
1228 const namespaceName = scriptName(stack, "ns");
1229 const name = scriptName(stack, "user");
1230 const namespace = Cloudflare.WorkersForPlatforms.DispatchNamespace("CyclicNamespace", {
1231 name: namespaceName,
1232 });
1233 // The namespace first: reading a script in a namespace that does not
1234 // exist yet fails with an unknown error.
1235 yield* stack.deploy(namespace);
1236 yield* stack.deploy(
1237 Effect.gen(function* () {
1238 yield* namespace;
1239 return yield* Cloudflare.Worker("CyclicOriginal", {
1240 main,
1241 name,
1242 namespace: namespaceName,
1243 });
1244 }),
1245 );
1246 const restore = yield* forget(stack, "CyclicOriginal");
1247 const request = { accountId, dispatchNamespace: namespaceName, scriptName: name };
1248 const before = yield* wfp.getDispatchNamespaceScript(request);
1249
1250 // A literal namespace is resolved, so `observe` can check the script in it.
1251 const program = Effect.gen(function* () {
1252 yield* namespace;
1253 return yield* cyclicWorker(name, namespaceName);
1254 });
1255 const error = yield* stack.deploy(program).pipe(Effect.flip);
1256 expect(error).toMatchObject({ _tag: "OwnedBySomeoneElse", logicalId: "CyclicDifferent" });
1257 expect((yield* wfp.getDispatchNamespaceScript(request)).modifiedOn).toBe(
1258 before.modifiedOn,
1259 );
1260
1261 // Remember the original before the namespace goes, so destroy deletes its script first.
1262 yield* restore;
1263 yield* stack.destroy();
1264 }).pipe(logLevel),
1265 { tags: ["live"], timeout: 180_000 },
1266 );
1267
1268 // #2540: a cyclic Worker whose namespace is still unresolved precreates a
1269 // stub that claims nothing. Its script must be checked once the namespace
1270 // resolves, before reconcile uploads over a foreign script there.
1271 test.provider(
1272 "a cyclic Worker refuses a foreign script in a namespace that resolves during apply",
1273 (stack) =>
1274 Effect.gen(function* () {
1275 const { accountId } = yield* yield* CloudflareEnvironment;
1276 yield* stack.destroy();
1277 const namespaceName = scriptName(stack, "late-ns");
1278 const name = scriptName(stack, "late-user");
1279 const namespace = Cloudflare.WorkersForPlatforms.DispatchNamespace("LateNamespace", {
1280 name: namespaceName,
1281 });
1282 yield* stack.deploy(namespace);
1283 yield* stack.deploy(
1284 Effect.gen(function* () {
1285 yield* namespace;
1286 return yield* Cloudflare.Worker("LateOriginal", {
1287 main,
1288 name,
1289 namespace: namespaceName,
1290 });
1291 }),
1292 );
1293 const restore = yield* forget(stack, "LateOriginal");
1294 const request = { accountId, dispatchNamespace: namespaceName, scriptName: name };
1295 const before = yield* wfp.getDispatchNamespaceScript(request);
1296
1297 const program = Effect.gen(function* () {
1298 const ns = yield* namespace;
1299 const kv = yield* Cloudflare.KV.Namespace("LateKv");
1300 const worker = yield* Cloudflare.Worker("LateDifferent", {
1301 main,
1302 name,
1303 // Resolves only once `LateKv` is created, after the cycle precreates.
1304 namespace: Output.all(ns.name, kv.namespaceId).pipe(Output.map(([name]) => name)),
1305 workersDev: false,
1306 env: { KV: kv },
1307 });
1308 yield* worker.bind`SELF_NAME`({
1309 bindings: [{ type: "plain_text", name: "SELF_NAME", text: worker.workerName }],
1310 });
1311 return worker;
1312 });
1313 const error = yield* stack.deploy(program).pipe(Effect.flip);
1314 expect(error).toMatchObject({ _tag: "OwnedBySomeoneElse", logicalId: "LateDifferent" });
1315 expect((yield* wfp.getDispatchNamespaceScript(request)).modifiedOn).toBe(
1316 before.modifiedOn,
1317 );
1318 const checkpoint = yield* Effect.gen(function* () {
1319 const state = yield* yield* State;
1320 return yield* state.get({
1321 stack: stack.name,
1322 stage: stack.stage,
1323 fqn: "LateDifferent",
1324 });
1325 }).pipe(Effect.provide(stack.state));
1326 // The stub claimed nothing, so a retry checks the script again.
1327 expect(checkpoint?.status).toBe("creating");
1328 if (isResourceState(checkpoint)) expect(checkpoint.attr).toBeUndefined();
1329
1330 // Remember the original before the namespace goes, so destroy deletes its script first.
1331 yield* restore;
1332 yield* stack.destroy();
1333 }).pipe(logLevel),
1334 { tags: ["live"], timeout: 180_000 },
1335 );
1336
1337 // #2533: a cyclic dispatch-namespace Worker precreates a stub that uploads
1338 // nothing. Its namespace comes from outside the cycle, so it resolves
1339 // before precreate and the stub records it. When the upload then fails,
1340 // destroy must not read that as an account-level Worker and delete the
1341 // same-name script there.
1342 test.provider(
1343 "destroy preserves the account Worker after an interrupted dispatch precreate",
1344 (stack) =>
1345 Effect.gen(function* () {
1346 const { accountId } = yield* yield* CloudflareEnvironment;
1347 yield* stack.destroy();
1348 const name = scriptName(stack, "stub-cleanup");
1349 // An account-level script tagged for `Api`, unknown to state.
1350 yield* stack.deploy(Cloudflare.Worker("Api", { main, name, workersDev: false }));
1351 const restore = yield* forget(stack, "Api");
1352 yield* Effect.gen(function* () {
1353 const deployments = () =>
1354 workers.listScriptDeployments({ accountId, scriptName: name });
1355 const before = yield* deployments();
1356 // The namespace derives from a new output and doesn't exist, so
1357 // the dispatch upload fails after precreate wrote its stub.
1358 const error = yield* stack
1359 .deploy(
1360 Effect.gen(function* () {
1361 const late = yield* Cloudflare.KV.Namespace("StubScopeMarker");
1362 const worker = yield* Cloudflare.Worker("Api", {
1363 main,
1364 name,
1365 namespace: Output.map(late.namespaceId, () =>
1366 scriptName(stack, "unavailable-ns"),
1367 ),
1368 env: { KV: late },
1369 });
1370 yield* worker.bind`SELF_NAME`({
1371 bindings: [{ type: "plain_text", name: "SELF_NAME", text: worker.workerName }],
1372 });
1373 return worker;
1374 }),
1375 )
1376 .pipe(Effect.flip);
1377 expect(error).toBeDefined();
1378 const checkpoint = yield* Effect.gen(function* () {
1379 const state = yield* yield* State;
1380 return yield* state.get({ stack: stack.name, stage: stack.stage, fqn: "Api" });
1381 }).pipe(Effect.provide(stack.state));
1382 expect(checkpoint).toMatchObject({ status: "creating" });
1383 if (!isResourceState(checkpoint))
1384 return yield* Effect.die("Missing resource checkpoint");
1385 expect(checkpoint.attr).toMatchObject({
1386 workerId: "",
1387 namespace: scriptName(stack, "unavailable-ns"),
1388 });
1389 expect(yield* deployments()).toEqual(before);
1390
1391 yield* stack.destroy();
1392 // The account-level script survived the destroy, untouched.
1393 expect(yield* deployments()).toEqual(before);
1394 }).pipe(Effect.ensuring(restore.pipe(Effect.andThen(stack.destroy()), Effect.orDie)));
1395 yield* waitForWorkerToBeDeleted(name, accountId);
1396 }).pipe(logLevel),
1397 { tags: ["live"], timeout: 180_000 },
1398 );
1399
1400 // First-deploy behaviour: the default (omitting `workersDev`) must enable
1401 // the workers.dev subdomain, and `workersDev: false` must disable it. Both
1402 // are asserted against live Cloudflare state via `getScriptSubdomain`,
1403 // not just the resource's output attributes.
1404 test.provider(
1405 "workersDev defaults to enabling the workers.dev subdomain on first deploy",
1406 (stack) =>
1407 Effect.gen(function* () {
1408 const { accountId } = yield* yield* CloudflareEnvironment;
1409
1410 yield* stack.destroy();
1411
1412 const worker = yield* stack.deploy(
1413 Effect.gen(function* () {
1414 return yield* Cloudflare.Worker("SubdomainDefaultWorker", {
1415 main,
1416 compatibility: { date: "2024-01-01" },
1417 });
1418 }),
1419 );
1420
1421 // Default: url = the stable workers.dev URL = allUrls[0], and
1422 // domains mirrors allUrls as bare hostnames.
1423 expect(worker.url).toMatch(
1424 new RegExp(`^https://${worker.workerName}\\..*\\.workers\\.dev$`),
1425 );
1426 expect(worker.urls).toEqual([worker.url]);
1427 expect(worker.domain).toBeUndefined();
1428 yield* expectWorkersDevSubdomain(worker.workerName, accountId, true);
1429
1430 yield* stack.destroy();
1431 yield* waitForWorkerToBeDeleted(worker.workerName, accountId);
1432 }).pipe(logLevel),
1433 { tags: ["live"] },
1434 );
1435
1436 test.provider(
1437 "workersDev: false disables the workers.dev subdomain on first deploy",
1438 (stack) =>
1439 Effect.gen(function* () {
1440 const { accountId } = yield* yield* CloudflareEnvironment;
1441
1442 yield* stack.destroy();
1443
1444 const worker = yield* stack.deploy(
1445 Effect.gen(function* () {
1446 return yield* Cloudflare.Worker("SubdomainDisabledWorker", {
1447 main,
1448 workersDev: false,
1449 compatibility: { date: "2024-01-01" },
1450 });
1451 }),
1452 );
1453
1454 expect(worker.url).toBeUndefined();
1455 expect(worker.urls).toEqual([]);
1456 expect(worker.domain).toBeUndefined();
1457 yield* expectWorkersDevSubdomain(worker.workerName, accountId, false);
1458
1459 yield* stack.destroy();
1460 yield* waitForWorkerToBeDeleted(worker.workerName, accountId);
1461 }).pipe(logLevel),
1462 { tags: ["live"] },
1463 );
1464
1465 // Update regression: toggling `workersDev` between deploys must propagate
1466 // to the live Cloudflare subdomain state. Before this regression
1467 // was fixed, the reconciler diffed the props symmetrically — but the
1468 // observed-vs-desired check inside reconcile must still flip the toggle
1469 // when props really do change.
1470 test.provider(
1471 "toggling workersDev between deploys flips the workers.dev subdomain",
1472 (stack) =>
1473 Effect.gen(function* () {
1474 const { accountId } = yield* yield* CloudflareEnvironment;
1475
1476 yield* stack.destroy();
1477
1478 const deploy = (workersDev: boolean) =>
1479 stack.deploy(
1480 Effect.gen(function* () {
1481 return yield* Cloudflare.Worker("SubdomainToggleWorker", {
1482 main,
1483 workersDev,
1484 compatibility: { date: "2024-01-01" },
1485 });
1486 }),
1487 );
1488
1489 const v1 = yield* deploy(true);
1490 expect(v1.url).toBeDefined();
1491 yield* expectWorkersDevSubdomain(v1.workerName, accountId, true);
1492
1493 const v2 = yield* deploy(false);
1494 expect(v2.workerName).toEqual(v1.workerName);
1495 expect(v2.url).toBeUndefined();
1496 yield* expectWorkersDevSubdomain(v2.workerName, accountId, false);
1497
1498 const v3 = yield* deploy(true);
1499 expect(v3.workerName).toEqual(v1.workerName);
1500 expect(v3.url).toBeDefined();
1501 yield* expectWorkersDevSubdomain(v3.workerName, accountId, true);
1502
1503 yield* stack.destroy();
1504 yield* waitForWorkerToBeDeleted(v1.workerName, accountId);
1505 }).pipe(logLevel),
1506 { tags: ["live"] },
1507 );
1508
1509 // `workersDev: { enabled: false, previewsEnabled: true }` — a "preview-only" worker.
1510 // The stable workers.dev URL is off, so the current version's preview URL
1511 // (`https://<version-prefix>-<name>.<account>.workers.dev`) becomes the
1512 // primary `url` output.
1513 test.provider(
1514 "workersDev previews-only surfaces the version preview URL as url",
1515 (stack) =>
1516 Effect.gen(function* () {
1517 const { accountId } = yield* yield* CloudflareEnvironment;
1518
1519 yield* stack.destroy();
1520
1521 const worker = yield* stack.deploy(
1522 Effect.gen(function* () {
1523 return yield* Cloudflare.Worker("PreviewOnlyWorker", {
1524 main,
1525 workersDev: { enabled: false, previewsEnabled: true },
1526 compatibility: { date: "2024-01-01" },
1527 });
1528 }),
1529 );
1530
1531 yield* expectWorkersDevPreviews(worker.workerName, accountId, {
1532 enabled: false,
1533 previewsEnabled: true,
1534 });
1535 // The preview URL is version-scoped: an 8-char version prefix in
1536 // front of the worker name.
1537 expect(worker.url).toMatch(
1538 new RegExp(`^https://[0-9a-f]{8}-${worker.workerName}\\..*\\.workers\\.dev$`),
1539 );
1540 expect(worker.urls).toEqual([worker.url]);
1541 expect(worker.domain).toBeUndefined();
1542
1543 yield* stack.destroy();
1544 yield* waitForWorkerToBeDeleted(worker.workerName, accountId);
1545 }).pipe(logLevel),
1546 { tags: ["live"] },
1547 );
1548
1549 // Dev mode: no workers.dev or custom-domain URLs exist, so the local dev
1550 // server's localhost URL leads `allUrls` and is the `url`.
1551 devTest.provider(
1552 "dev mode: url is the local dev server URL",
1553 (stack) =>
1554 Effect.gen(function* () {
1555 yield* stack.destroy();
1556
1557 const worker = yield* stack.deploy(
1558 Effect.gen(function* () {
1559 return yield* Cloudflare.Worker("LocalUrlWorker", {
1560 main,
1561 dev: { port: 0 },
1562 compatibility: { date: "2024-01-01" },
1563 });
1564 }),
1565 );
1566
1567 expect(worker.url).toMatch(/^http:\/\/localhost:\d+$/);
1568 expect(worker.urls[0]).toEqual(worker.url);
1569 expect(new URL(worker.urls[0]).hostname).toEqual("localhost");
1570 expect(worker.domain).toBeUndefined();
1571
1572 // The URL actually serves the local worker.
1573 yield* expectUrlContains(`${worker.url}/`, "Hello from TestWorker", {
1574 timeout: "30 seconds",
1575 label: "local dev worker",
1576 });
1577
1578 yield* stack.destroy();
1579 }).pipe(logLevel),
1580 { tags: ["local"] },
1581 );
1582
1583 // Drift regression: if something external (a previous failed deploy,
1584 // a Cloudflare dashboard toggle, the bootstrap path in `loginWithCloudflare`)
1585 // leaves the workers.dev subdomain in `enabled: true, previewsEnabled: false`,
1586 // a redeploy must observe `previewsEnabled` and flip it back on. The
1587 // pre-fix reconciler diffed only `enabled` against desired, so it
1588 // skipped the API call and let the drift persist.
1589 test.provider(
1590 "redeploy re-enables previewsEnabled when externally disabled",
1591 (stack) =>
1592 Effect.gen(function* () {
1593 const { accountId } = yield* yield* CloudflareEnvironment;
1594
1595 yield* stack.destroy();
1596
1597 // Deploy with different compatibility dates to force the update.
1598 const deploy = (date: string) =>
1599 stack.deploy(
1600 Cloudflare.Worker("SubdomainPreviewsDriftWorker", { main, compatibility: { date } }),
1601 );
1602
1603 const v1 = yield* deploy("2026-01-01");
1604 yield* expectWorkersDevPreviews(v1.workerName, accountId, {
1605 enabled: true,
1606 previewsEnabled: true,
1607 });
1608
1609 // Simulate external drift: leave `enabled: true` but turn
1610 // `previewsEnabled` off out-of-band.
1611 yield* workers.createScriptSubdomain({
1612 accountId,
1613 scriptName: v1.workerName,
1614 enabled: true,
1615 previewsEnabled: false,
1616 });
1617 const drifted = yield* workers.getScriptSubdomain({
1618 accountId,
1619 scriptName: v1.workerName,
1620 });
1621 expect(drifted).toEqual({ enabled: true, previewsEnabled: false });
1622
1623 const v2 = yield* deploy("2026-01-02");
1624 expect(v2.workerName).toEqual(v1.workerName);
1625 yield* expectWorkersDevPreviews(v2.workerName, accountId, {
1626 enabled: true,
1627 previewsEnabled: true,
1628 });
1629
1630 yield* stack.destroy();
1631 yield* waitForWorkerToBeDeleted(v1.workerName, accountId);
1632 }).pipe(logLevel),
1633 { tags: ["live"] },
1634 );
1635
1636 // `process.stdin` is undefined on compatibility dates before Node.js
1637 // process v2, so an Effect Worker's platform services must not read it
1638 // while the Worker starts.
1639 for (const [label, worker, dev] of [
1640 ["live", test, false],
1641 ["dev", devTest, true],
1642 ] as const) {
1643 worker.provider(
1644 `Effect Worker serves on a compatibility date without process.stdin (${label})`,
1645 (stack) =>
1646 Effect.gen(function* () {
1647 yield* stack.destroy();
1648 const deployed = yield* stack.deploy(OldCompatEffectWorker);
1649 yield* expectUrlContains(deployed.url!, "Hello from an old compatibility date", {
1650 label: `old compatibility date (${label})`,
1651 });
1652 yield* stack.destroy();
1653 }).pipe(logLevel),
1654 { tags: [dev ? "local" : "live"] },
1655 );
1656
1657 // ...while on later dates, where `process.stdin` exists, handlers
1658 // still get the `Terminal` service.
1659 worker.provider(
1660 `Effect Worker on a current compatibility date still provides Terminal (${label})`,
1661 (stack) =>
1662 Effect.gen(function* () {
1663 yield* stack.destroy();
1664 const deployed = yield* stack.deploy(TerminalEffectWorker);
1665 yield* expectUrlContains(deployed.url!, "Terminal provided (number)", {
1666 label: `Terminal on a current compatibility date (${label})`,
1667 });
1668 yield* stack.destroy();
1669 }).pipe(logLevel),
1670 { tags: [dev ? "local" : "live"] },
1671 );
1672 }
1673
1674 // #745 regression: metadata-only edits (compatibility flags, observability,
1675 // placement, limits, logpush, env literals, ...) never touch the
1676 // bundle/vite/asset-content hashes, so the update decision used to plan
1677 // them as a noop and silently skip the deploy. `hash.metadata` makes them
1678 // visible to the diff. Deploy a worker, re-deploy with a
1679 // compatibility-flag-only and then an observability-only change, and
1680 // assert each change actually lands in the live script settings. Identical
1681 // props must keep planning as a noop — that guards the hash's stability
1682 // across runs (Redacted env values hash by value, not by reference, so the
1683 // freshly-constructed secret in each plan must not force a phantom update).
1684 test.provider(
1685 "metadata-only changes (compatibility flags, observability) deploy",
1686 (stack) =>
1687 Effect.gen(function* () {
1688 const { accountId } = yield* yield* CloudflareEnvironment;
1689
1690 yield* stack.destroy();
1691
1692 const program = (opts: { flags: string[]; observability: boolean }) =>
1693 Effect.gen(function* () {
1694 return yield* Cloudflare.Worker("MetadataOnlyWorker", {
1695 main,
1696 compatibility: { date: "2024-01-01", flags: opts.flags },
1697 observability: { enabled: opts.observability },
1698 env: { WORKER_SECRET: Redacted.make("metadata-hash-stability") },
1699 });
1700 });
1701
1702 const actionOf = (plan: any, logicalId: string) =>
1703 (Object.values(plan.resources) as any[]).find(
1704 (node: any) => node.resource.LogicalId === logicalId,
1705 )?.action;
1706
1707 const v1 = yield* stack.deploy(program({ flags: [], observability: false }));
1708
1709 // Identical props → noop.
1710 const stablePlan = yield* stack.plan(program({ flags: [], observability: false }));
1711 expect(actionOf(stablePlan, "MetadataOnlyWorker")).toBe("noop");
1712
1713 // A compatibility-flag-only change must plan as an update ...
1714 const flagPlan = yield* stack.plan(
1715 program({ flags: ["nodejs_als"], observability: false }),
1716 );
1717 expect(actionOf(flagPlan, "MetadataOnlyWorker")).toBe("update");
1718
1719 // ... and the deploy must apply it to the live script settings.
1720 const v2 = yield* stack.deploy(program({ flags: ["nodejs_als"], observability: false }));
1721 expect(v2.workerName).toEqual(v1.workerName);
1722 const flagSettings = yield* workers.getScriptScriptAndVersionSetting({
1723 accountId,
1724 scriptName: v2.workerName,
1725 });
1726 expect(flagSettings.compatibilityFlags).toContain("nodejs_als");
1727
1728 // Same for an observability-only change. The bundle hash must not
1729 // move — proof the update decision came from the metadata hash alone,
1730 // not from an incidental rebuild.
1731 const v3 = yield* stack.deploy(program({ flags: ["nodejs_als"], observability: true }));
1732 expect(v3.hash?.bundle).toEqual(v2.hash?.bundle);
1733 const observabilitySettings = yield* workers.getScriptScriptAndVersionSetting({
1734 accountId,
1735 scriptName: v3.workerName,
1736 });
1737 expect(observabilitySettings.observability?.enabled).toBe(true);
1738
1739 // The applied props are now the stored state → back to noop.
1740 const settledPlan = yield* stack.plan(
1741 program({ flags: ["nodejs_als"], observability: true }),
1742 );
1743 expect(actionOf(settledPlan, "MetadataOnlyWorker")).toBe("noop");
1744
1745 yield* stack.destroy();
1746 yield* waitForWorkerToBeDeleted(v1.workerName, accountId);
1747 }).pipe(logLevel),
1748 { tags: ["live"], timeout: 360_000 },
1749 );
1750
1751 // Cloudflare keeps a `secret_text` binding that a script upload omits, so
1752 // a secret removed from `env` stayed bound to the deployed Worker. The
1753 // cleanup must not touch a secret set outside Alchemy.
1754 test.provider(
1755 "a secret removed from env is unbound; one set outside Alchemy is kept",
1756 (stack) =>
1757 Effect.gen(function* () {
1758 const { accountId } = yield* yield* CloudflareEnvironment;
1759
1760 yield* stack.destroy();
1761
1762 const program = (env: Record<string, Redacted.Redacted<string>>) =>
1763 Cloudflare.Worker("RemovedSecretWorker", { main, env });
1764 const secretBindings = (scriptName: string) =>
1765 workers.getScriptScriptAndVersionSetting({ accountId, scriptName }).pipe(
1766 Effect.map((settings) =>
1767 (settings.bindings ?? [])
1768 .filter((binding) => binding.type === "secret_text")
1769 .map((binding) => binding.name)
1770 .sort(),
1771 ),
1772 );
1773
1774 const v1 = yield* stack.deploy(
1775 program({ DROPPED: Redacted.make("dropped"), KEPT: Redacted.make("kept") }),
1776 );
1777 expect(yield* secretBindings(v1.workerName)).toEqual(["DROPPED", "KEPT"]);
1778 yield* workers.putScriptSecret({
1779 accountId,
1780 scriptName: v1.workerName,
1781 name: "OUTSIDE",
1782 text: "set-outside-alchemy",
1783 type: "secret_text",
1784 });
1785
1786 const v2 = yield* stack.deploy(program({ KEPT: Redacted.make("kept") }));
1787 expect(yield* secretBindings(v2.workerName)).toEqual(["KEPT", "OUTSIDE"]);
1788 expect(v2.secretNames).toEqual(["KEPT"]);
1789
1790 const settledPlan = yield* stack.plan(program({ KEPT: Redacted.make("kept") }));
1791 const action = Object.values(settledPlan.resources).find(
1792 (node) => node.resource.LogicalId === "RemovedSecretWorker",
1793 )?.action;
1794 expect(action).toBe("noop");
1795
1796 yield* stack.destroy();
1797 yield* waitForWorkerToBeDeleted(v1.workerName, accountId);
1798 }).pipe(logLevel),
1799 { tags: ["live"], timeout: 240_000 },
1800 );
1801
1802 test.provider(
1803 "Issues survive code redeploys and can be disabled or removed",
1804 (stack) =>
1805 Effect.gen(function* () {
1806 const { accountId } = yield* yield* CloudflareEnvironment;
1807 yield* stack.destroy();
1808
1809 const observability = {
1810 enabled: true,
1811 headSamplingRate: 0.5,
1812 logs: { enabled: true, invocationLogs: true, headSamplingRate: 0, persist: false },
1813 traces: { enabled: false, headSamplingRate: 0.1, persist: false },
1814 };
1815 let original: workers.GetScriptScriptAndVersionSettingResponse | undefined;
1816 let scriptName = "";
1817 let tailName = "";
1818 for (const [issues, version] of [
1819 [true, "v1"],
1820 [true, "v2"],
1821 [false, "v2"],
1822 [true, "v2"],
1823 [undefined, "v2"],
1824 ] as const) {
1825 const { worker, tail } = yield* stack.deploy(
1826 Effect.gen(function* () {
1827 const tail = yield* Cloudflare.Worker("IssuesTail", {
1828 script: "export default { tail() {} };",
1829 bundle: false,
1830 });
1831 const worker = yield* Cloudflare.Worker("IssuesWorker", {
1832 script: `export default { fetch() { return new Response("${version}"); } };`,
1833 bundle: false,
1834 logpush: true,
1835 tags: ["issues-preservation"],
1836 tailConsumers: [tail],
1837 compatibility: { date: "2024-01-01", flags: ["nodejs_als"] },
1838 limits: { cpuMs: 50 },
1839 env: { PRESERVED: "issues-preservation" },
1840 observability: {
1841 ...observability,
1842 issues: issues === undefined ? undefined : { enabled: issues },
1843 },
1844 });
1845 return { worker, tail };
1846 }),
1847 );
1848 tailName = tail.workerName;
1849 if (scriptName) expect(worker.workerName).toBe(scriptName);
1850 scriptName = worker.workerName;
1851
1852 const settings = yield* workers.getScriptScriptAndVersionSetting({
1853 accountId,
1854 scriptName,
1855 });
1856 expect(settings.observability?.issues?.enabled ?? false).toBe(issues ?? false);
1857 expect(settings.observability?.enabled).toBe(true);
1858 expect(settings.observability?.headSamplingRate).toBe(0.5);
1859 expect(settings.observability?.logs).toMatchObject(observability.logs);
1860 expect(settings.observability?.traces).toMatchObject(observability.traces);
1861 expect(settings.logpush).toBe(true);
1862 expect(settings.tags).toContain("issues-preservation");
1863 expect(settings.tailConsumers).toEqual([{ service: tailName }]);
1864 expect(settings.compatibilityDate).toBe("2024-01-01");
1865 expect(settings.compatibilityFlags).toEqual(["nodejs_als"]);
1866 expect(settings.limits).toMatchObject({ cpuMs: 50 });
1867 expect(settings.bindings).toContainEqual({
1868 type: "plain_text",
1869 name: "PRESERVED",
1870 text: "issues-preservation",
1871 });
1872 const unchanged = {
1873 ...settings,
1874 observability: { ...settings.observability!, issues: undefined },
1875 };
1876 if (original) expect(unchanged).toEqual(original);
1877 else original = unchanged;
1878 yield* expectUrlContains(worker.url!, version, { timeout: "30 seconds" });
1879 }
1880 // Exercise PATCH explicitly: a successful upload can make the fallback unnecessary.
1881 for (const enabled of [true, false]) {
1882 yield* workers.patchScriptSetting({
1883 accountId,
1884 scriptName,
1885 observability: {
1886 ...observability,
1887 redactQueryString: true,
1888 issues: { enabled },
1889 },
1890 });
1891 const patched = yield* workers.getScriptScriptAndVersionSetting({
1892 accountId,
1893 scriptName,
1894 });
1895 expect(patched.observability?.issues?.enabled).toBe(enabled);
1896 expect({
1897 ...patched,
1898 observability: { ...patched.observability, issues: undefined },
1899 }).toEqual({
1900 ...original,
1901 observability: { ...original!.observability, redactQueryString: true },
1902 });
1903 }
1904
1905 yield* stack.destroy();
1906 yield* waitForWorkerToBeDeleted(scriptName, accountId);
1907 yield* waitForWorkerToBeDeleted(tailName, accountId);
1908 }).pipe(logLevel),
1909 { tags: ["live"], timeout: 120_000 },
1910 );
1911
1912 // #874 regression: binding a tagged Worker identity (an Effect class) in
1913 // another Worker's `env` — the circular-bindings pattern — must converge.
1914 // The tag stays in the desired props (`news.env.TARGET` is an Effect) while
1915 // `stripUnresolved` removes it from the stored props at commit, so a diff
1916 // that compares the two raw shapes plans an update on every deploy, forever.
1917 // After a successful deploy, an identical program must plan as a noop —
1918 // and a code-only change must STILL plan as an update (the tag must not
1919 // knock the diff off its bundle-hash path onto the raw-props fallback,
1920 // which can't see file contents).
1921 test.provider(
1922 "Effect-valued worker tag in env converges to a noop plan",
1923 (stack) =>
1924 Effect.gen(function* () {
1925 const { accountId } = yield* yield* CloudflareEnvironment;
1926 const fs = yield* FileSystem.FileSystem;
1927 const path = yield* Path.Path;
1928
1929 yield* stack.destroy();
1930
1931 class EnvTagTarget extends Cloudflare.Worker<EnvTagTarget, {}>()("EnvTagTargetWorker") {}
1932 class EnvTagCaller extends Cloudflare.Worker<EnvTagCaller, {}>()("EnvTagCallerWorker") {}
1933
1934 // The caller's entry lives in a temp dir so the test can edit its
1935 // contents mid-flight without touching the shared checked-in fixture.
1936 const callerScript = (marker: string) =>
1937 `export default { fetch: async () => new Response(${JSON.stringify(marker)}) };\n`;
1938 const tempDir = yield* fs.makeTempDirectory({ prefix: "alchemy-env-tag-worker" });
1939 const callerMain = path.join(tempDir, "worker.ts");
1940 yield* fs.writeFileString(callerMain, callerScript("v1"));
1941
1942 const layers = Layer.mergeAll(
1943 EnvTagTarget.make({ main, isExternal: true }, Effect.succeed({})),
1944 EnvTagCaller.make(
1945 { main: callerMain, isExternal: true, env: { TARGET: EnvTagTarget } },
1946 Effect.succeed({}),
1947 ),
1948 );
1949
1950 const program = () =>
1951 Effect.gen(function* () {
1952 const target = yield* EnvTagTarget;
1953 const caller = yield* EnvTagCaller;
1954 return { target, caller };
1955 }).pipe(Effect.provide(layers));
1956
1957 const actionOf = (plan: any, logicalId: string) =>
1958 (Object.values(plan.resources) as any[]).find(
1959 (node: any) => node.resource.LogicalId === logicalId,
1960 )?.action;
1961
1962 const deployed = yield* stack.deploy(program());
1963
1964 // The env tag must have landed as a live service binding.
1965 const settings = yield* workers.getScriptScriptAndVersionSetting({
1966 accountId,
1967 scriptName: deployed.caller.workerName,
1968 });
1969 expect(settings.bindings).toContainEqual(
1970 expect.objectContaining({
1971 type: "service",
1972 name: "TARGET",
1973 service: deployed.target.workerName,
1974 }),
1975 );
1976
1977 // Identical program → both workers plan as noop.
1978 const settledPlan = yield* stack.plan(program());
1979 expect(actionOf(settledPlan, "EnvTagTargetWorker")).toBe("noop");
1980 expect(actionOf(settledPlan, "EnvTagCallerWorker")).toBe("noop");
1981
1982 // A code-only change to the caller's entry (identical props — the
1983 // bundle hash is the only difference) must still plan as an update.
1984 yield* fs.writeFileString(callerMain, callerScript("v2"));
1985 const codeChangePlan = yield* stack.plan(program());
1986 expect(actionOf(codeChangePlan, "EnvTagTargetWorker")).toBe("noop");
1987 expect(actionOf(codeChangePlan, "EnvTagCallerWorker")).toBe("update");
1988
1989 yield* stack.destroy();
1990 yield* waitForWorkerToBeDeleted(deployed.caller.workerName, accountId);
1991 yield* waitForWorkerToBeDeleted(deployed.target.workerName, accountId);
1992 }).pipe(logLevel),
1993 { tags: ["live"], timeout: 360_000 },
1994 );
1995
1996 // #1272 regression, remaining #874 case: an already-yielded Worker is
1997 // plain resource attributes rather than an Effect-valued tag. In a binding
1998 // chain, plan and apply may materialize different stable/full projections
1999 // of those attributes, but both describe the same service binding and must
2000 // converge.
2001 // Switching the actual target must still update the caller and land in
2002 // Cloudflare.
2003 test.provider(
2004 "nested yielded worker resources in env converge to noop plans",
2005 (stack) =>
2006 Effect.gen(function* () {
2007 const { accountId } = yield* yield* CloudflareEnvironment;
2008
2009 yield* stack.destroy();
2010
2011 const program = (selected: "A" | "B") =>
2012 Effect.gen(function* () {
2013 const targetB = yield* Cloudflare.Worker("YieldedEnvTargetB", { main });
2014 const targetA = yield* Cloudflare.Worker("YieldedEnvTargetA", {
2015 main,
2016 env: { UPSTREAM: targetB },
2017 });
2018 const caller = yield* Cloudflare.Worker("YieldedEnvCaller", {
2019 main,
2020 env: { TARGET: selected === "A" ? targetA : targetB },
2021 });
2022 return { targetA, targetB, caller };
2023 });
2024
2025 const actionOf = (plan: any, logicalId: string) =>
2026 (Object.values(plan.resources) as any[]).find(
2027 (node: any) => node.resource.LogicalId === logicalId,
2028 )?.action;
2029
2030 const deployedA = yield* stack.deploy(program("A"));
2031 const bindingTarget = Effect.fn(function* (callerName: string) {
2032 const settings = yield* workers.getScriptScriptAndVersionSetting({
2033 accountId,
2034 scriptName: callerName,
2035 });
2036 return settings.bindings?.find(
2037 (binding) => binding.type === "service" && binding.name === "TARGET",
2038 );
2039 });
2040 expect(yield* bindingTarget(deployedA.caller.workerName)).toEqual(
2041 expect.objectContaining({
2042 type: "service",
2043 name: "TARGET",
2044 service: deployedA.targetA.workerName,
2045 }),
2046 );
2047
2048 const stableA = yield* stack.plan(program("A"));
2049 expect(actionOf(stableA, "YieldedEnvTargetA")).toBe("noop");
2050 expect(actionOf(stableA, "YieldedEnvTargetB")).toBe("noop");
2051 expect(actionOf(stableA, "YieldedEnvCaller")).toBe("noop");
2052
2053 const switchPlan = yield* stack.plan(program("B"));
2054 expect(actionOf(switchPlan, "YieldedEnvTargetA")).toBe("noop");
2055 expect(actionOf(switchPlan, "YieldedEnvTargetB")).toBe("noop");
2056 expect(actionOf(switchPlan, "YieldedEnvCaller")).toBe("update");
2057
2058 const deployedB = yield* stack.deploy(program("B"));
2059 expect(yield* bindingTarget(deployedB.caller.workerName)).toEqual(
2060 expect.objectContaining({
2061 type: "service",
2062 name: "TARGET",
2063 service: deployedB.targetB.workerName,
2064 }),
2065 );
2066
2067 const stableB = yield* stack.plan(program("B"));
2068 expect(actionOf(stableB, "YieldedEnvTargetA")).toBe("noop");
2069 expect(actionOf(stableB, "YieldedEnvTargetB")).toBe("noop");
2070 expect(actionOf(stableB, "YieldedEnvCaller")).toBe("noop");
2071
2072 yield* stack.destroy();
2073 yield* Effect.all(
2074 [
2075 deployedB.caller.workerName,
2076 deployedB.targetA.workerName,
2077 deployedB.targetB.workerName,
2078 ].map((name) => waitForWorkerToBeDeleted(name, accountId)),
2079 { concurrency: "unbounded" },
2080 );
2081 }).pipe(logLevel),
2082 { tags: ["live"], timeout: 360_000 },
2083 );
2084
2085 // Precreate publishes the URLs known before the first upload, so a cycle
2086 // of Workers binding each other's `url` resolves on the first deploy.
2087 // Worker A serves only on a custom domain (`workersDev: false`): its
2088 // precreate `url` must be the domain, not `undefined`.
2089 const circularUrlZone =
2090 process.env.CLOUDFLARE_TEST_WORKER_DOMAIN_ZONE_NAME ?? "alchemy-test-2.us";
2091 test.provider(
2092 "circular Worker URL bindings resolve custom-domain and workers.dev URLs on the first deploy",
2093 (stack) =>
2094 Effect.gen(function* () {
2095 const { accountId } = yield* yield* CloudflareEnvironment;
2096 const suffix = stageSuffix();
2097 const domainA = `alchemy-circular-url-${suffix}.${circularUrlZone}`;
2098
2099 yield* stack.destroy();
2100
2101 const program = () =>
2102 Effect.gen(function* () {
2103 const a = yield* Cloudflare.Worker("CircularUrlA", {
2104 main,
2105 workersDev: false,
2106 domain: domainA,
2107 });
2108 const b = yield* Cloudflare.Worker("CircularUrlB", { main });
2109 yield* a.bind`B_URL`({
2110 bindings: [
2111 {
2112 type: "plain_text",
2113 name: "B_URL",
2114 text: b.url.as<string>(),
2115 },
2116 ],
2117 });
2118 yield* b.bind`A_URL`({
2119 bindings: [
2120 {
2121 type: "plain_text",
2122 name: "A_URL",
2123 text: a.url.as<string>(),
2124 },
2125 ],
2126 });
2127 return { a, b };
2128 });
2129
2130 const deployed = yield* stack.deploy(program());
2131 expect(deployed.a.url).toEqual(`https://${domainA}`);
2132 expect(deployed.b.url).toMatch(/^https:\/\/.*\.workers\.dev$/);
2133 for (const [worker, name, peerUrl] of [
2134 [deployed.a, "B_URL", deployed.b.url],
2135 [deployed.b, "A_URL", deployed.a.url],
2136 ] as const) {
2137 const settings = yield* workers.getScriptScriptAndVersionSetting({
2138 accountId,
2139 scriptName: worker.workerName,
2140 });
2141 expect(settings.bindings).toContainEqual(
2142 expect.objectContaining({
2143 type: "plain_text",
2144 name,
2145 text: peerUrl,
2146 }),
2147 );
2148 }
2149
2150 const settled = yield* stack.plan(program());
2151 for (const logicalId of ["CircularUrlA", "CircularUrlB"]) {
2152 const node = (Object.values(settled.resources) as any[]).find(
2153 (candidate) => candidate.resource.LogicalId === logicalId,
2154 );
2155 expect(node?.action).toBe("noop");
2156 }
2157
2158 yield* stack.destroy();
2159 yield* waitForWorkerToBeDeleted(deployed.a.workerName, accountId);
2160 yield* waitForWorkerToBeDeleted(deployed.b.workerName, accountId);
2161 }).pipe(logLevel),
2162 { tags: ["live"], timeout: 360_000 },
2163 );
2164
2165 // The full circular case from the #874 report: A and B each bind the
2166 // OTHER's tag in env. The tags keep the dependency on the binding channel
2167 // (precreate stubs + converge pass) — a cycle the props channel cannot
2168 // express — and both workers must still converge to noop plans.
2169 test.provider(
2170 "circular worker tags in env converge to noop plans",
2171 (stack) =>
2172 Effect.gen(function* () {
2173 const { accountId } = yield* yield* CloudflareEnvironment;
2174
2175 yield* stack.destroy();
2176
2177 class CircTagA extends Cloudflare.Worker<CircTagA, {}>()("CircTagAWorker") {}
2178 class CircTagB extends Cloudflare.Worker<CircTagB, {}>()("CircTagBWorker") {}
2179
2180 const layers = Layer.mergeAll(
2181 CircTagA.make({ main, isExternal: true, env: { PEER: CircTagB } }, Effect.succeed({})),
2182 CircTagB.make({ main, isExternal: true, env: { PEER: CircTagA } }, Effect.succeed({})),
2183 );
2184
2185 const program = () =>
2186 Effect.gen(function* () {
2187 const a = yield* CircTagA;
2188 const b = yield* CircTagB;
2189 return { a, b };
2190 }).pipe(Effect.provide(layers));
2191
2192 const actionOf = (plan: any, logicalId: string) =>
2193 (Object.values(plan.resources) as any[]).find(
2194 (node: any) => node.resource.LogicalId === logicalId,
2195 )?.action;
2196
2197 const deployed = yield* stack.deploy(program());
2198
2199 // Each side must carry a live service binding to the other.
2200 for (const [self, peer] of [
2201 [deployed.a, deployed.b],
2202 [deployed.b, deployed.a],
2203 ] as const) {
2204 const settings = yield* workers.getScriptScriptAndVersionSetting({
2205 accountId,
2206 scriptName: self.workerName,
2207 });
2208 expect(settings.bindings).toContainEqual(
2209 expect.objectContaining({ type: "service", name: "PEER", service: peer.workerName }),
2210 );
2211 }
2212
2213 const settled = yield* stack.plan(program());
2214 expect(actionOf(settled, "CircTagAWorker")).toBe("noop");
2215 expect(actionOf(settled, "CircTagBWorker")).toBe("noop");
2216
2217 yield* stack.destroy();
2218 yield* waitForWorkerToBeDeleted(deployed.a.workerName, accountId);
2219 yield* waitForWorkerToBeDeleted(deployed.b.workerName, accountId);
2220 }).pipe(logLevel),
2221 { tags: ["live"], timeout: 360_000 },
2222 );
2223
2224 // #874 (comments): an Output-valued `worker.bind` binding must also
2225 // converge. Terminal apply commits must persist the RESOLVED binding
2226 // payload — raw `node.bindings` hold the Output expression, which JSON
2227 // state stores silently drop, so every later plan's `diffBindings` would
2228 // compare a lossy stored shape against resolved data and re-update
2229 // forever (the PR #266 path).
2230 test.provider(
2231 "Output-valued worker.bind binding converges to a noop plan",
2232 (stack) =>
2233 Effect.gen(function* () {
2234 const { accountId } = yield* yield* CloudflareEnvironment;
2235
2236 yield* stack.destroy();
2237
2238 const program = () =>
2239 Effect.gen(function* () {
2240 const source = yield* Cloudflare.Worker("BindTextSource", { main });
2241 const host = yield* Cloudflare.Worker("BindTextHost", { main });
2242 // `source.workerName` is an Output<string> at plan time — the
2243 // same shape as an Action-produced value bound as plain_text.
2244 yield* host.bind`REV`({
2245 bindings: [{ type: "plain_text", name: "REV", text: source.workerName }],
2246 });
2247 return { source, host };
2248 });
2249
2250 const actionOf = (plan: any, logicalId: string) =>
2251 (Object.values(plan.resources) as any[]).find(
2252 (node: any) => node.resource.LogicalId === logicalId,
2253 )?.action;
2254
2255 const deployed = yield* stack.deploy(program());
2256
2257 // The resolved text must have landed in the live binding.
2258 const settings = yield* workers.getScriptScriptAndVersionSetting({
2259 accountId,
2260 scriptName: deployed.host.workerName,
2261 });
2262 expect(settings.bindings).toContainEqual(
2263 expect.objectContaining({
2264 type: "plain_text",
2265 name: "REV",
2266 text: deployed.source.workerName,
2267 }),
2268 );
2269
2270 const settled = yield* stack.plan(program());
2271 expect(actionOf(settled, "BindTextSource")).toBe("noop");
2272 expect(actionOf(settled, "BindTextHost")).toBe("noop");
2273
2274 yield* stack.destroy();
2275 yield* waitForWorkerToBeDeleted(deployed.host.workerName, accountId);
2276 yield* waitForWorkerToBeDeleted(deployed.source.workerName, accountId);
2277 }).pipe(logLevel),
2278 { tags: ["live"], timeout: 360_000 },
2279 );
2280
2281 // Effect-valued env entries are stripped from the props comparison (#874),
2282 // so change detection for them rides entirely on the evaluated binding
2283 // data. This test guards that channel: when only the VALUE an env Effect
2284 // resolves to changes (a `gen` Effect — serializes value-blind, so the
2285 // props comparison could never see it), the plan must still flip from
2286 // noop to update.
2287 test.provider(
2288 "changing the value of an Effect-valued env entry plans an update",
2289 (stack) =>
2290 Effect.gen(function* () {
2291 const { accountId } = yield* yield* CloudflareEnvironment;
2292
2293 yield* stack.destroy();
2294
2295 const program = (value: string) =>
2296 Effect.gen(function* () {
2297 return yield* Cloudflare.Worker("EffectEnvValueWorker", {
2298 main,
2299 env: {
2300 VALUE: Effect.gen(function* () {
2301 return value;
2302 }),
2303 },
2304 });
2305 });
2306
2307 const actionOf = (plan: any, logicalId: string) =>
2308 (Object.values(plan.resources) as any[]).find(
2309 (node: any) => node.resource.LogicalId === logicalId,
2310 )?.action;
2311
2312 const deployed = yield* stack.deploy(program("v1"));
2313
2314 // The evaluated value lands as a plain_text binding.
2315 const settings = yield* workers.getScriptScriptAndVersionSetting({
2316 accountId,
2317 scriptName: deployed.workerName,
2318 });
2319 expect(settings.bindings).toContainEqual(
2320 expect.objectContaining({ type: "plain_text", name: "VALUE", text: "v1" }),
2321 );
2322
2323 // Same value → noop; changed value → update.
2324 const samePlan = yield* stack.plan(program("v1"));
2325 expect(actionOf(samePlan, "EffectEnvValueWorker")).toBe("noop");
2326 const changedPlan = yield* stack.plan(program("v2"));
2327 expect(actionOf(changedPlan, "EffectEnvValueWorker")).toBe("update");
2328
2329 // The changed value must actually deploy — and then converge.
2330 const redeployed = yield* stack.deploy(program("v2"));
2331 const updatedSettings = yield* workers.getScriptScriptAndVersionSetting({
2332 accountId,
2333 scriptName: redeployed.workerName,
2334 });
2335 expect(updatedSettings.bindings).toContainEqual(
2336 expect.objectContaining({ type: "plain_text", name: "VALUE", text: "v2" }),
2337 );
2338 const resettled = yield* stack.plan(program("v2"));
2339 expect(actionOf(resettled, "EffectEnvValueWorker")).toBe("noop");
2340
2341 yield* stack.destroy();
2342 yield* waitForWorkerToBeDeleted(deployed.workerName, accountId);
2343 }).pipe(logLevel),
2344 { tags: ["live"], timeout: 360_000 },
2345 );
2346
2347 // #1831 regression: a `Config` value read in an Effect-native Worker's
2348 // Init lands in `props.env` only, which the Worker diff does not compare;
2349 // the planner compares Init-captured values itself. Changing the value
2350 // must plan an update and reach the deployed Worker; an unchanged value
2351 // must stay a noop.
2352 test.provider(
2353 "changing a Config value read in Init plans an update",
2354 (stack) =>
2355 Effect.gen(function* () {
2356 const { accountId } = yield* yield* CloudflareEnvironment;
2357
2358 yield* stack.destroy();
2359
2360 // Layer the value over the ambient provider: the harness snapshots
2361 // `process.env` when the test starts.
2362 const program = (mode: string) =>
2363 Effect.gen(function* () {
2364 const ambient = yield* ConfigProvider.ConfigProvider;
2365 return yield* InitConfigWorker.pipe(
2366 Effect.provideService(
2367 ConfigProvider.ConfigProvider,
2368 ConfigProvider.orElse(
2369 ConfigProvider.fromUnknown({ INIT_CONFIG_WORKER_MODE: mode }),
2370 ambient,
2371 ),
2372 ),
2373 );
2374 });
2375
2376 const actionOf = (plan: any, logicalId: string) =>
2377 (Object.values(plan.resources) as any[]).find(
2378 (node: any) => node.resource.LogicalId === logicalId,
2379 )?.action;
2380
2381 const deployed = yield* stack.deploy(program("init-config-v1"));
2382 yield* expectUrlContains(deployed.url!, "init-config-v1", {
2383 timeout: "60 seconds",
2384 label: "initial Init config value",
2385 });
2386
2387 const samePlan = yield* stack.plan(program("init-config-v1"));
2388 expect(actionOf(samePlan, "InitConfigWorker")).toBe("noop");
2389 const changedPlan = yield* stack.plan(program("init-config-v2"));
2390 expect(actionOf(changedPlan, "InitConfigWorker")).toBe("update");
2391
2392 const redeployed = yield* stack.deploy(program("init-config-v2"));
2393 yield* expectUrlContains(redeployed.url!, "init-config-v2", {
2394 timeout: "60 seconds",
2395 label: "updated Init config value",
2396 });
2397 const resettled = yield* stack.plan(program("init-config-v2"));
2398 expect(actionOf(resettled, "InitConfigWorker")).toBe("noop");
2399
2400 yield* stack.destroy();
2401 yield* waitForWorkerToBeDeleted(deployed.workerName, accountId);
2402 }).pipe(logLevel),
2403 { tags: ["live"], timeout: 360_000 },
2404 );
2405
2406 // `allUrls`/`domains` should reflect the workers.dev URL when the
2407 // subdomain is enabled and be empty when it isn't. `worker.url` is always
2408 // `allUrls[0]`, so the three must stay in lockstep across deploys.
2409 test.provider(
2410 "allUrls and domains reflect the workers.dev subdomain and track url",
2411 (stack) =>
2412 Effect.gen(function* () {
2413 const { accountId } = yield* yield* CloudflareEnvironment;
2414
2415 yield* stack.destroy();
2416
2417 const deploy = (workersDev: boolean) =>
2418 stack.deploy(
2419 Effect.gen(function* () {
2420 return yield* Cloudflare.Worker("DomainsWorker", {
2421 main,
2422 workersDev,
2423 compatibility: { date: "2024-01-01" },
2424 });
2425 }),
2426 );
2427
2428 const enabled = yield* deploy(true);
2429 expect(enabled.urls).toHaveLength(1);
2430 expect(enabled.urls[0]).toMatch(/\.workers\.dev$/);
2431 expect(enabled.url).toEqual(enabled.urls[0]);
2432 expect(enabled.domain).toBeUndefined();
2433
2434 const disabled = yield* deploy(false);
2435 expect(disabled.urls).toEqual([]);
2436 expect(disabled.domain).toBeUndefined();
2437 expect(disabled.url).toBeUndefined();
2438
2439 yield* stack.destroy();
2440 yield* waitForWorkerToBeDeleted(enabled.workerName, accountId);
2441 }).pipe(logLevel),
2442 { tags: ["live"] },
2443 );
2444
2445 // Ordering contract: the canonical custom domain leads `urls` (it is the
2446 // most significant URL), aliases follow in declared order, and the
2447 // workers.dev URL comes last. Swapping name and alias moves `url`.
2448 const customDomainZone =
2449 process.env.CLOUDFLARE_TEST_WORKER_DOMAIN_ZONE_NAME ?? "alchemy-test-2.us";
2450 test.provider(
2451 "custom domain outranks workers.dev in urls and selects url",
2452 (stack) =>
2453 Effect.gen(function* () {
2454 const { accountId } = yield* yield* CloudflareEnvironment;
2455 const suffix = stageSuffix();
2456 const domainA = `alchemy-worker-a-${suffix}.${customDomainZone}`;
2457 const domainB = `alchemy-worker-b-${suffix}.${customDomainZone}`;
2458
2459 yield* stack.destroy();
2460
2461 const deploy = (workersDev: boolean, domain: { name: string; aliases?: string[] }) =>
2462 stack.deploy(
2463 Effect.gen(function* () {
2464 return yield* Cloudflare.Worker("CustomDomainWorker", {
2465 main,
2466 workersDev,
2467 domain,
2468 compatibility: { date: "2024-01-01" },
2469 });
2470 }),
2471 );
2472
2473 // workers.dev enabled: the canonical domain still leads `urls`,
2474 // the alias follows, and the workers.dev URL comes last.
2475 const worker = yield* deploy(true, { name: domainA, aliases: [domainB] });
2476 expect(worker.urls).toHaveLength(3);
2477 expect(worker.urls.slice(0, 2)).toEqual([`https://${domainA}`, `https://${domainB}`]);
2478 expect(worker.urls[2]).toMatch(
2479 new RegExp(`^https://${worker.workerName}\\..*\\.workers\\.dev$`),
2480 );
2481 expect(worker.url).toEqual(`https://${domainA}`);
2482 expect(worker.domain).toEqual({ name: domainA, aliases: [domainB], redirects: [] });
2483
2484 // Domain only (no workers.dev): urls is just the domain + alias.
2485 const domainOnly = yield* deploy(false, { name: domainA, aliases: [domainB] });
2486 expect(domainOnly.urls).toEqual([`https://${domainA}`, `https://${domainB}`]);
2487 expect(domainOnly.url).toEqual(`https://${domainA}`);
2488
2489 // Swap name and alias — `url` follows the canonical name.
2490 const swapped = yield* deploy(false, { name: domainB, aliases: [domainA] });
2491 expect(swapped.urls).toEqual([`https://${domainB}`, `https://${domainA}`]);
2492 expect(swapped.url).toEqual(`https://${domainB}`);
2493 expect(swapped.domain).toEqual({ name: domainB, aliases: [domainA], redirects: [] });
2494
2495 yield* stack.destroy();
2496 yield* waitForWorkerToBeDeleted(worker.workerName, accountId);
2497 }).pipe(logLevel),
2498 { tags: ["live"] },
2499 );
2500
2501 // State-migration: Worker state written by older Alchemy versions stored
2502 // `domains` as `https://<hostname>` URL strings with the workers.dev URL
2503 // mixed in (beta.45–57) or as `{ id, hostname, zoneId }` objects
2504 // (<= beta.44), and had no `allUrls`. A deploy on top of either shape must
2505 // not crash the diff/reconcile and must rewrite the attributes to the
2506 // current shape (bare hostnames aligned with `allUrls`).
2507 test.provider(
2508 "redeploy coerces legacy domains state",
2509 (stack) =>
2510 Effect.gen(function* () {
2511 const { accountId } = yield* yield* CloudflareEnvironment;
2512
2513 yield* stack.destroy();
2514
2515 const deploy = (date: string) =>
2516 stack.deploy(
2517 Effect.gen(function* () {
2518 return yield* Cloudflare.Worker("LegacyStateWorker", {
2519 main,
2520 compatibility: { date },
2521 });
2522 }),
2523 );
2524
2525 const v1 = yield* deploy("2024-01-01");
2526 const workersDevHost = new URL(v1.url!).hostname;
2527
2528 // Rewrite the persisted record to a legacy shape. The stale
2529 // custom-domain entry ("app.example.com") was never attached on
2530 // Cloudflare, so the redeploy must also converge state back to the
2531 // observed cloud truth rather than trusting the record. `props`
2532 // optionally gains the pre-redesign keys so `olds` reaching the diff
2533 // looks exactly like a record an old deploy persisted.
2534 const writeLegacyRecord = (legacy: {
2535 url: string | undefined;
2536 domains: unknown[];
2537 legacyProps?: Record<string, unknown>;
2538 }) =>
2539 Effect.gen(function* () {
2540 const state = yield* yield* State;
2541 const key = { stack: stack.name, stage: stack.stage, fqn: "LegacyStateWorker" };
2542 const current = yield* state.get(key);
2543 expect(current).toBeDefined();
2544 const attr = { ...(current as any).attr, url: legacy.url, domains: legacy.domains };
2545 delete attr.urls;
2546 delete attr.domain;
2547 yield* state.set({
2548 ...key,
2549 value: {
2550 ...(current as any),
2551 attr,
2552 props: { ...(current as any).props, ...legacy.legacyProps },
2553 },
2554 });
2555 }).pipe(Effect.provide(stack.state));
2556
2557 // beta.45–57: URL strings, workers.dev mixed in, no allUrls.
2558 yield* writeLegacyRecord({
2559 url: "https://app.example.com",
2560 domains: ["https://app.example.com", `https://${workersDevHost}`],
2561 });
2562
2563 const v2 = yield* deploy("2024-01-02");
2564 expect(v2.url).toEqual(`https://${workersDevHost}`);
2565 expect(v2.urls).toEqual([`https://${workersDevHost}`]);
2566 expect(v2.domain).toBeUndefined();
2567
2568 // <= beta.44: `{ id, hostname, zoneId }` objects — and the props the
2569 // old code persisted alongside them (`url`/`subdomain` keys), so the
2570 // diff's `olds` carries the pre-redesign prop shape too.
2571 yield* writeLegacyRecord({
2572 url: undefined,
2573 domains: [{ id: "legacy", hostname: "app.example.com", zoneId: "z" }],
2574 legacyProps: { url: true, subdomain: { enabled: true, previewsEnabled: true } },
2575 });
2576
2577 const v3 = yield* deploy("2024-01-03");
2578 expect(v3.url).toEqual(`https://${workersDevHost}`);
2579 expect(v3.urls).toEqual([`https://${workersDevHost}`]);
2580 expect(v3.domain).toBeUndefined();
2581
2582 yield* stack.destroy();
2583 yield* waitForWorkerToBeDeleted(v1.workerName, accountId);
2584 }).pipe(logLevel),
2585 { tags: ["live"] },
2586 );
2587
2588 // The real upgrade path for a bare Worker: the user's props are byte-for-
2589 // byte identical before and after upgrading Alchemy, so the *only* thing
2590 // that can trigger the state migration is the metadata hash (its surface
2591 // changed: `url`/`subdomain` keys out, `workersDev` in). The migration
2592 // must be a one-time update — and a downstream resource consuming
2593 // `worker.urls` (absent from legacy state) must re-resolve through it
2594 // and settle back to noop.
2595 test.provider(
2596 "props-identical redeploy migrates legacy state via the metadata hash",
2597 (stack) =>
2598 Effect.gen(function* () {
2599 const { accountId } = yield* yield* CloudflareEnvironment;
2600
2601 yield* stack.destroy();
2602
2603 // Never changes across the test — like a user who upgrades Alchemy
2604 // without touching their stack code.
2605 const program = Effect.gen(function* () {
2606 const worker = yield* Cloudflare.Worker("BareUpstream", {
2607 main,
2608 compatibility: { date: "2024-01-01" },
2609 });
2610 yield* Cloudflare.Alerting.NotificationWebhook("Hook", {
2611 url: worker.urls.pipe(Output.map((urls) => urls[0]!)),
2612 });
2613 return worker;
2614 });
2615
2616 const actionOf = (plan: any, logicalId: string) =>
2617 (Object.values(plan.resources) as any[]).find(
2618 (node: any) => node.resource.LogicalId === logicalId,
2619 )?.action;
2620
2621 const v1 = yield* stack.deploy(program);
2622 const workersDevHost = new URL(v1.url!).hostname;
2623
2624 // Rewrite the record to what an old deploy persisted: URL-string
2625 // domains, no allUrls, and a metadata hash computed over the old
2626 // surface (any value the new code can't reproduce).
2627 yield* Effect.gen(function* () {
2628 const state = yield* yield* State;
2629 const key = { stack: stack.name, stage: stack.stage, fqn: "BareUpstream" };
2630 const current = yield* state.get(key);
2631 expect(current).toBeDefined();
2632 const attr = {
2633 ...(current as any).attr,
2634 url: `https://${workersDevHost}`,
2635 domains: [`https://${workersDevHost}`],
2636 hash: { ...(current as any).attr.hash, metadata: "legacy" },
2637 };
2638 delete attr.urls;
2639 yield* state.set({ ...key, value: { ...(current as any), attr } });
2640 }).pipe(Effect.provide(stack.state));
2641
2642 // Identical props still plan as an update — driven by the metadata
2643 // hash alone. The downstream's `allUrls` reference is unresolvable
2644 // from legacy state (never marked stable), so it takes a one-time
2645 // update alongside the migration.
2646 const migrationPlan = yield* stack.plan(program);
2647 expect(actionOf(migrationPlan, "BareUpstream")).toBe("update");
2648 expect(actionOf(migrationPlan, "Hook")).toBe("update");
2649
2650 const migrated = yield* stack.deploy(program);
2651 expect(migrated.url).toEqual(`https://${workersDevHost}`);
2652 expect(migrated.urls).toEqual([`https://${workersDevHost}`]);
2653 expect(migrated.domain).toBeUndefined();
2654
2655 // Migration is one-time: the same props now settle as a full noop,
2656 // including the downstream (allUrls is present and stable again).
2657 const settledPlan = yield* stack.plan(program);
2658 expect(actionOf(settledPlan, "BareUpstream")).toBe("noop");
2659 expect(actionOf(settledPlan, "Hook")).toBe("noop");
2660
2661 yield* stack.destroy();
2662 yield* waitForWorkerToBeDeleted(v1.workerName, accountId);
2663 }).pipe(logLevel),
2664 { tags: ["provider:cloudflare:alerting", "live"], timeout: 240_000 },
2665 );
2666
2667 // Canonical `list()` test (account collection): deploy a real Worker and
2668 // assert it shows up in the exhaustively-paginated account-wide listing.
2669 test.provider(
2670 "list enumerates the deployed worker",
2671 (stack) =>
2672 Effect.gen(function* () {
2673 const { accountId } = yield* yield* CloudflareEnvironment;
2674
2675 yield* stack.destroy();
2676
2677 const worker = yield* stack.deploy(
2678 Effect.gen(function* () {
2679 return yield* Cloudflare.Worker("ListWorker", {
2680 main,
2681 compatibility: { date: "2024-01-01" },
2682 });
2683 }),
2684 );
2685
2686 const provider = yield* Provider.findProvider(Cloudflare.Worker);
2687 const all = yield* provider.list();
2688
2689 expect(all.some((w) => w.workerName === worker.workerName)).toBe(true);
2690 const found = all.find((w) => w.workerName === worker.workerName);
2691 expect(found?.workerId).toEqual(worker.workerId);
2692 expect(found?.accountId).toEqual(accountId);
2693
2694 yield* stack.destroy();
2695 yield* waitForWorkerToBeDeleted(worker.workerName, accountId);
2696 }).pipe(logLevel),
2697 { tags: ["live"] },
2698 );
2699
2700 test.provider(
2701 "downstream referencing worker.url is not re-updated when the worker changes",
2702 (stack) =>
2703 // Regression: a downstream resource that references `worker.url` as a
2704 // plain prop (e.g. a GitHub Webhook delivery URL built via
2705 // `Output.interpolate`) must not spuriously re-update every time the
2706 // upstream worker changes. The worker's url is stable across a
2707 // code/config change, so the planner must resolve `worker.url` to a
2708 // concrete value (rather than an unresolved Output, which would make
2709 // `havePropsChanged` short-circuit on `Output.hasOutputs` and force a
2710 // phantom update) and plan the downstream as a no-op.
2711 Effect.gen(function* () {
2712 yield* stack.destroy();
2713
2714 // A worker plus a notification webhook whose `url` prop points at the
2715 // worker (a plain prop dependency, exactly like a GitHub webhook's
2716 // delivery URL). `crons` is the only thing that varies between the
2717 // deploy and the re-plan — it forces the worker to plan as an
2718 // `update` while leaving its url untouched.
2719 const program = (crons: string[]) =>
2720 Effect.gen(function* () {
2721 const worker = yield* Cloudflare.Worker("Upstream", {
2722 main,
2723 crons,
2724 compatibility: { date: "2024-01-01" },
2725 });
2726 yield* Cloudflare.Alerting.NotificationWebhook("Hook", {
2727 url: Output.interpolate`${worker.url}`,
2728 });
2729 });
2730
2731 yield* stack.deploy(program([]));
2732
2733 // Re-plan with the worker changed (a new cron forces an update) but
2734 // the webhook identical. The plan is never applied, so the cron is
2735 // never actually deployed.
2736 const plan = yield* stack.plan(program(["*/10 * * * *"]));
2737
2738 const actionOf = (logicalId: string) =>
2739 Object.values(plan.resources).find((node) => node.resource.LogicalId === logicalId)
2740 ?.action;
2741
2742 expect(actionOf("Upstream")).toBe("update");
2743 expect(actionOf("Hook")).toBe("noop");
2744
2745 yield* stack.destroy();
2746 }).pipe(logLevel),
2747 { tags: ["provider:cloudflare:alerting", "live"], timeout: 180_000 },
2748 );
2749
2750 precreateRaceTest.provider(
2751 "deploy survives a settings read that races the precreated durable object",
2752 (stack) =>
2753 Effect.gen(function* () {
2754 const { accountId } = yield* yield* CloudflareEnvironment;
2755 precreateRace.hostPath = undefined;
2756 precreateRace.injected = 0;
2757 yield* stack.destroy();
2758
2759 // Only Workers in a dependency cycle are precreated, so the Durable
2760 // Object host and a second Worker bind each other's URL.
2761 const { worker, peer } = yield* stack.deploy(
2762 Effect.gen(function* () {
2763 const worker = yield* Cloudflare.Worker("PrecreateRaceWorker", {
2764 script: `import { DurableObject } from "cloudflare:workers";
2765 export class Counter extends DurableObject {
2766 async increment() {
2767 const next = ((await this.ctx.storage.get("count")) ?? 0) + 1;
2768 await this.ctx.storage.put("count", next);
2769 return next;
2770 }
2771 }
2772 export default {
2773 async fetch(request, env) {
2774 const value = await env.Counter.getByName("shared").increment();
2775 return new Response("count=" + value);
2776 },
2777 };`,
2778 env: { Counter: Cloudflare.DurableObject("Counter") },
2779 });
2780 const peer = yield* Cloudflare.Worker("PrecreateRacePeer", { main });
2781 yield* worker.bind`PEER_URL`({
2782 bindings: [{ type: "plain_text", name: "PEER_URL", text: peer.url.as<string>() }],
2783 });
2784 yield* peer.bind`HOST_URL`({
2785 bindings: [{ type: "plain_text", name: "HOST_URL", text: worker.url.as<string>() }],
2786 });
2787 return { worker, peer };
2788 }),
2789 );
2790
2791 // Both racing reads were injected and the deploy still converged.
2792 expect(precreateRace.injected).toBe(2);
2793 expect(Object.keys(worker.durableObjectNamespaces)).toEqual(["Counter"]);
2794 yield* expectUrlContains(worker.url!, "count=");
2795
2796 yield* stack.destroy();
2797 yield* waitForWorkerToBeDeleted(worker.workerName, accountId);
2798 yield* waitForWorkerToBeDeleted(peer.workerName, accountId);
2799 }).pipe(logLevel),
2800 { tags: ["live"], timeout: 180_000 },
2801 );
2802
2803 test.provider(
2804 "codeUpdateStrategy defers or applies Durable Object code updates",
2805 (stack) =>
2806 Effect.gen(function* () {
2807 const { accountId } = yield* yield* CloudflareEnvironment;
2808 const client = yield* HttpClient.HttpClient;
2809 yield* stack.destroy();
2810
2811 // The object reports the code version it runs plus an id minted in
2812 // its constructor, so a reset onto new code is visible.
2813 const program = (
2814 version: string,
2815 codeUpdateStrategy: Cloudflare.WorkerCodeUpdateStrategy,
2816 ) =>
2817 Effect.gen(function* () {
2818 return yield* Cloudflare.Worker("CodeUpdateStrategyWorker", {
2819 script: `import { DurableObject } from "cloudflare:workers";
2820 export class Probe extends DurableObject {
2821 started = crypto.randomUUID();
2822 whoami() {
2823 return "${version}:" + this.started;
2824 }
2825 }
2826 export default {
2827 async fetch(request, env) {
2828 return new Response(await env.Probe.getByName("shared").whoami());
2829 },
2830 };`,
2831 env: { Probe: Cloudflare.DurableObject("Probe") },
2832 codeUpdateStrategy,
2833 });
2834 });
2835 const deferred = { mode: "deferred", maxDelay: "10 minutes" } as const;
2836 const immediate = { mode: "immediate" } as const;
2837
2838 const worker = yield* stack.deploy(program("v1", deferred));
2839 yield* expectUrlContains(worker.url!, "v1:");
2840 const whoami = client.get(worker.url!, { headers: { "cache-control": "no-cache" } }).pipe(
2841 Effect.flatMap(HttpClientResponse.filterStatusOk),
2842 Effect.flatMap((response) => response.text),
2843 );
2844 const v1 = yield* whoami;
2845 expect(v1).toMatch(/^v1:/);
2846
2847 // The strategy applies per deploy: changing only it is not an update.
2848 const plan = yield* stack.plan(program("v1", immediate));
2849 expect(
2850 Object.values(plan.resources).find(
2851 (node) => node.resource.LogicalId === "CodeUpdateStrategyWorker",
2852 )?.action,
2853 ).toBe("noop");
2854
2855 // Deferred: keep the object active through the deploy, and it
2856 // keeps running the code it started with.
2857 const pinger = yield* whoami.pipe(
2858 Effect.ignore,
2859 Effect.repeat(Schedule.spaced("1 second")),
2860 Effect.forkChild,
2861 );
2862 yield* stack.deploy(program("v2", deferred));
2863 const samples = yield* whoami.pipe(
2864 Effect.repeat({ schedule: Schedule.spaced("1 second"), times: 4 }),
2865 Effect.andThen(whoami),
2866 );
2867 yield* Fiber.interrupt(pinger);
2868 expect(samples).toBe(v1);
2869
2870 // Immediate: the object resets onto the new code right away.
2871 yield* stack.deploy(program("v3", immediate));
2872 yield* expectUrlContains(worker.url!, "v3:", { timeout: "30 seconds" });
2873
2874 // Out of range is rejected before anything is uploaded.
2875 const error = yield* stack
2876 .deploy(program("v4", { mode: "deferred", maxDelay: "25 hours" }))
2877 .pipe(Effect.flip);
2878 expect(error).toMatchObject({ _tag: "WorkerCodeUpdateStrategyError" });
2879
2880 yield* stack.destroy();
2881 yield* waitForWorkerToBeDeleted(worker.workerName, accountId);
2882 }).pipe(logLevel),
2883 { tags: ["live"], timeout: 240_000 },
2884 );
2885
2886 test.provider(
2887 "worker.durableObjectNamespaces stability across DO and worker changes",
2888 (stack) =>
2889 // Exercises plan actions for a downstream resource whose props reference
2890 // `worker.durableObjectNamespaces.<ClassName>`. Scenarios:
2891 //
2892 // | Step | Worker | Hook |
2893 // |------------------------------|------------|------------|
2894 // | First deploy (no DO) | create | — |
2895 // | Add first DO + hook | update | create |
2896 // | Worker-only change | update | noop |
2897 // | Add another DO class | update | noop |
2898 // | Remove a DO class | update | update |
2899 // | Worker-only change (restored)| update | noop |
2900 // | Swap DO class (add+remove) | update | noop |
2901 // | Deploy swap + hook follows | (apply) | (apply) |
2902 // | No further changes | noop | noop |
2903 // | Remove last DO class | update | update |
2904 Effect.gen(function* () {
2905 yield* stack.destroy();
2906
2907 type DoClass = "Counter" | "Meter";
2908
2909 const program = (opts: {
2910 crons: string[];
2911 dos: ReadonlyArray<DoClass>;
2912 hookRef: DoClass | null;
2913 }) =>
2914 Effect.gen(function* () {
2915 const bindings: any = {};
2916 if (opts.dos.includes("Counter")) {
2917 bindings.Counter = Cloudflare.DurableObject<Counter>("Counter");
2918 }
2919 if (opts.dos.includes("Meter")) {
2920 bindings.Meter = Cloudflare.DurableObject<Meter>("Meter");
2921 }
2922
2923 const worker = yield* Cloudflare.Worker("Upstream", {
2924 main: doMain,
2925 crons: opts.crons,
2926 compatibility: { date: "2024-09-23" },
2927 bindings,
2928 } as any);
2929
2930 if (opts.hookRef !== null) {
2931 // Embed the DO namespace id in the (real, reachable) worker URL so
2932 // the webhook's live URL validation passes while still depending on
2933 // `durableObjectNamespaces`. The worker responds 200 to any path.
2934 yield* Cloudflare.Alerting.NotificationWebhook("Hook", {
2935 url: Output.interpolate`${worker.url}/${worker.durableObjectNamespaces.pipe(
2936 Output.map((namespaces) => namespaces[opts.hookRef!]),
2937 )}`,
2938 });
2939 }
2940 });
2941
2942 const actionOf = (plan: any, logicalId: string) =>
2943 (Object.values(plan.resources) as any[]).find(
2944 (node: any) => node.resource.LogicalId === logicalId,
2945 )?.action;
2946
2947 // ── First deploy: worker with no DO classes yet ──
2948 const workerOnlyFirstPlan = yield* stack.plan(
2949 program({ crons: [], dos: [], hookRef: null }),
2950 );
2951 expect(actionOf(workerOnlyFirstPlan, "Upstream")).toBe("create");
2952 expect(actionOf(workerOnlyFirstPlan, "Hook")).toBeUndefined();
2953
2954 yield* stack.deploy(program({ crons: [], dos: [], hookRef: null }));
2955
2956 // ── Add the first DO class + hook referencing it ──
2957 const addFirstDoPlan = yield* stack.plan(
2958 program({ crons: [], dos: ["Counter"], hookRef: "Counter" }),
2959 );
2960 expect(actionOf(addFirstDoPlan, "Upstream")).toBe("update");
2961 expect(actionOf(addFirstDoPlan, "Hook")).toBe("create");
2962
2963 yield* stack.deploy(program({ crons: [], dos: ["Counter"], hookRef: "Counter" }));
2964
2965 // ── Worker-only change, same DO set → hook noop ──
2966 const workerOnlyPlan = yield* stack.plan(
2967 program({ crons: ["*/10 * * * *"], dos: ["Counter"], hookRef: "Counter" }),
2968 );
2969 expect(actionOf(workerOnlyPlan, "Upstream")).toBe("update");
2970 expect(actionOf(workerOnlyPlan, "Hook")).toBe("noop");
2971
2972 // ── Add a DO class (Meter) while hook still refs Counter → Counter's
2973 // namespace id is unchanged, so the hook is a noop even though the
2974 // worker must update to register the new class ──
2975 const addDoPlan = yield* stack.plan(
2976 program({ crons: ["*/10 * * * *"], dos: ["Counter", "Meter"], hookRef: "Counter" }),
2977 );
2978 expect(actionOf(addDoPlan, "Upstream")).toBe("update");
2979 expect(actionOf(addDoPlan, "Hook")).toBe("noop");
2980
2981 yield* stack.deploy(
2982 program({ crons: ["*/10 * * * *"], dos: ["Counter", "Meter"], hookRef: "Counter" }),
2983 );
2984
2985 // ── Remove a DO class (Meter) while hook still refs Counter → DO set
2986 // changed, so the hook must re-plan even though Counter's id is
2987 // unchanged in the cloud ──
2988 const removeDoPlan = yield* stack.plan(
2989 program({ crons: ["*/10 * * * *"], dos: ["Counter"], hookRef: "Counter" }),
2990 );
2991 expect(actionOf(removeDoPlan, "Upstream")).toBe("update");
2992 expect(actionOf(removeDoPlan, "Hook")).toBe("update");
2993
2994 yield* stack.deploy(
2995 program({ crons: ["*/10 * * * *"], dos: ["Counter"], hookRef: "Counter" }),
2996 );
2997
2998 // ── Same DO set restored → hook noop on another worker-only change ──
2999 const stableAgainPlan = yield* stack.plan(
3000 program({ crons: [], dos: ["Counter"], hookRef: "Counter" }),
3001 );
3002 expect(actionOf(stableAgainPlan, "Upstream")).toBe("update");
3003 expect(actionOf(stableAgainPlan, "Hook")).toBe("noop");
3004
3005 // ── Swap Counter → Meter (add & remove in one step), hook still refs
3006 // Counter. The worker must update; the hook plans as noop because the
3007 // persisted Counter namespace id is still carried in state until apply ──
3008 const swapDoPlan = yield* stack.plan(
3009 program({ crons: [], dos: ["Meter"], hookRef: "Counter" }),
3010 );
3011 expect(actionOf(swapDoPlan, "Upstream")).toBe("update");
3012 expect(actionOf(swapDoPlan, "Hook")).toBe("noop");
3013
3014 yield* stack.deploy(program({ crons: [], dos: ["Meter"], hookRef: "Meter" }));
3015
3016 // ── No further changes → noop ──
3017 const hookFollowsDoPlan = yield* stack.plan(
3018 program({ crons: [], dos: ["Meter"], hookRef: "Meter" }),
3019 );
3020 expect(actionOf(hookFollowsDoPlan, "Upstream")).toBe("noop");
3021 expect(actionOf(hookFollowsDoPlan, "Hook")).toBe("noop");
3022
3023 // ── Remove the last DO class entirely while hook still refs Meter →
3024 // hook must update (plan-only; URL would be invalid to deploy) ──
3025 const removeLastDoPlan = yield* stack.plan(
3026 program({ crons: [], dos: [], hookRef: "Meter" }),
3027 );
3028 expect(actionOf(removeLastDoPlan, "Upstream")).toBe("update");
3029 expect(actionOf(removeLastDoPlan, "Hook")).toBe("update");
3030
3031 yield* stack.destroy();
3032 }).pipe(logLevel),
3033 { tags: ["provider:cloudflare:alerting", "live"], timeout: 360_000 },
3034 );
3035
3036 test.provider(
3037 "plain worker importing node builtins deploys without explicit compatibility flags",
3038 (stack) =>
3039 Effect.gen(function* () {
3040 const fs = yield* FileSystem.FileSystem;
3041 const path = yield* Path.Path;
3042 const { accountId } = yield* yield* CloudflareEnvironment;
3043
3044 yield* stack.destroy();
3045
3046 // Regression for #796: a plain (external) `export default { fetch }`
3047 // Worker importing `node:crypto`, with NO `compatibility` prop. The
3048 // default `nodejs_compat` must reach both the bundler (so `node:*`
3049 // stays external instead of warning) and the upload metadata (so
3050 // Cloudflare doesn't reject with `No such module "node:crypto"`).
3051 const workerDir = yield* fs.makeTempDirectory({ prefix: "alchemy-worker-node-compat-" });
3052 const workerPath = path.join(workerDir, "worker.ts");
3053 yield* fs.writeFileString(
3054 workerPath,
3055 `import { randomBytes } from "node:crypto";
3056 export default {
3057 fetch: async () =>
3058 new Response("node-compat:" + randomBytes(8).toString("hex")),
3059 };
3060 `,
3061 );
3062
3063 const worker = yield* stack.deploy(
3064 Effect.gen(function* () {
3065 return yield* Cloudflare.Worker("NodeCompatDefault", {
3066 main: workerPath,
3067 workersDev: true,
3068 });
3069 }),
3070 );
3071
3072 yield* expectUrlContains(worker.url!, "node-compat:", {
3073 timeout: "60 seconds",
3074 label: "node:crypto served under default nodejs_compat",
3075 });
3076
3077 yield* stack.destroy();
3078 yield* waitForWorkerToBeDeleted(worker.workerName, accountId);
3079 }).pipe(logLevel),
3080 { tags: ["live"], timeout: 360_000 },
3081 );
3082
3083 test.provider(
3084 "deploys a worker whose main is derived from a Command.Build output",
3085 (stack) =>
3086 Effect.gen(function* () {
3087 const { accountId } = yield* yield* CloudflareEnvironment;
3088 const fs = yield* FileSystem.FileSystem;
3089 const path = yield* Path.Path;
3090
3091 yield* stack.destroy();
3092
3093 // Regression for #1049: `main` computed from another resource's
3094 // output is still an unresolved Output when `precreate` runs on raw
3095 // props — `getCompatibility` (via `isPythonMain`) must tolerate it.
3096 // The entry module only exists after the build command runs, so the
3097 // Worker cannot know its `main` path until `build.outdir` resolves.
3098 const marker = testName("alchemy-output-main-e2e-ok-7c31");
3099 const tempDir = yield* fs.makeTempDirectory({ prefix: "alchemy-output-main-" });
3100 yield* fs.writeFileString(
3101 path.join(tempDir, "worker.src.mjs"),
3102 `export default { fetch: () => new Response(${JSON.stringify(marker)}) };\n`,
3103 );
3104 yield* fs.writeFileString(
3105 path.join(tempDir, "build.sh"),
3106 "mkdir -p dist\ncp worker.src.mjs dist/worker.mjs\n",
3107 );
3108
3109 const worker = yield* stack.deploy(
3110 Effect.gen(function* () {
3111 const build = yield* Command.Build("OutputMainBuild", {
3112 command: "bash build.sh",
3113 cwd: tempDir,
3114 outdir: "dist",
3115 });
3116 return yield* Cloudflare.Worker("OutputMainWorker", {
3117 isExternal: true,
3118 workersDev: true,
3119 // `build.outdir` is persisted relative to the initial cwd —
3120 // resolve it against `initialCwd` (per Build's contract), not
3121 // live `process.cwd()`, which another suite's in-process build
3122 // can transiently chdir away.
3123 main: Output.map(build.outdir, (dir) =>
3124 pathe.resolve(initialCwd, dir, "worker.mjs"),
3125 ),
3126 });
3127 }),
3128 );
3129
3130 expect(worker.url).toBeDefined();
3131 yield* expectUrlContains(worker.url!, marker);
3132
3133 yield* stack.destroy();
3134 yield* waitForWorkerToBeDeleted(worker.workerName, accountId);
3135 }).pipe(logLevel),
3136 { tags: ["live"], timeout: 360_000 },
3137 );
3138 },
3139 );