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

main
ts 6,174 lines 273 KB
Raw
1 import * as crypto from "node:crypto";
2 import * as durableObjectsApi from "@distilled.cloud/cloudflare/durable-objects";
3 import * as rulesets from "@distilled.cloud/cloudflare/rulesets";
4 import * as workers from "@distilled.cloud/cloudflare/workers";
5 import * as wfp from "@distilled.cloud/cloudflare/workers-for-platforms";
6 import { Unowned, Unresolved } from "alchemy/AdoptPolicy";
7 import { dotAlchemyDirectory } from "alchemy/AlchemyContext";
8 import { havePropsChanged, isResolved, stripEffects } from "alchemy/Diff";
9 import * as ProviderLayer from "alchemy/Local/ProviderLayer";
10 import * as Provider from "alchemy/Provider";
11 import type { ScopedPlanStatusSession } from "alchemy/Report";
12 import { type ResourceBinding } from "alchemy/Resource";
13 import { isRedactedMarker } from "alchemy/RuntimeContext";
14 import { Stack } from "alchemy/Stack";
15 import { cachedFunction } from "alchemy/Util/cached-function";
16 import { sha256Object } from "alchemy/Util/sha256";
17 import * as Config from "effect/Config";
18 import * as Data from "effect/Data";
19 import * as Duration from "effect/Duration";
20 import * as Effect from "effect/Effect";
21 import { isHttpClientError } from "effect/http/HttpClientError";
22 import * as Layer from "effect/Layer";
23 import * as Option from "effect/Option";
24 import * as Predicate from "effect/Predicate";
25 import * as Redacted from "effect/Redacted";
26 import * as Schedule from "effect/Schedule";
27 import * as Stream from "effect/Stream";
28 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
29 import {
30 assertBindingContainersOnAsyncClasses,
31 mergeWorkerContainers,
32 } from "../Containers/ContainerConfiguration.ts";
33 import * as DomainVersion from "../Domain/Version.ts";
34 import { localRuntimeServices } from "../LocalRuntime.ts";
35 import { CloudflareLogs } from "../Logs.ts";
36 import { detachQueueConsumersOfScript } from "../Queues/Consumer.ts";
37 import { resolveZoneId, type Reference as ZoneReference } from "../Zone/lookup.ts";
38 import {
39 getAssetsPathPrefix,
40 mergeAssetsConfigFiles,
41 readAssets,
42 readAssetsConfigFiles,
43 uploadAssets,
44 } from "./Assets.ts";
45 import { getCompatibility } from "./Compatibility.ts";
46 import { isDurableObjectExport } from "./DurableObject.ts";
47 import { LocalWorkerProvider } from "./LocalWorkerProvider.ts";
48 import { placeholderResetReason } from "./Placeholder.ts";
49 import { routePatternUrl } from "./RoutePattern.ts";
50 import { isAssetsOnly, makeSourceContext, resolveSource } from "./Source.ts";
51 import { assertCloudflareTelemetryCompatibility } from "./Telemetry.ts";
52 import {
53 Worker,
54 type WorkerProps,
55 type WorkerRouteConfig,
56 type WorkerVersionAffinity,
57 } from "./Worker.ts";
58 import { getCacheBinding, getCronBindings, resolveObservability } from "./WorkerAsyncBindings.ts";
59 import {
60 type WireWorkerBinding,
61 type WorkerBinding,
62 type WorkerSettingsBinding,
63 withoutDevOnlyBindings,
64 } from "./WorkerBinding.ts";
65 import { createWorkerName } from "./WorkerName.ts";
66 class MissingDurableObjects extends Data.TaggedError("MissingDurableObjects")<{
67 scriptName: string;
68 expected: string[];
69 }> {}
70
71 /**
72 * A Durable Object class is being dropped from this Worker while a binding in
73 * the same deploy still references it on another script — the class moved
74 * cross-script, but its namespace (and every stored object in it) still lives
75 * on this Worker. Cloudflare rejects a single upload that both deletes the
76 * class and ships a binding referencing it, and silently deleting would
77 * destroy the namespace's data irreversibly, so the deploy fails before any
78 * upload.
79 *
80 * Moving a Durable Object class between Workers is always declared: set
81 * `transferredFrom` on the Durable Object at its **new host** — naming the
82 * former host by Worker logical id (same stack) or physical script name — and
83 * Alchemy moves the namespace, with its data, on the new host's deploy; this
84 * deploy then converges on its own. To abandon the
85 * data instead, remove the binding entirely in one deploy (which deletes the
86 * class and its data), then add the cross-script binding in a second deploy.
87 */
88 export class DurableObjectTransferRequired extends Data.TaggedError(
89 "DurableObjectTransferRequired",
90 )<{ scriptName: string; className: string; targetScriptName: string | undefined }> {
91 override get message() {
92 return (
93 `Durable Object class '${this.className}' still lives on Worker '${this.scriptName}' but this deploy re-binds it as a cross-script reference` +
94 (this.targetScriptName ? ` to '${this.targetScriptName}'` : "") +
95 ". Durable Object data does NOT move with the class automatically. " +
96 `To move the data, set transferredFrom: "${this.scriptName}" (the former host's script name, or its Worker logical id for same-stack moves) on the Durable Object declaration in its new host Worker. ` +
97 "To abandon the data, remove the binding entirely in one deploy before re-adding it as a cross-script reference."
98 );
99 }
100 }
101
102 /**
103 * More than one script matches the `transferredFrom` declaration of a Durable
104 * Object (e.g. an orphaned script left behind by a `name` prop change still
105 * carries the same alchemy tags, or the host history lists several scripts
106 * that each still hold a same-class namespace). Alchemy refuses to guess
107 * which namespace's data to move — narrow the declaration to the exact
108 * physical script name that holds the data.
109 */
110 export class AmbiguousDurableObjectTransfer extends Data.TaggedError(
111 "AmbiguousDurableObjectTransfer",
112 )<{ scriptName: string; logicalId: string; className: string; sources: string[] }> {
113 override get message() {
114 return (
115 `Durable Object '${this.logicalId}' (class '${this.className}') is new to Worker '${this.scriptName}' and multiple scripts match its transferredFrom declaration: ${this.sources.join(", ")}. ` +
116 `Narrow transferredFrom to the exact physical script name that holds the data.`
117 );
118 }
119 }
120
121 /**
122 * Resolve the Workers for Platforms dispatch-namespace *name* from a resolved
123 * `namespace` prop or persisted attribute. The engine resolves a passed
124 * {@link DispatchNamespace} resource to its Attributes object (see
125 * `Input.Resolve` / Plan.ts), so the value is either the namespace name
126 * string, that attributes object, or `undefined` for a regular Worker.
127 *
128 * @internal
129 */
130 export const resolveNamespaceName = (namespace: unknown): string | undefined => {
131 if (namespace == null) return undefined;
132 if (typeof namespace === "string") return namespace;
133 return (namespace as { name?: string }).name;
134 };
135
136 /**
137 * Resolve a Worker's `tailConsumers` / `streamingTailConsumers` prop into
138 * the wire-shape consumer list
139 * (`[{ service }]`). The engine resolves a passed {@link Worker} to its
140 * Attributes object — possibly stables-only during planning, but
141 * `workerName` is always a stable — so each entry is either a script-name
142 * string or that attributes object. Whole-resource entries are reduced to
143 * the script name alone so hashing/diffing never sees the consumer's
144 * per-deploy fields (`hash`, `url`, ...), mirroring
145 * {@link resolveVersionParentName}.
146 *
147 * An empty array resolves to `[]` (explicitly detach every consumer);
148 * `undefined`/absent resolves to `undefined`.
149 *
150 * This is also the seam for local emulation: the local provider lowers this
151 * same resolved list into workerd's `Worker.tails` / `Worker.streamingTails`
152 * service designators (`RuntimeWorker.tails` / `RuntimeWorker.streamingTails`).
153 *
154 * @internal
155 */
156 export const resolveTailConsumers = (
157 tailConsumers: WorkerProps["tailConsumers" | "streamingTailConsumers"],
158 ): { service: string }[] | undefined => {
159 if (tailConsumers == null) return undefined;
160 return tailConsumers.flatMap((consumer) => {
161 const service =
162 typeof consumer === "string" ? consumer : (consumer as { workerName?: unknown }).workerName;
163 return typeof service === "string" ? [{ service }] : [];
164 });
165 };
166
167 /**
168 * A Worker's `version` configuration is invalid — a prop that can't be
169 * combined with `version.parent` (script-level settings belong to the
170 * parent), a locally-hosted Durable Object / Workflow class on a version
171 * worker, an out-of-range `traffic`, or a gradual rollout that requires
172 * changes the versions API can't carry (assets, DO migrations).
173 */
174 export class WorkerVersionConfigError extends Data.TaggedError("WorkerVersionConfigError")<{
175 message: string;
176 }> {}
177
178 /**
179 * Resolve the parent script *name* from a resolved `version.parent` prop or
180 * persisted props. The engine resolves a passed {@link Worker} (or
181 * `Worker.ref(...)`) to its Attributes object — possibly stables-only during
182 * planning, but `workerName` is always a stable — so the value is either the
183 * script name string, that attributes object, or `undefined`.
184 *
185 * @internal
186 */
187 export const resolveVersionParentName = (version: WorkerProps["version"]): string | undefined => {
188 const parent = version?.parent;
189 if (parent == null) return undefined;
190 if (typeof parent === "string") return parent;
191 const workerName = (parent as { workerName?: unknown }).workerName;
192 return typeof workerName === "string" ? workerName : undefined;
193 };
194
195 /**
196 * A Worker's `preview` configuration is invalid — combined with
197 * `version.parent`, missing `preview.of`, a bad Preview name, or a
198 * script-level setting that belongs to the parent.
199 */
200 export class WorkerPreviewConfigError extends Data.TaggedError("WorkerPreviewConfigError")<{
201 message: string;
202 }> {}
203
204 /**
205 * Resolve the parent script *name* from a resolved `preview.of` prop.
206 *
207 * @internal
208 */
209 export const resolvePreviewParentName = (preview: WorkerProps["preview"]): string | undefined => {
210 const parent = preview?.of;
211 if (parent == null) return undefined;
212 if (typeof parent === "string") return parent;
213 const workerName = (parent as { workerName?: unknown }).workerName;
214 return typeof workerName === "string" ? workerName : undefined;
215 };
216
217 const toPreviewWireKey = (key: string) => key.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`);
218
219 const toPreviewWire = (value: unknown): unknown => {
220 if (Array.isArray(value)) return value.map(toPreviewWire);
221 if (value !== null && typeof value === "object") {
222 return Object.fromEntries(
223 Object.entries(value as Record<string, unknown>).map(([k, v]) => [
224 toPreviewWireKey(k),
225 toPreviewWire(v),
226 ]),
227 );
228 }
229 return value;
230 };
231
232 const previewVerbatimFields = new Set(["json", "algorithm", "keyJwk", "props"]);
233
234 /** Convert Alchemy's binding array into wrangler's Preview `env` map. */
235 const bindingsToPreviewEnv = (bindings: WorkerBinding[]): Record<string, unknown> => {
236 const env: Record<string, unknown> = {};
237 for (const binding of bindings) {
238 const { name, ...rest } = binding as unknown as { name?: unknown } & Record<string, unknown>;
239 if (typeof name !== "string") continue;
240 env[name] = Object.fromEntries(
241 Object.entries(rest).map(([k, v]) => [
242 toPreviewWireKey(k),
243 previewVerbatimFields.has(k) ? v : toPreviewWire(v),
244 ]),
245 );
246 }
247 return env;
248 };
249
250 /**
251 * The traffic percentage a *self-owned* Worker's new version should receive,
252 * or `undefined` for the default full cutover. Only a `version` prop without
253 * a `parent` participates — version workers handle traffic separately.
254 *
255 * @internal
256 */
257 const getSelfRolloutTraffic = (news: WorkerProps): number | undefined => {
258 if (!news.version || news.version.parent != null) return undefined;
259 const traffic = news.version.traffic;
260 return traffic === undefined || traffic >= 100 ? undefined : traffic;
261 };
262
263 const validateTraffic = (traffic: number | undefined) =>
264 traffic !== undefined && (!Number.isFinite(traffic) || traffic < 0 || traffic > 100)
265 ? Effect.fail(
266 new WorkerVersionConfigError({
267 message: `version.traffic must be a percentage between 0 and 100, got ${traffic}`,
268 }),
269 )
270 : Effect.void;
271
272 /** The request header Cloudflare hashes to pin a request to a version. */
273 const AFFINITY_HEADER = "Cloudflare-Workers-Version-Key";
274
275 /**
276 * `version.affinity` normalized to a single key source plus the optional
277 * IP fallback.
278 *
279 * @internal exported for unit testing.
280 */
281 export interface ResolvedVersionAffinity {
282 source:
283 | { kind: "cookie" | "header"; name: string }
284 | { kind: "ip" }
285 | { kind: "key"; expression: string };
286 ipFallback: boolean;
287 }
288
289 // Cookie / header names are interpolated into a double-quoted Rules-language
290 // string literal — restrict them to the token characters real-world names
291 // use so a name can never terminate the literal or smuggle expression text.
292 const AFFINITY_NAME_PATTERN = /^[A-Za-z0-9_.-]+$/;
293
294 /**
295 * Validate `version.affinity` and normalize it to its key source: exactly
296 * one of `cookie` / `header` / `key`, or `ip: true` alone; `ip` combines
297 * with `cookie` / `header` as the absent-source fallback.
298 *
299 * @internal exported for unit testing.
300 */
301 export const resolveVersionAffinity = (
302 affinity: WorkerVersionAffinity,
303 ): Effect.Effect<ResolvedVersionAffinity, WorkerVersionConfigError> =>
304 Effect.gen(function* () {
305 const declared = [
306 ...(affinity.cookie !== undefined ? ["cookie"] : []),
307 ...(affinity.header !== undefined ? ["header"] : []),
308 ...(affinity.key !== undefined ? ["key"] : []),
309 ];
310 if (declared.length > 1) {
311 return yield* new WorkerVersionConfigError({
312 message: `version.affinity accepts exactly one key source, got ${declared.join(" and ")}. Combine sources with a raw \`key\` expression instead.`,
313 });
314 }
315 if (declared.length === 0 && affinity.ip !== true) {
316 return yield* new WorkerVersionConfigError({
317 message:
318 "version.affinity requires a key source: set `cookie`, `header`, `key`, or `ip: true`.",
319 });
320 }
321 if (affinity.key !== undefined && affinity.ip === true) {
322 return yield* new WorkerVersionConfigError({
323 message:
324 "version.affinity: `ip` is the fallback for an absent `cookie`/`header` — a raw `key` expression has no absence condition to fall back from. Fold `ip.src` into the expression instead.",
325 });
326 }
327 for (const [prop, name] of [
328 ["cookie", affinity.cookie],
329 ["header", affinity.header],
330 ] as const) {
331 if (name !== undefined && !AFFINITY_NAME_PATTERN.test(name)) {
332 return yield* new WorkerVersionConfigError({
333 message: `version.affinity.${prop} '${name}' is not a valid ${prop} name: expected only letters, digits, '_', '.', and '-'.`,
334 });
335 }
336 }
337 const source: ResolvedVersionAffinity["source"] =
338 affinity.cookie !== undefined
339 ? { kind: "cookie", name: affinity.cookie }
340 : affinity.header !== undefined
341 ? // Rules-language header map keys are lowercase.
342 { kind: "header", name: affinity.header.toLowerCase() }
343 : affinity.key !== undefined
344 ? { kind: "key", expression: affinity.key }
345 : { kind: "ip" };
346 return {
347 source,
348 ipFallback: affinity.ip === true && (source.kind === "cookie" || source.kind === "header"),
349 };
350 });
351
352 /** A hostname a Worker serves on within one zone. */
353 interface AffinityZoneHost {
354 host: string;
355 /** `true` when `host` came from a route pattern containing `*`. */
356 wildcard: boolean;
357 }
358
359 /**
360 * The `http.host` clause scoping a zone's affinity rules to the Worker's
361 * own hostnames, so unrelated zone traffic — and other Workers' rollouts
362 * on the same zone — never get this Worker's version key.
363 *
364 * @internal exported for unit testing.
365 */
366 export const affinityHostExpression = (hosts: readonly AffinityZoneHost[]): string => {
367 const dedupe = (values: string[]) => [...new Set(values)].sort();
368 const exact = dedupe(hosts.filter((h) => !h.wildcard).map((h) => h.host));
369 const wild = dedupe(hosts.filter((h) => h.wildcard).map((h) => h.host));
370 const clauses = [
371 ...(exact.length === 1
372 ? [`http.host eq "${exact[0]}"`]
373 : exact.length > 1
374 ? [`http.host in {${exact.map((h) => `"${h}"`).join(" ")}}`]
375 : []),
376 ...wild.map((h) => `http.host wildcard "${h}"`),
377 ];
378 return clauses.length === 1 ? clauses[0] : `(${clauses.join(" or ")})`;
379 };
380
381 interface AffinityRuleSpec {
382 description: string;
383 expression: string;
384 /** Rules-language expression producing the header value. */
385 value: string;
386 }
387
388 const affinityRulePrefix = (scriptName: string) => `alchemy:worker:${scriptName}:affinity`;
389
390 /**
391 * The transform rules pinning one zone's traffic: a primary rule filling
392 * the version-key header from the configured source, plus — for
393 * `cookie`/`header` sources with `ip: true` — a fallback rule keying
394 * requests that lack the source by client IP.
395 *
396 * @internal exported for unit testing.
397 */
398 export const buildAffinityZoneRules = (
399 scriptName: string,
400 affinity: ResolvedVersionAffinity,
401 hosts: readonly AffinityZoneHost[],
402 ): AffinityRuleSpec[] => {
403 const prefix = affinityRulePrefix(scriptName);
404 const hostExpr = affinityHostExpression(hosts);
405 const { source } = affinity;
406 if (source.kind === "ip" || source.kind === "key") {
407 return [
408 {
409 description: `${prefix}:key`,
410 expression: hostExpr,
411 value: source.kind === "ip" ? "to_string(ip.src)" : source.expression,
412 },
413 ];
414 }
415 const field =
416 source.kind === "cookie"
417 ? `http.request.cookies["${source.name}"]`
418 : `http.request.headers["${source.name}"]`;
419 return [
420 {
421 description: `${prefix}:key`,
422 expression: `${hostExpr} and len(${field}) > 0`,
423 value: `${field}[0]`,
424 },
425 ...(affinity.ipFallback
426 ? [
427 {
428 // An absent cookie/header is a *missing* value in the Rules
429 // language, and every comparison on missing evaluates false —
430 // `len(field) == 0` can never match. `not (len(field) > 0)`
431 // is the complement that does: missing → false → `not` → true.
432 description: `${prefix}:ip`,
433 expression: `${hostExpr} and not (len(${field}) > 0)`,
434 value: "to_string(ip.src)",
435 },
436 ]
437 : []),
438 ];
439 };
440
441 /**
442 * A Worker's `domain` configuration is invalid — a hostname appears in more
443 * than one role (name/aliases/redirects), or a redirect targets itself.
444 */
445 export class WorkerDomainConfigError extends Data.TaggedError("WorkerDomainConfigError")<{
446 message: string;
447 }> {}
448
449 /**
450 * The resolved shape of `WorkerProps.workersDev`: `enabled` drives the
451 * stable `<name>.<account>.workers.dev` URL, `previewsEnabled` the
452 * per-version preview URLs. The two toggles are independent on the
453 * Cloudflare API.
454 *
455 * @internal exported for unit testing.
456 */
457 export interface ResolvedWorkersDev {
458 enabled: boolean;
459 previewsEnabled: boolean;
460 }
461
462 /**
463 * Resolve the `workersDev` prop to its full shape. `true` / omitted means
464 * "default workers.dev behavior" (stable URL + version previews), `false`
465 * disables both, and the object form fills unset toggles with `true`.
466 *
467 * @internal exported for unit testing.
468 */
469 export const resolveWorkersDev = (workersDev: WorkerProps["workersDev"]): ResolvedWorkersDev => {
470 if (workersDev === undefined || workersDev === true) {
471 return { enabled: true, previewsEnabled: true };
472 }
473 if (workersDev === false) {
474 return { enabled: false, previewsEnabled: false };
475 }
476 return {
477 enabled: workersDev.enabled ?? true,
478 previewsEnabled: workersDev.previewsEnabled ?? true,
479 };
480 };
481
482 /**
483 * The resolved shape of `WorkerProps.domain`: the canonical hostname plus
484 * alias and redirect hostname lists, all punycode-normalized and
485 * de-duplicated.
486 *
487 * @internal exported for unit testing.
488 */
489 export interface ResolvedWorkerDomain {
490 name: string;
491 aliases: string[];
492 redirects: string[];
493 /** Pinned zone from props, when the caller set zoneId / zone / zoneName. */
494 zone?: ZoneReference;
495 /** Serve Worker Previews on this custom domain. */
496 previews?: boolean;
497 }
498
499 const isZoneReference = (value: unknown): value is ZoneReference => {
500 if (typeof value === "string") return true;
501 if (typeof value !== "object" || value === null) return false;
502 const candidate = value as { zoneId?: unknown; name?: unknown };
503 return (
504 typeof candidate.zoneId === "string" &&
505 (candidate.name === undefined || typeof candidate.name === "string")
506 );
507 };
508
509 /** Collapse Worker.domain zone pin fields to one {@link ZoneReference}. */
510 export const resolveWorkerDomainZone = (
511 config:
512 | { readonly zoneId?: unknown; readonly zoneName?: unknown; readonly zone?: unknown }
513 | undefined,
514 ): ZoneReference | undefined => {
515 if (config === undefined) return undefined;
516 if (typeof config.zoneId === "string") return config.zoneId;
517 if (isZoneReference(config.zone)) return config.zone;
518 if (typeof config.zoneName === "string") return config.zoneName;
519 return undefined;
520 };
521
522 /** Whether an existing attachment must move to satisfy an explicit zone pin. */
523 export const shouldRecreateWorkerDomainAttachment = (
524 liveZoneId: string,
525 desiredZoneId: string | undefined,
526 ): boolean => desiredZoneId !== undefined && liveZoneId !== desiredZoneId;
527
528 // After deleting a custom-domain attachment, Cloudflare can briefly retain
529 // ownership of the hostname and reject the replacement with code 100116.
530 const workerDomainConflictSchedule = Schedule.max([
531 Schedule.spaced("2 seconds"),
532 Schedule.recurs(8),
533 ]);
534
535 // Convert non-ASCII hostnames (emoji, IDN, etc.) to punycode so the
536 // Cloudflare API receives the form it stores domains in. `new URL(...)`
537 // does IDNA via WHATWG URL parsing — `📦.alchemy.run` → `xn--5z8h.alchemy.run`.
538 const toPunycode = (hostname: string): string => {
539 try {
540 return new URL(`https://${hostname}`).hostname;
541 } catch {
542 return hostname;
543 }
544 };
545
546 /**
547 * Resolve the `domain` prop to its full shape — a bare string is shorthand
548 * for `{ name }`. Hostnames are punycode-normalized and de-duplicated;
549 * a hostname may only play one role, so aliases/redirects that repeat the
550 * canonical name (or each other) fail with a typed error.
551 *
552 * @internal exported for unit testing.
553 */
554 export const resolveWorkerDomain = (
555 // `string[]` is the pre-redesign prop shape — it can still reach us from
556 // persisted `olds` written by older providers (read's classification).
557 domain: WorkerProps["domain"] | string[],
558 ): Effect.Effect<ResolvedWorkerDomain | undefined, WorkerDomainConfigError> =>
559 Effect.gen(function* () {
560 if (domain === undefined || domain === null) return undefined;
561 // Legacy array form: the first hostname was the primary custom domain
562 // (`url = domains[0]` back then), the rest map to aliases. A legacy
563 // empty array was the explicit detach-all — no domain.
564 const config =
565 typeof domain === "string"
566 ? { name: domain }
567 : Array.isArray(domain)
568 ? domain.length > 0
569 ? { name: domain[0], aliases: domain.slice(1) }
570 : undefined
571 : domain;
572 if (config === undefined) return undefined;
573 const name = toPunycode(config.name);
574 const aliases = Array.from(new Set((config.aliases ?? []).map(toPunycode)));
575 const redirects = Array.from(new Set((config.redirects ?? []).map(toPunycode)));
576 const overlap = [
577 ...aliases.filter((h) => h === name),
578 ...redirects.filter((h) => h === name || aliases.includes(h)),
579 ];
580 if (overlap.length > 0) {
581 return yield* new WorkerDomainConfigError({
582 message: `Each hostname may play only one role in a Worker's domain config; ${[...new Set(overlap)].map((h) => `'${h}'`).join(", ")} appears in more than one of name/aliases/redirects.`,
583 });
584 }
585 const zone = resolveWorkerDomainZone(config);
586 const previews = "previews" in config && config.previews === true ? true : undefined;
587 return {
588 name,
589 aliases,
590 redirects,
591 ...(zone === undefined ? {} : { zone }),
592 ...(previews === undefined ? {} : { previews }),
593 };
594 });
595
596 /**
597 * Preserve the resolved domain metadata only while the declared canonical
598 * hostname is attached. Alias, redirect, and unknown-hostname classification
599 * is supplied by `read`; zone and previews retain reconcile's persisted shape.
600 */
601 const resolveObservedWorkerDomain = (
602 serving: readonly string[],
603 redirects: string[],
604 declared: ResolvedWorkerDomain | undefined,
605 ): ResolvedWorkerDomain | undefined =>
606 serving.length > 0
607 ? {
608 ...(declared?.name === serving[0] ? declared : {}),
609 name: serving[0],
610 aliases: serving.slice(1),
611 redirects,
612 }
613 : undefined;
614
615 const isWorkersDevHostname = (hostname: string) => hostname.endsWith(".workers.dev");
616
617 // Hostnames that only appear in local-dev state (the dev server's
618 // localhost/LAN URLs), never as attachable custom domains.
619 const isLocalDevHostname = (hostname: string) =>
620 hostname === "localhost" || hostname === "::1" || /^\d+\.\d+\.\d+\.\d+$/.test(hostname);
621
622 const urlHostname = (url: string): string => {
623 try {
624 return new URL(url).hostname;
625 } catch {
626 return url;
627 }
628 };
629
630 /** The `rules` payload shape of a zone phase-entrypoint PUT. */
631 type PutZoneRedirectRules = rulesets.PutPhasForZoneRequest["rules"];
632 /** A rule as a zone phase entrypoint read returns it. */
633 type PhaseRule = NonNullable<rulesets.GetPhasResponse["rules"]>[number];
634
635 /**
636 * The *custom domain* hostnames recorded in a Worker's persisted legacy
637 * `domains` state — minus the workers.dev (stable or preview) and local-dev
638 * entries that shared the list in older formats.
639 *
640 * @internal exported for unit testing.
641 */
642 export const stateCustomDomains = (domains: readonly unknown[] | undefined): string[] =>
643 normalizeStateDomains(domains).filter(
644 (hostname) => !isWorkersDevHostname(hostname) && !isLocalDevHostname(hostname),
645 );
646
647 /**
648 * The Worker's persisted domain configuration: the `domain` attribute for
649 * state written by the current format, else re-derived from the legacy
650 * `domains` list (first custom hostname = canonical name, rest = aliases;
651 * legacy state had no redirects).
652 *
653 * @internal exported for unit testing.
654 */
655 export const stateWorkerDomain = (output: object | undefined): ResolvedWorkerDomain | undefined => {
656 const state = output as
657 | {
658 domain?: {
659 name?: unknown;
660 aliases?: unknown[];
661 redirects?: unknown[];
662 zone?: ZoneReference;
663 zoneId?: unknown;
664 zoneName?: unknown;
665 previews?: unknown;
666 } | null;
667 domains?: unknown[];
668 }
669 | undefined;
670 const domain = state?.domain;
671 if (domain && typeof domain.name === "string") {
672 const zone = resolveWorkerDomainZone(domain);
673 return {
674 name: domain.name,
675 aliases: (domain.aliases ?? []).filter((h): h is string => typeof h === "string"),
676 redirects: (domain.redirects ?? []).filter((h): h is string => typeof h === "string"),
677 ...(zone === undefined ? {} : { zone }),
678 ...(domain.previews === true ? { previews: true } : {}),
679 };
680 }
681 const legacy = stateCustomDomains(state?.domains);
682 return legacy.length > 0
683 ? { name: legacy[0], aliases: legacy.slice(1), redirects: [] }
684 : undefined;
685 };
686
687 // Workers for Platforms "user workers" live inside a dispatch namespace and
688 // use a parallel family of script endpoints (`/workers/dispatch/namespaces/
689 // :namespace/scripts/...`). The request/response shapes are identical to the
690 // account-level Workers API for everything the provider touches, so these
691 // helpers route by `dispatchNamespace` and the call sites stay agnostic.
692
693 /**
694 * Read a script's combined settings, routing to the dispatch-namespace
695 * endpoint when `dispatchNamespace` is set. The two response shapes are
696 * structurally identical for the fields the provider consumes (`bindings`,
697 * `tags`, `logpush`), so the WFP response is surfaced as the workers shape.
698 *
699 * @internal
700 */
701 const getScriptSettings = (
702 accountId: string,
703 scriptName: string,
704 dispatchNamespace: string | undefined,
705 ) =>
706 // `Effect.gen` (rather than a ternary) so the two branches unify into a
707 // single `Effect<Settings, WorkersErr | WfpErr>` instead of a *union* of
708 // Effects, which `.pipe`/`catchTag` at the call sites can't consume.
709 Effect.gen(function* () {
710 if (dispatchNamespace) {
711 const settings = yield* wfp.getDispatchNamespaceScriptSetting({
712 accountId,
713 dispatchNamespace,
714 scriptName,
715 });
716 // The dispatch-namespace settings response is structurally identical to
717 // the account-level one for the fields the provider reads.
718 return settings as unknown as workers.GetScriptScriptAndVersionSettingResponse;
719 }
720 return yield* workers.getScriptScriptAndVersionSetting({ accountId, scriptName });
721 });
722
723 /**
724 * Look up a dispatch-namespace script, or `undefined` when it or its
725 * namespace does not exist. The settings endpoint answers a missing
726 * namespace with an untyped 500, so check existence here first.
727 */
728 const findDispatchNamespaceScript = (
729 accountId: string,
730 dispatchNamespace: string,
731 scriptName: string,
732 ) =>
733 wfp
734 .getDispatchNamespaceScript({ accountId, dispatchNamespace, scriptName })
735 .pipe(
736 Effect.catchTag(
737 ["DispatchNamespaceNotFound", "DispatchNamespaceScriptNotFound"],
738 () => Effect.undefined,
739 ),
740 );
741
742 /**
743 * Deploy-time binding validation rejects an upload whose bindings
744 * reference a resource Cloudflare can't see (each resource type has
745 * its own typed not-found error, verified against the live API).
746 * Every bound resource is provisioned before the Worker deploys —
747 * dependency order for KV/R2/D1/queues/etc., a pre-created stub
748 * (which exports the Durable Object classes) for circular
749 * Worker↔Worker references — so a not-found here is either
750 * propagation lag on a just-created resource (a Secrets Store secret
751 * still `pending`, a stub script not yet in the registry) that
752 * retrying converges, or a genuine misconfiguration that keeps
753 * failing and surfaces as the typed error once the bounded budget is
754 * exhausted.
755 */
756 const isBindingTargetNotFound = (
757 e:
758 | Effect.Error<ReturnType<typeof workers.putScript>>
759 | Effect.Error<ReturnType<typeof wfp.putDispatchNamespaceScript>>
760 | Effect.Error<ReturnType<typeof workers.createScriptVersion>>,
761 ): boolean =>
762 e._tag === "SecretsStoreBindingNotFound" ||
763 e._tag === "KVNamespaceNotFound" ||
764 e._tag === "R2BucketNotFound" ||
765 e._tag === "D1DatabaseNotFound" ||
766 e._tag === "QueueNotFound" ||
767 e._tag === "ServiceBindingNotFound" ||
768 e._tag === "DurableObjectClassNotFound" ||
769 e._tag === "HyperdriveConfigNotFound" ||
770 e._tag === "VectorizeIndexNotFound" ||
771 e._tag === "DispatchNamespaceNotFound" ||
772 e._tag === "MtlsCertificateNotFound";
773
774 const bindingTargetNotFoundRetrySchedule = () =>
775 Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(10)]);
776
777 /**
778 * Script PUT is an idempotent upsert, so a pure transport failure (the
779 * request died before any response — e.g. Cloudflare closing a keep-alive
780 * socket that idled while slow upstream resources provisioned earlier in the
781 * deploy) is safe to replay. Errors that carry a response are real API
782 * verdicts and are NOT retried here.
783 */
784 const isScriptPutTransportError = (e: { _tag?: string }): boolean =>
785 isHttpClientError(e) && e.reason._tag === "TransportError";
786
787 const retryableScriptPut = (e: Parameters<typeof isBindingTargetNotFound>[0]): boolean =>
788 isBindingTargetNotFound(e) || isScriptPutTransportError(e);
789
790 /**
791 * Upsert a Worker script, routing to the dispatch-namespace endpoint when
792 * `dispatchNamespace` is set. The metadata/files contract is identical, and
793 * both endpoints run the same binding validation (see
794 * {@link isBindingTargetNotFound}), so both get the same bounded retry.
795 *
796 * @internal
797 */
798 /**
799 * A cached `workerId` attribute usable as the immutable script ID — rules
800 * out the legacy shape (older releases persisted the script *name*), the
801 * `dev:`-marked local identity, and the precreate stub's provisional `""`.
802 */
803 const cachedWorkerId = (value: string | undefined, scriptName: string): string | undefined =>
804 value !== undefined && value !== "" && value !== scriptName && !value.startsWith("dev:")
805 ? value
806 : undefined;
807
808 /**
809 * Whether `output` is a precreate stub that uploaded nothing: a version,
810 * preview, or dispatch-namespace worker's provisional row (`workerId: ""`).
811 * Its `workerName` names no script this resource wrote. Without a recorded
812 * namespace it can't even say which endpoint the attempt targeted — a
813 * dispatch stub's namespace may still have been unresolved — so the
814 * account-level script of that name proves nothing (#2533).
815 */
816 const isUnscopedStub = (output: Worker["Attributes"]): boolean =>
817 output.workerId === "" && !output.namespace;
818
819 export class WorkerIdNotFound extends Data.TaggedError("WorkerIdNotFound")<{
820 scriptName: string;
821 message: string;
822 }> {}
823
824 /**
825 * Resolve a script's immutable Worker ID (carried as `tag` on Cloudflare's
826 * wire) by script name. Neither the settings endpoints nor GET /content
827 * expose it, so scan the account's script listing lazily and stop at the
828 * first match. The listing is eventually consistent, so a missing entry is
829 * retried briefly before failing.
830 */
831 const findWorkerId = (accountId: string, scriptName: string) =>
832 workers.listScripts.items({ accountId }).pipe(
833 Stream.filter((script) => script.id === scriptName),
834 Stream.runHead,
835 Effect.map(Option.getOrUndefined),
836 Effect.flatMap((script) =>
837 script?.tag != null
838 ? Effect.succeed(script.tag)
839 : Effect.fail(
840 new WorkerIdNotFound({
841 scriptName,
842 message: `Cloudflare Worker: could not resolve the immutable ID of script '${scriptName}' from the account listing`,
843 }),
844 ),
845 ),
846 Effect.retry({
847 while: (e) => e._tag === "WorkerIdNotFound",
848 schedule: Schedule.max([Schedule.spaced(2000), Schedule.recurs(3)]),
849 }),
850 );
851
852 export class WorkerCodeUpdateStrategyError extends Data.TaggedError(
853 "WorkerCodeUpdateStrategyError",
854 )<{
855 message: string;
856 }> {}
857
858 /**
859 * Lower `codeUpdateStrategy` to its wire shape: `max_delay` is seconds with
860 * millisecond precision, between 0 and 24 hours, and only `deferred` accepts
861 * it (Cloudflare rejects `max_delay` alongside `immediate`).
862 */
863 const resolveCodeUpdateStrategy = Effect.fn(function* (
864 strategy: WorkerProps["codeUpdateStrategy"],
865 ) {
866 if (strategy === undefined) return undefined;
867 if (strategy.mode === "immediate") {
868 return { mode: "immediate" } satisfies workers.CodeUpdateStrategy;
869 }
870 if (strategy.maxDelay === undefined) {
871 return { mode: "deferred" } satisfies workers.CodeUpdateStrategy;
872 }
873 const maxDelay = Duration.fromInput(strategy.maxDelay).pipe(
874 Option.map((d) => Math.round(Duration.toMillis(d)) / 1000),
875 Option.filter((seconds) => seconds >= 0 && seconds <= 86_400),
876 );
877 if (Option.isNone(maxDelay)) {
878 return yield* new WorkerCodeUpdateStrategyError({
879 message: `codeUpdateStrategy.maxDelay must be a duration between 0 and 24 hours, got ${JSON.stringify(strategy.maxDelay)}.`,
880 });
881 }
882 return { mode: "deferred", maxDelay: maxDelay.value } satisfies workers.CodeUpdateStrategy;
883 });
884
885 export const putWorkerScript = (params: {
886 accountId: string;
887 scriptName: string;
888 dispatchNamespace: string | undefined;
889 metadata: workers.PutScriptRequest["metadata"];
890 files: workers.PutScriptRequest["files"];
891 }) =>
892 Effect.gen(function* () {
893 if (params.dispatchNamespace) {
894 return yield* wfp
895 .putDispatchNamespaceScript({
896 accountId: params.accountId,
897 dispatchNamespace: params.dispatchNamespace,
898 scriptName: params.scriptName,
899 metadata: params.metadata,
900 files: params.files,
901 })
902 .pipe(
903 Effect.retry({
904 while: retryableScriptPut,
905 schedule: bindingTargetNotFoundRetrySchedule(),
906 }),
907 );
908 }
909 return yield* workers
910 .putScript({
911 accountId: params.accountId,
912 scriptName: params.scriptName,
913 metadata: params.metadata,
914 files: params.files,
915 })
916 .pipe(
917 Effect.retry({ while: retryableScriptPut, schedule: bindingTargetNotFoundRetrySchedule() }),
918 );
919 });
920
921 /**
922 * Delete a Worker script, routing to the dispatch-namespace endpoint when
923 * `dispatchNamespace` is set.
924 *
925 * @internal
926 */
927 const deleteWorkerScript = (
928 accountId: string,
929 scriptName: string,
930 dispatchNamespace: string | undefined,
931 ) =>
932 Effect.gen(function* () {
933 if (dispatchNamespace) {
934 return yield* wfp.deleteDispatchNamespaceScript({
935 accountId,
936 dispatchNamespace,
937 scriptName,
938 force: true,
939 });
940 }
941 return yield* workers.deleteScript({ accountId, scriptName, force: true }).pipe(
942 // The script is still registered as a queue consumer (even with
943 // `force`). Normally the sibling Consumer resource detaches first,
944 // but state loss (e.g. a consumer row rewritten by a pre-stamping
945 // dev run) can strand a live consumer pointing at this script with
946 // nothing left to delete it. The script is going away, so any
947 // consumer wiring pointing at it is dead — detach and retry.
948 Effect.catchTag("QueueConsumerConflict", () =>
949 detachQueueConsumersOfScript(accountId, scriptName).pipe(
950 Effect.andThen(workers.deleteScript({ accountId, scriptName, force: true })),
951 ),
952 ),
953 );
954 });
955
956 /**
957 * Normalize a Worker's persisted *legacy* `domains` state to bare
958 * hostnames. Alchemy <= beta.44 stored each custom domain as a
959 * `{ id, hostname, zoneId }` object; beta.45+ stored `https://<hostname>`
960 * URL strings (with the workers.dev URL mixed in); current state stores the
961 * `domain` config object instead of a `domains` list. All legacy
962 * generations coerce to hostnames so the diff never throws on older state
963 * (#546). Entries that fit no generation are dropped rather than turned
964 * into a bogus hostname that would skew the diff.
965 *
966 * @internal exported for unit testing.
967 */
968 export const normalizeStateDomains = (domains: readonly unknown[] | undefined): string[] =>
969 (domains ?? []).flatMap((u) => {
970 if (typeof u === "string") {
971 if (u.includes("://")) {
972 try {
973 return [new URL(u).hostname];
974 } catch {
975 return [];
976 }
977 }
978 return u.length > 0 ? [u] : [];
979 }
980 const hostname = (u as { hostname?: unknown } | null)?.hostname;
981 return typeof hostname === "string" ? [hostname] : [];
982 });
983
984 /**
985 * Custom domains Alchemy is responsible for on this Worker — either declared
986 * on props (`domain`) or already persisted as non-`workers.dev` URLs in state.
987 * Used by `read` to skip `listDomains` when the surface is unmanaged (#926).
988 *
989 * @internal exported for unit testing.
990 */
991 export const shouldObserveWorkerDomains = (
992 olds: Pick<WorkerProps, "domain"> | undefined,
993 output: object | undefined,
994 ): boolean => olds?.domain !== undefined || stateWorkerDomain(output) !== undefined;
995
996 /**
997 * Zone routes Alchemy is responsible for on this Worker. Used by `read` to
998 * skip account-wide zone/route fan-out when the surface is unmanaged (#926).
999 *
1000 * @internal exported for unit testing.
1001 */
1002 export const shouldObserveWorkerRoutes = (
1003 olds: Pick<WorkerProps, "routes"> | undefined,
1004 output: Pick<Worker["Attributes"], "routes"> | undefined,
1005 ): boolean => olds?.routes !== undefined || (output?.routes?.length ?? 0) > 0;
1006
1007 const routeKey = (route: { pattern: string; zoneId: string }) => `${route.zoneId}:${route.pattern}`;
1008
1009 /**
1010 * Order observed zone routes the way state records them. `listRoutes`
1011 * returns routes in Cloudflare's order while `reconcile` records them in
1012 * declared order, and drift compares attributes positionally, so the same
1013 * routes in another order would read as drift. Routes missing from state
1014 * keep their listing order after the known ones.
1015 *
1016 * @internal exported for unit testing.
1017 */
1018 export const orderObservedWorkerRoutes = <Route extends { pattern: string; zoneId: string }>(
1019 observed: readonly Route[],
1020 known: readonly { pattern: string; zoneId: string }[] | undefined,
1021 ): Route[] => {
1022 const position = new Map((known ?? []).map((route, index) => [routeKey(route), index]));
1023 const rank = (route: Route) => position.get(routeKey(route)) ?? position.size;
1024 return [...observed].sort((a, b) => rank(a) - rank(b));
1025 };
1026
1027 /**
1028 * Cron triggers Alchemy is responsible for on this Worker. Used by `read` to
1029 * skip `getScriptSchedule` when the surface is unmanaged (#926). Effect-native
1030 * `cron()` bindings persist into `output.crons` after the first reconcile, so
1031 * subsequent reads still observe them.
1032 *
1033 * @internal exported for unit testing.
1034 */
1035 export const shouldObserveWorkerCrons = (
1036 olds: Pick<WorkerProps, "crons"> | undefined,
1037 output: Pick<Worker["Attributes"], "crons"> | undefined,
1038 ): boolean => olds?.crons !== undefined || (output?.crons?.length ?? 0) > 0;
1039
1040 /**
1041 * Optional override for the account's stable `workers.dev` subdomain
1042 * (`<subdomain>` in `https://<script>.<subdomain>.workers.dev`). When set,
1043 * Worker URL construction skips `GET /accounts/{id}/workers/subdomain`.
1044 */
1045 const CLOUDFLARE_WORKERS_SUBDOMAIN = Config.String("CLOUDFLARE_WORKERS_SUBDOMAIN").pipe(
1046 Config.map((value) => value.trim()),
1047 Config.option,
1048 );
1049
1050 const WORKERS_SUBDOMAIN_PATTERN = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
1051
1052 /**
1053 * Max concurrent `GET /zones/{id}/workers/routes` calls when observing the
1054 * routes attached to a Worker. Route listing is per-zone, so this fans out
1055 * with the number of zones the Worker has routes in; unbounded fan-out here
1056 * is what trips Cloudflare account-level 429 / code 971 throttling (#926).
1057 */
1058 const WORKER_ROUTE_LIST_CONCURRENCY = 8;
1059
1060 type MetadataHashValue =
1061 | string
1062 | number
1063 | boolean
1064 | null
1065 | undefined
1066 | readonly MetadataHashValue[]
1067 | { readonly [key: string]: MetadataHashValue };
1068
1069 /**
1070 * Deeply materialize an arbitrary value into a JSON-stable shape for hashing:
1071 * unwrap `Redacted` secrets by value, ISO-stringify `Date`s, keep plain
1072 * objects/arrays/primitives, and drop Effects, functions, `undefined`, and
1073 * class instances (which don't round-trip through `JSON.stringify`). Redacted
1074 * values contribute by value, not by reference identity, so two
1075 * independently-constructed secrets with the same contents hash identically.
1076 *
1077 * Effects are dropped, never executed: evaluating one here may require
1078 * plan-phase context that is not available inside lifecycle operations.
1079 */
1080 const resolveMetadataHashValue = (value: unknown): Effect.Effect<MetadataHashValue> =>
1081 Effect.gen(function* () {
1082 if (Effect.isEffect(value)) {
1083 return undefined;
1084 }
1085 const resolved = Redacted.isRedacted(value) ? Redacted.value(value) : value;
1086
1087 if (
1088 resolved === null ||
1089 Predicate.isString(resolved) ||
1090 Predicate.isNumber(resolved) ||
1091 Predicate.isBoolean(resolved)
1092 ) {
1093 return resolved;
1094 }
1095 if (resolved === undefined || Predicate.isFunction(resolved)) {
1096 return undefined;
1097 }
1098 if (Predicate.isDate(resolved)) {
1099 return resolved.toISOString();
1100 }
1101 if (Array.isArray(resolved)) {
1102 return yield* Effect.forEach(resolved, (item) => resolveMetadataHashValue(item), {
1103 concurrency: "unbounded",
1104 });
1105 }
1106 if (Predicate.isObject(resolved)) {
1107 // Only plain objects round-trip predictably. A class instance would
1108 // serialize to `{}` (or throw), so drop it rather than hash a lie.
1109 const prototype = Object.getPrototypeOf(resolved);
1110 if (prototype !== Object.prototype && prototype !== null) {
1111 return undefined;
1112 }
1113 const entries = yield* Effect.forEach(
1114 Object.entries(resolved),
1115 ([key, nested]) =>
1116 resolveMetadataHashValue(nested).pipe(
1117 Effect.map((materializedNested) => [key, materializedNested] as const),
1118 ),
1119 { concurrency: "unbounded" },
1120 );
1121 return Object.fromEntries(entries.filter(([, nested]) => nested !== undefined));
1122 }
1123 return undefined;
1124 });
1125
1126 /**
1127 * The deploy-time metadata surface of a Worker whose changes must trigger an
1128 * update but that never touch the bundle/vite/asset-content hashes:
1129 * compatibility, env/bindings, asset routing config, cache, limits, logpush,
1130 * observability, placement, subdomain, and tags. See #745.
1131 */
1132 interface WorkerMetadataHashInput {
1133 readonly props: WorkerProps;
1134 readonly bindings: readonly ResourceBinding<Worker["Binding"]>[];
1135 readonly accountId: string;
1136 readonly stack: { readonly name: string; readonly stage: string };
1137 /**
1138 * The resolved URL a `Worker.URL` (`self_url`) binding lowers into.
1139 * Included in the hash so external URL changes (an account-subdomain
1140 * rename, a custom-domain reorder) redeploy the Worker with the fresh
1141 * value even though props and binding data are unchanged.
1142 */
1143 readonly selfUrl?: string;
1144 }
1145
1146 // The asset router config the resource declares (htmlHandling,
1147 // notFoundHandling, ...), minus the local `directory` path (machine-specific,
1148 // would break hash stability across machines) and the precomputed `hash`
1149 // (already compared via `output.hash.assets`). A bare string `assets` is just
1150 // a directory path, so it contributes nothing here.
1151 const workerAssetConfigForHash = (assets: WorkerProps["assets"]) => {
1152 if (!assets || typeof assets === "string") {
1153 return undefined;
1154 }
1155 const { directory: _directory, ...config } = assets;
1156 if (Predicate.hasProperty(config, "hash")) {
1157 const { hash: _hash, ...configWithoutHash } = config;
1158 return configWithoutHash;
1159 }
1160 return config;
1161 };
1162
1163 /**
1164 * Hash a Worker's deploy-time metadata surface so metadata-only edits are
1165 * detected by the diff (#745). Previously the update decision compared only
1166 * the bundle/vite/asset-content hashes, so a change to e.g. a compatibility
1167 * flag or observability config planned as a noop and silently never deployed.
1168 */
1169 const resolveWorkerMetadataHash = ({
1170 props,
1171 bindings,
1172 accountId,
1173 stack,
1174 selfUrl,
1175 }: WorkerMetadataHashInput): Effect.Effect<string> =>
1176 resolveMetadataHashValue({
1177 accountId,
1178 selfUrl,
1179 stack: { name: stack.name, stage: stack.stage },
1180 compatibility: getCompatibility(props),
1181 // Every `env` entry is lowered into binding data by
1182 // `bindWorkerAsyncBindings`, including literals and VITE_ values. Hash only
1183 // that canonical wire representation. Resource-backed env values can be
1184 // materialized as different attribute projections between reconcile and a
1185 // later plan; hashing props.env as well would turn those irrelevant shape
1186 // differences into perpetual updates.
1187 bindings: bindings.map((binding) => ({ sid: binding.sid, data: binding.data })),
1188 assets: workerAssetConfigForHash(props.assets),
1189 cache: props.cache,
1190 entrypoints: props.entrypoints,
1191 limits: props.limits,
1192 logpush: props.logpush,
1193 observability: props.observability,
1194 placement: props.placement,
1195 // The source descriptor is plain JSON data; hashing it means
1196 // switching providers (or changing provider options) triggers an
1197 // update even when no hash slot the new source computes differs.
1198 source: props.source,
1199 tags: props.tags,
1200 // Reduce each consumer to its script name: a referenced Worker's other
1201 // attributes (hash, url, ...) change on every consumer deploy, which
1202 // would spuriously re-deploy this producer.
1203 tailConsumers: resolveTailConsumers(props.tailConsumers),
1204 streamingTailConsumers: resolveTailConsumers(props.streamingTailConsumers),
1205 workersDev: resolveWorkersDev(props.workersDev),
1206 // Reduce `version.parent` to the parent's script name: the resolved
1207 // parent is a full attributes object whose *other* fields (hash, url,
1208 // ...) change on every parent deploy, which would spuriously re-version
1209 // this Worker even though nothing about the version itself changed.
1210 version: props.version
1211 ? {
1212 parent: resolveVersionParentName(props.version),
1213 traffic: props.version.traffic,
1214 alias: props.version.alias,
1215 affinity: props.version.affinity,
1216 message: props.version.message,
1217 tag: props.version.tag,
1218 }
1219 : undefined,
1220 preview: props.preview
1221 ? {
1222 of: resolvePreviewParentName(props.preview),
1223 name: props.preview.name,
1224 message: props.preview.message,
1225 tag: props.preview.tag,
1226 }
1227 : undefined,
1228 }).pipe(Effect.flatMap((metadata) => sha256Object({ metadata })));
1229
1230 export const WorkerProvider = () =>
1231 ProviderLayer.dual(Worker, {
1232 live: () => LiveWorkerProvider(),
1233 // The local runtime deps (workerd, WorkerProxy, LocalRuntimeState)
1234 // compose INTO the local variant so a live deploy only constructs them
1235 // if the local provider is actually demanded (e.g. deleting a local
1236 // dev worker's state row). See ProviderLayer.dual.
1237 local: () => LocalWorkerProvider().pipe(Layer.provide(localRuntimeServices())),
1238 });
1239
1240 export const LiveWorkerProvider = () =>
1241 Provider.effect(
1242 Worker,
1243 Effect.gen(function* () {
1244 const stack = yield* Stack;
1245 const dotAlchemy = yield* dotAlchemyDirectory;
1246
1247 // const createScriptSubdomain = yield* workers.createScriptSubdomain;
1248 // const deleteScript = yield* workers.deleteScript;
1249 // const getScriptSubdomain = yield* workers.getScriptSubdomain;
1250 // const getScriptSchedule = yield* workers.getScriptSchedule;
1251 // const getScriptSettings = yield* workers.getScriptScriptAndVersionSetting;
1252 // const getSubdomain = yield* workers.getSubdomain;
1253 // const putScript = yield* workers.putScript;
1254 // const putScriptSchedule = yield* workers.putScriptSchedule;
1255 // const putDomain = yield* workers.putDomain;
1256 // const listDomains = yield* workers.listDomains;
1257 // const deleteDomain = yield* workers.deleteDomain;
1258 // const listZones = yield* zones.listZones;
1259 const telemetry = yield* CloudflareLogs;
1260
1261 // Account subdomain is invariant for the life of a provider layer —
1262 // memoize so N Workers (or repeated plan/deploy reads) don't each hit
1263 // GET /accounts/{id}/workers/subdomain and trip Cloudflare's 429/971
1264 // throttle (#926). `CLOUDFLARE_WORKERS_SUBDOMAIN` bypasses the lookup
1265 // entirely when the operator already knows the value.
1266 const getAccountSubdomain = yield* cachedFunction((accountId: string) =>
1267 Effect.gen(function* () {
1268 const configured = yield* CLOUDFLARE_WORKERS_SUBDOMAIN;
1269 if (Option.isSome(configured) && configured.value !== "") {
1270 if (!WORKERS_SUBDOMAIN_PATTERN.test(configured.value)) {
1271 return yield* Effect.die(
1272 new Error(
1273 `Invalid CLOUDFLARE_WORKERS_SUBDOMAIN "${configured.value}": ` +
1274 "expected a workers.dev subdomain label (lowercase letters, digits, hyphens)",
1275 ),
1276 );
1277 }
1278 return configured.value;
1279 }
1280 const result = yield* workers.getSubdomain({ accountId });
1281 return result.subdomain;
1282 }),
1283 );
1284
1285 // Converge the script's workers.dev settings via `POST /subdomain`.
1286 // The two toggles are independent on the Cloudflare API: `enabled`
1287 // drives the stable `<name>.<account>.workers.dev` URL and
1288 // `previews_enabled` the per-version preview URLs.
1289 const setWorkerSubdomain = Effect.fn(function* (name: string, desired: ResolvedWorkersDev) {
1290 const { accountId } = yield* yield* CloudflareEnvironment;
1291 return yield* workers.createScriptSubdomain({
1292 accountId,
1293 scriptName: name,
1294 enabled: desired.enabled,
1295 previewsEnabled: desired.previewsEnabled,
1296 });
1297 });
1298
1299 const normalizeCrons = (crons: string[] | undefined): string[] =>
1300 Array.from(new Set(crons ?? []));
1301
1302 const hasSelfUrlBinding = (bindings: readonly ResourceBinding<Worker["Binding"]>[]) =>
1303 bindings.some((b) => (b.data.bindings ?? []).some((item) => item.type === "self_url"));
1304
1305 // Resolve the URL this Worker will be served at — the same formula that
1306 // produces the `url` attribute (first custom domain in user order, else
1307 // the workers.dev URL) — usable BEFORE the script upload, so `Worker.URL`
1308 // bindings can be lowered into plain_text bindings and VITE_*-prefixed
1309 // env entries can be inlined into the client bundle at build time.
1310 const resolveSelfUrl = Effect.fn(function* (
1311 name: string,
1312 props: WorkerProps,
1313 accountId: string,
1314 ) {
1315 const domain = yield* resolveWorkerDomain(props.domain);
1316 if (domain) {
1317 return `https://${domain.name}`;
1318 }
1319 if (!resolveWorkersDev(props.workersDev).enabled) {
1320 return yield* Effect.die(
1321 `Worker "${name}" binds its own URL (Worker.URL) but has none: the stable workers.dev URL is disabled (workersDev) and no custom domain is configured.`,
1322 );
1323 }
1324 return `https://${name}.${yield* getAccountSubdomain(accountId)}.workers.dev`;
1325 });
1326
1327 const getWorkerCrons = Effect.fn(function* (scriptName: string) {
1328 const { accountId } = yield* yield* CloudflareEnvironment;
1329 return yield* workers.getScriptSchedule({ accountId, scriptName }).pipe(
1330 Effect.map((response) =>
1331 normalizeCrons(response.schedules.map((schedule) => schedule.cron)),
1332 ),
1333 Effect.catchTag("WorkerNotFound", () => Effect.succeed([])),
1334 );
1335 });
1336
1337 const reconcileCrons = (
1338 scriptName: string,
1339 desired: string[],
1340 previous: string[],
1341 session: ScopedPlanStatusSession,
1342 ) =>
1343 Effect.gen(function* () {
1344 const { accountId } = yield* yield* CloudflareEnvironment;
1345 const live = yield* getWorkerCrons(scriptName);
1346 const desiredSorted = [...desired].sort();
1347 const liveSorted = [...live].sort();
1348 const changed =
1349 desiredSorted.length !== liveSorted.length ||
1350 desiredSorted.some((cron, index) => cron !== liveSorted[index]);
1351
1352 if (!changed) return live;
1353
1354 if (desired.length > 0 || previous.length > 0 || live.length > 0) {
1355 yield* session.note(`Reconciling Cron Triggers (${desired.length}) ...`, {
1356 kind: "status",
1357 });
1358 }
1359
1360 const result = yield* workers
1361 .putScriptSchedule({ accountId, scriptName, body: desired.map((cron) => ({ cron })) })
1362 .pipe(
1363 Effect.retry({
1364 while: (error) => error._tag === "WorkerNotFound",
1365 schedule: Schedule.max([Schedule.exponential(200), Schedule.recurs(15)]),
1366 }),
1367 );
1368 return normalizeCrons(result.schedules.map((schedule) => schedule.cron));
1369 });
1370
1371 /**
1372 * Resolve a hostname to a Cloudflare zone id. An explicit pin
1373 * (`zoneId` / zone name / `{ zoneId }`) wins. Otherwise look the
1374 * hostname up with {@link resolveZoneId} (`GET /zones?name=` per
1375 * parent label) — never by listing the account's first page of zones.
1376 */
1377 const inferZoneIdForHostname = (
1378 hostname: string,
1379 zoneCache: Map<string, string>,
1380 zone?: ZoneReference,
1381 ) =>
1382 Effect.gen(function* () {
1383 const cacheKey =
1384 zone === undefined
1385 ? hostname
1386 : `${hostname}:${typeof zone === "string" ? zone : zone.zoneId}`;
1387 const cached = zoneCache.get(cacheKey);
1388 if (cached) return cached;
1389 const { accountId } = yield* yield* CloudflareEnvironment;
1390 const zoneId = yield* resolveZoneId({ accountId, zone, hostname });
1391 zoneCache.set(cacheKey, zoneId);
1392 return zoneId;
1393 });
1394
1395 const reconcileDomains = (
1396 scriptName: string,
1397 desired: string[],
1398 zone?: ZoneReference,
1399 previewsEnabled?: boolean,
1400 ) =>
1401 Effect.gen(function* () {
1402 const { accountId } = yield* yield* CloudflareEnvironment;
1403 // Always query the live state of domains attached to *this*
1404 // Worker rather than trusting `_previous` from local state.
1405 // State may have been wiped, populated by another machine, or
1406 // simply be out of date. Without this we PUT domains that are
1407 // already registered to this same Worker and Cloudflare
1408 // returns a confusing "hostname already in use" error.
1409 const liveAll = yield* workers.listDomains({ accountId, service: scriptName }).pipe(
1410 Effect.map((r) =>
1411 (r.result ?? []).flatMap((d) =>
1412 d.id && d.hostname && d.zoneId
1413 ? [
1414 {
1415 id: d.id,
1416 hostname: d.hostname,
1417 zoneId: d.zoneId,
1418 service: d.service ?? undefined,
1419 previewsEnabled: d.previewsEnabled === true,
1420 },
1421 ]
1422 : [],
1423 ),
1424 ),
1425 Effect.orElseSucceed(() => []),
1426 );
1427
1428 const desiredSet = new Set(desired);
1429 const liveByHostname = new Map(liveAll.map((d) => [d.hostname, d]));
1430
1431 // Detach what's no longer wanted. Use the live list so we
1432 // don't try to delete domains we no longer track.
1433 const toRemove = liveAll.filter((d) => !desiredSet.has(d.hostname));
1434 yield* Effect.forEach(
1435 toRemove,
1436 (d) =>
1437 workers
1438 .deleteDomain({ accountId, domainId: d.id })
1439 .pipe(Effect.catchTag("DomainNotFound", () => Effect.void)),
1440 { concurrency: "unbounded" },
1441 );
1442
1443 if (desired.length === 0) return [];
1444
1445 const zoneCache = new Map<string, string>();
1446
1447 // Attach `hostname` to this Worker. Skip the PUT entirely if
1448 // the hostname is already attached to *this* Worker — that's a
1449 // no-op for Cloudflare and avoids the "already in use" 409.
1450 // If it's attached to a *different* Worker, refuse with a
1451 // clear message rather than silently re-routing traffic.
1452 const attachDomain = Effect.fn(function* (hostname: string) {
1453 const live = liveByHostname.get(hostname);
1454 const desiredZoneId =
1455 zone === undefined
1456 ? undefined
1457 : yield* inferZoneIdForHostname(hostname, zoneCache, zone);
1458 if (
1459 live &&
1460 !shouldRecreateWorkerDomainAttachment(live.zoneId, desiredZoneId) &&
1461 live.previewsEnabled === (previewsEnabled === true)
1462 ) {
1463 return { hostname: live.hostname, id: live.id, zoneId: live.zoneId };
1464 }
1465
1466 if (live) {
1467 // Cloudflare cannot change the zone of an existing custom
1468 // domain in place. Delete only this still-desired attachment,
1469 // then recreate it below with the explicitly requested zone.
1470 yield* workers
1471 .deleteDomain({ accountId, domainId: live.id })
1472 .pipe(Effect.catchTag("DomainNotFound", () => Effect.void));
1473 }
1474
1475 // Not attached to this Worker — but it could still belong
1476 // to another Worker. Check before we try to PUT so we can
1477 // emit a helpful error instead of the raw 409.
1478 const otherOwner = yield* workers.listDomains({ accountId, hostname }).pipe(
1479 Effect.map((r) =>
1480 (r.result ?? []).find((d) => d.hostname === hostname && d.service !== scriptName),
1481 ),
1482 Effect.orElseSucceed(() => undefined),
1483 );
1484 if (otherOwner?.id) {
1485 return yield* Effect.die(
1486 new Error(
1487 `Cannot attach hostname '${hostname}' to Worker '${scriptName}': ` +
1488 `it is already attached to Worker '${otherOwner.service ?? "<unknown>"}'. ` +
1489 `Detach it from that Worker first, or pick a different hostname.`,
1490 ),
1491 );
1492 }
1493
1494 const zoneId = desiredZoneId ?? (yield* inferZoneIdForHostname(hostname, zoneCache));
1495 // Same eventual-consistency window as `setWorkerSubdomain`:
1496 // PUT /accounts/.../workers/domains right after `putScript`
1497 // can return `WorkerNotFound` until Cloudflare's script
1498 // registry has propagated. Retry on that specific tag.
1499 const res = yield* workers
1500 .putDomain({
1501 accountId,
1502 hostname,
1503 service: scriptName,
1504 zoneId,
1505 // Private-beta field — only send it when the user opted
1506 // into custom-domain Previews. Omitting it keeps the
1507 // public PUT /workers/domains body unchanged for everyone
1508 // else.
1509 ...(previewsEnabled === true ? { previewsEnabled: true } : {}),
1510 })
1511 .pipe(
1512 Effect.retry({
1513 while: (error) => error._tag === "WorkerNotFound",
1514 schedule: Schedule.max([Schedule.exponential(200), Schedule.recurs(15)]),
1515 }),
1516 Effect.retry({
1517 while: (error) => error._tag === "HostnameAlreadyInUse",
1518 schedule: workerDomainConflictSchedule,
1519 }),
1520 );
1521 return { hostname, id: res.id ?? "", zoneId: res.zoneId ?? zoneId };
1522 });
1523
1524 const applied = yield* Effect.forEach(desired, attachDomain, {
1525 concurrency: "unbounded",
1526 });
1527 return applied;
1528 });
1529
1530 // The preview URL of the Worker's *current* version:
1531 // `https://<version-prefix>-<name>.<subdomain>.workers.dev`, where the
1532 // prefix is the first 8 characters of the version id (read from the
1533 // latest deployment's majority version). Resolves to `undefined` when
1534 // no deployment is visible yet — callers treat the preview URL as
1535 // best-effort. Only consulted in previews-only mode
1536 // (`workersDev: { enabled: false, previewsEnabled: true }`), where it
1537 // is the Worker's only workers.dev surface.
1538 const getPreviewUrl = Effect.fn(function* (scriptName: string, accountSubdomain: string) {
1539 const { accountId } = yield* yield* CloudflareEnvironment;
1540 const deployments = yield* workers.listScriptDeployments({ accountId, scriptName }).pipe(
1541 Effect.map((response) => response.deployments ?? []),
1542 Effect.orElseSucceed(() => []),
1543 );
1544 const latest = [...deployments].sort((a, b) => b.createdOn.localeCompare(a.createdOn))[0];
1545 const version = latest?.versions?.reduce(
1546 (max, candidate) =>
1547 max === undefined || candidate.percentage > max.percentage ? candidate : max,
1548 undefined as { percentage: number; versionId: string } | undefined,
1549 );
1550 if (!version?.versionId) return undefined;
1551 return `https://${version.versionId.slice(0, 8)}-${scriptName}.${accountSubdomain}.workers.dev`;
1552 });
1553
1554 const computeStableWorkerUrls = Effect.fn(function* (params: {
1555 scriptName: string;
1556 workersDev: ResolvedWorkersDev;
1557 domain: ResolvedWorkerDomain | undefined;
1558 }) {
1559 const { workersDev, domain, scriptName } = params;
1560 const urls: string[] = [];
1561 if (domain) {
1562 urls.push(
1563 `https://${domain.name}`,
1564 ...domain.aliases.map((hostname) => `https://${hostname}`),
1565 );
1566 }
1567 if (workersDev.enabled) {
1568 const { accountId } = yield* yield* CloudflareEnvironment;
1569 const accountSubdomain = yield* getAccountSubdomain(accountId);
1570 urls.push(`https://${scriptName}.${accountSubdomain}.workers.dev`);
1571 }
1572 return urls;
1573 });
1574
1575 /**
1576 * Assemble every URL a deployed, script-owning Worker serves at, most
1577 * significant first — the first entry becomes the `url` attribute:
1578 *
1579 * 1. `https://<domain.name>` — the canonical custom domain
1580 * 2. aliases, in declared order
1581 * 3. the stable workers.dev URL (`workersDev.enabled`)
1582 * 4. preview URLs of the version this deploy uploaded (gradual
1583 * rollouts), or — in previews-only mode — the current version's
1584 * preview URL, which is then the only workers.dev surface
1585 *
1586 * Redirect hostnames never appear: they don't serve the Worker.
1587 * (Version workers don't use this — their `urls` are their preview
1588 * URLs, assembled in `putWorkerVersion`.)
1589 */
1590 const computeWorkerUrls = Effect.fn(function* (params: {
1591 scriptName: string;
1592 workersDev: ResolvedWorkersDev;
1593 domain: ResolvedWorkerDomain | undefined;
1594 /** the version uploaded by this deploy (self-rollout), if any */
1595 uploadedVersionId?: string;
1596 /** user-provided `version.alias` attached to the uploaded version */
1597 uploadedVersionAlias?: string;
1598 }) {
1599 const { workersDev, scriptName } = params;
1600 const urls = yield* computeStableWorkerUrls(params);
1601 if (workersDev.previewsEnabled) {
1602 const { accountId } = yield* yield* CloudflareEnvironment;
1603 const accountSubdomain = yield* getAccountSubdomain(accountId);
1604 if (params.uploadedVersionId !== undefined) {
1605 if (params.uploadedVersionAlias !== undefined) {
1606 urls.push(
1607 `https://${params.uploadedVersionAlias}-${scriptName}.${accountSubdomain}.workers.dev`,
1608 );
1609 }
1610 urls.push(
1611 `https://${params.uploadedVersionId.split("-")[0]}-${scriptName}.${accountSubdomain}.workers.dev`,
1612 );
1613 } else if (!workersDev.enabled) {
1614 const previewUrl = yield* getPreviewUrl(scriptName, accountSubdomain);
1615 if (previewUrl) urls.push(previewUrl);
1616 }
1617 }
1618 return urls;
1619 });
1620
1621 /**
1622 * Converge the rules a Worker owns (descriptions starting with
1623 * `prefix`) in a zone's shared phase entrypoint, one rule at a time:
1624 * create each desired rule that's missing and delete each owned rule
1625 * nothing desires, by rule id. Every other rule in the entrypoint is
1626 * never written. Replacing the whole phase instead loses updates when
1627 * two Workers converge the same zone at once: each writes back the
1628 * other's rules as it last read them, so a rule one of them just
1629 * removed comes back.
1630 */
1631 const syncOwnedPhaseRules = Effect.fn(function* <
1632 Rule extends { readonly description: string; readonly expression: string },
1633 >(params: {
1634 zoneId: string;
1635 phase: "http_request_dynamic_redirect" | "http_request_late_transform";
1636 prefix: string;
1637 desired: ReadonlyArray<Rule>;
1638 /** Whether an owned rule with the same description and expression is `rule`. */
1639 matches: (existing: PhaseRule, rule: Rule) => boolean;
1640 }) {
1641 const { zoneId, phase } = params;
1642 const entrypoint = yield* rulesets
1643 .getPhasForZone({ zoneId, rulesetPhase: phase })
1644 // Only a missing entrypoint means no rules yet. Any other failure
1645 // stops here rather than treating the phase as empty.
1646 .pipe(Effect.catchTag("RulesetNotFound", () => Effect.undefined));
1647 if (entrypoint === undefined) {
1648 if (params.desired.length === 0) return;
1649 yield* rulesets.putPhasForZone({
1650 zoneId,
1651 rulesetPhase: phase,
1652 rules: [...params.desired] as unknown as PutZoneRedirectRules,
1653 });
1654 return;
1655 }
1656 const owned = (entrypoint.rules ?? []).filter((rule) =>
1657 (rule.description ?? "").startsWith(params.prefix),
1658 );
1659 const kept = new Set<string>();
1660 const missing: Rule[] = [];
1661 for (const rule of params.desired) {
1662 const match = owned.find(
1663 (existing) =>
1664 !kept.has(existing.id ?? "") &&
1665 existing.description === rule.description &&
1666 existing.expression === rule.expression &&
1667 params.matches(existing, rule),
1668 );
1669 if (match?.id) kept.add(match.id);
1670 else missing.push(rule);
1671 }
1672 for (const rule of missing) {
1673 yield* rulesets.createRuleForZone({
1674 zoneId,
1675 rulesetId: entrypoint.id,
1676 body: rule as unknown as rulesets.CreateRuleForZoneRequest["body"],
1677 });
1678 }
1679 for (const existing of owned) {
1680 if (existing.id === undefined || existing.id === null || kept.has(existing.id)) continue;
1681 yield* rulesets
1682 .deleteRuleForZone({ zoneId, rulesetId: entrypoint.id, ruleId: existing.id })
1683 .pipe(Effect.catchTag("RulesetRuleNotFound", () => Effect.void));
1684 }
1685 });
1686
1687 /**
1688 * Converge the redirect rules for a Worker's `domain.redirects` in
1689 * each affected zone's `http_request_dynamic_redirect` phase
1690 * entrypoint. Rules are identified by a
1691 * `alchemy:worker:<script>:redirect:<host>` description; only our own
1692 * rules are added/removed — every other rule in the shared entrypoint
1693 * ruleset passes through untouched. Zones that previously held our
1694 * rules but no longer should (removed redirects, removed domain) are
1695 * cleaned the same way.
1696 */
1697 const reconcileRedirectRules = Effect.fn(function* (params: {
1698 scriptName: string;
1699 domain: ResolvedWorkerDomain | undefined;
1700 /** hostname → zoneId for every currently-attached custom domain */
1701 zoneIdByHostname: ReadonlyMap<string, string>;
1702 /** redirect hostnames from previous state (for zone cleanup) */
1703 previousRedirects: readonly string[];
1704 }) {
1705 const prefix = `alchemy:worker:${params.scriptName}:redirect:`;
1706 const desired = params.domain?.redirects ?? [];
1707 const targetName = params.domain?.name;
1708 // Zones to touch: every zone hosting a desired redirect, plus every
1709 // zone that hosted one before (so removals converge). A hostname
1710 // missing from the attached-domain map — the domain list lags a
1711 // fresh attach, or the domain is already detached — is looked up by
1712 // name, so its rule is still removed. Hostnames whose zone can't be
1713 // resolved at all are skipped: dead config at worst, never a failed
1714 // destroy.
1715 const zoneIds = new Set<string>();
1716 const zoneCache = new Map<string, string>();
1717 for (const hostname of [...desired, ...params.previousRedirects]) {
1718 const zoneId =
1719 params.zoneIdByHostname.get(hostname) ??
1720 (yield* inferZoneIdForHostname(hostname, zoneCache, params.domain?.zone).pipe(
1721 Effect.orElseSucceed(() => undefined),
1722 ));
1723 if (zoneId) zoneIds.add(zoneId);
1724 }
1725 if (zoneIds.size === 0) return;
1726 for (const zoneId of zoneIds) {
1727 const ourDesired = desired
1728 .filter((hostname) => params.zoneIdByHostname.get(hostname) === zoneId)
1729 .map((hostname) => ({
1730 action: "redirect" as const,
1731 expression: `http.host eq "${hostname}"`,
1732 description: `${prefix}${hostname}`,
1733 enabled: true,
1734 actionParameters: {
1735 fromValue: {
1736 statusCode: 301,
1737 preserveQueryString: true,
1738 targetUrl: {
1739 expression: `concat("https://${targetName}", http.request.uri.path)`,
1740 },
1741 },
1742 },
1743 }));
1744 // Compare the redirect target too: a changed canonical `name`
1745 // keeps each rule's description and match expression. Fields are
1746 // compared one by one because the read fills unset fields with
1747 // `null`.
1748 yield* syncOwnedPhaseRules({
1749 zoneId,
1750 phase: "http_request_dynamic_redirect",
1751 prefix,
1752 desired: ourDesired,
1753 matches: (existing, rule) => {
1754 const fromValue =
1755 existing.action === "redirect"
1756 ? (
1757 existing as {
1758 actionParameters?: {
1759 fromValue?: {
1760 statusCode?: number | null;
1761 preserveQueryString?: boolean | null;
1762 targetUrl?: { expression?: string | null } | null;
1763 } | null;
1764 } | null;
1765 }
1766 ).actionParameters?.fromValue
1767 : undefined;
1768 const want = rule.actionParameters.fromValue;
1769 return (
1770 fromValue?.targetUrl?.expression === want.targetUrl.expression &&
1771 fromValue?.statusCode === want.statusCode &&
1772 fromValue?.preserveQueryString === want.preserveQueryString
1773 );
1774 },
1775 });
1776 }
1777 });
1778
1779 /**
1780 * Converge the version-affinity transform rules (`version.affinity`)
1781 * in each serving zone's `http_request_late_transform` phase
1782 * entrypoint: `rewrite` rules that fill the
1783 * `Cloudflare-Workers-Version-Key` header from the configured source,
1784 * scoped to the Worker's hostnames in that zone. Rules are identified
1785 * by an `alchemy:worker:<script>:affinity` description prefix; only
1786 * our own rules are added/updated/removed — every other rule in the
1787 * shared entrypoint passes through untouched. Zones that previously
1788 * held our rules but no longer should (affinity removed, zone no
1789 * longer served) are cleaned the same way. Returns the zone ids now
1790 * holding rules, for persistence in `affinityZoneIds`.
1791 */
1792 const reconcileAffinityRules = Effect.fn(function* (params: {
1793 scriptName: string;
1794 /** `undefined` removes every rule (affinity removed / delete). */
1795 desired:
1796 | {
1797 affinity: ResolvedVersionAffinity;
1798 hostsByZone: ReadonlyMap<string, AffinityZoneHost[]>;
1799 }
1800 | undefined;
1801 /** zone ids holding rules per previous state (for cleanup). */
1802 previousZoneIds: readonly string[];
1803 }) {
1804 const prefix = affinityRulePrefix(params.scriptName);
1805 const zoneIds = new Set([
1806 ...(params.desired?.hostsByZone.keys() ?? []),
1807 ...params.previousZoneIds,
1808 ]);
1809 for (const zoneId of zoneIds) {
1810 const hosts = params.desired?.hostsByZone.get(zoneId);
1811 const ourDesired =
1812 params.desired !== undefined && hosts !== undefined
1813 ? buildAffinityZoneRules(params.scriptName, params.desired.affinity, hosts)
1814 : [];
1815 yield* syncOwnedPhaseRules({
1816 zoneId,
1817 phase: "http_request_late_transform",
1818 prefix,
1819 desired: ourDesired.map((rule) => ({
1820 action: "rewrite" as const,
1821 description: rule.description,
1822 enabled: true,
1823 expression: rule.expression,
1824 actionParameters: {
1825 headers: { [AFFINITY_HEADER]: { operation: "set", expression: rule.value } },
1826 },
1827 })),
1828 // The header-value expression of an existing rewrite rule.
1829 // `headers` is an untyped wire record:
1830 // `{ "<Header-Name>": { operation, expression | value } }`.
1831 matches: (existing, rule) => {
1832 const headers = (
1833 existing as {
1834 actionParameters?: { headers?: Record<string, unknown> | null } | null;
1835 }
1836 ).actionParameters?.headers;
1837 const header = headers?.[AFFINITY_HEADER] as { expression?: unknown } | undefined;
1838 return (
1839 header?.expression === rule.actionParameters.headers[AFFINITY_HEADER].expression
1840 );
1841 },
1842 });
1843 }
1844 return [...(params.desired?.hostsByZone.keys() ?? [])].sort();
1845 });
1846
1847 type NormalizedWorkerRoute = { pattern: string; zoneId: string };
1848
1849 // Derive a concrete hostname inside the zone from a route pattern so
1850 // zone inference can walk the DNS label hierarchy. A wildcard label
1851 // (`*.example.com/*`) is replaced with a stand-in label — only the
1852 // parent labels matter for finding the zone.
1853 const hostnameFromPattern = (pattern: string): string => {
1854 const hostPart = pattern.split("/")[0] ?? pattern;
1855 return hostPart.startsWith("*.") ? `routes.${hostPart.slice(2)}` : hostPart;
1856 };
1857
1858 // Resolve each route's zone to a concrete zone id: an explicit
1859 // `zoneId` wins, then `zone` / `zoneName` via `resolveZoneId`, and
1860 // finally inference from the pattern's hostname. Duplicate
1861 // `(zoneId, pattern)` pairs are dropped — Cloudflare enforces one
1862 // route per pattern per zone.
1863 const normalizeRoutes = (routes: WorkerRouteConfig[] | undefined) =>
1864 Effect.gen(function* () {
1865 if (!routes?.length) return [] as NormalizedWorkerRoute[];
1866 const { accountId } = yield* yield* CloudflareEnvironment;
1867 const zoneCache = new Map<string, string>();
1868 const normalized: NormalizedWorkerRoute[] = [];
1869 const seen = new Set<string>();
1870 for (const route of routes) {
1871 const pattern = route.pattern.trim();
1872 const zoneId = route.zoneId
1873 ? route.zoneId
1874 : route.zone || route.zoneName
1875 ? yield* resolveZoneId({
1876 accountId,
1877 zone: route.zone ?? route.zoneName!,
1878 hostname: hostnameFromPattern(pattern),
1879 })
1880 : yield* inferZoneIdForHostname(hostnameFromPattern(pattern), zoneCache);
1881 const key = routeKey({ pattern, zoneId });
1882 if (seen.has(key)) continue;
1883 seen.add(key);
1884 normalized.push({ pattern, zoneId });
1885 }
1886 return normalized;
1887 });
1888
1889 // List the routes attached to `scriptName` across the given zones.
1890 // Routes without an id/pattern or owned by another script are
1891 // ignored. Zones the token can't read are skipped rather than
1892 // failing the whole listing.
1893 const listWorkerRoutesInZones = (scriptName: string, zoneIds: readonly string[]) => {
1894 const uniqueZoneIds = Array.from(new Set(zoneIds));
1895 if (uniqueZoneIds.length === 0) {
1896 return Effect.succeed([] as Worker["Attributes"]["routes"]);
1897 }
1898
1899 const routesByZone = Effect.forEach(
1900 uniqueZoneIds,
1901 (zoneId) =>
1902 workers.listRoutes({ zoneId }).pipe(
1903 Effect.map((response): Worker["Attributes"]["routes"] =>
1904 (response.result ?? []).flatMap((route) =>
1905 route.id && route.pattern && route.script === scriptName
1906 ? [
1907 {
1908 id: route.id,
1909 pattern: route.pattern,
1910 zoneId,
1911 url: routePatternUrl(route.pattern),
1912 },
1913 ]
1914 : [],
1915 ),
1916 ),
1917 Effect.orElseSucceed(() => []),
1918 ),
1919 // Bounded: this issues one request per zone, so a Worker with routes
1920 // spread across many zones would otherwise burst the account's whole
1921 // API budget in a single tick (#926).
1922 { concurrency: WORKER_ROUTE_LIST_CONCURRENCY },
1923 );
1924
1925 return Effect.map(routesByZone, (routes) => routes.flat());
1926 };
1927
1928 // Observe the routes attached to `scriptName` in the zones Alchemy
1929 // already associates with this Worker.
1930 //
1931 // This used to enumerate every zone on the account and then list routes
1932 // in each one. Routes are zone-scoped with no account-level enumeration
1933 // API, so that costs O(zones) requests on *every* Worker read — on an
1934 // account with a few hundred zones a couple of plan/deploy cycles
1935 // exhausts Cloudflare's per-user API budget and unrelated calls start
1936 // coming back 429 / code 971 (#926).
1937 //
1938 // `reconcileRoutes` already scopes itself to the zones implied by
1939 // `desired ∪ previous` rather than sweeping the account, so `read` now
1940 // uses the same bounded zone set: the zones of the routes already
1941 // recorded in state. The blind spot this introduces — a route added out
1942 // of band in a zone this Worker has never had a route in — is the one
1943 // `reconcileRoutes` already has.
1944 const readWorkerRoutes = (
1945 scriptName: string,
1946 knownRoutes: Worker["Attributes"]["routes"] | undefined,
1947 ) =>
1948 listWorkerRoutesInZones(
1949 scriptName,
1950 (knownRoutes ?? []).map((route) => route.zoneId),
1951 ).pipe(Effect.map((routes) => orderObservedWorkerRoutes(routes, knownRoutes)));
1952
1953 // Converge the zone routes attached to `scriptName` to `desired`.
1954 // Observed cloud state (not `previous`) is the diff baseline —
1955 // `previous` only contributes zone ids so routes moved out of a zone
1956 // are still cleaned up after state loss or an interrupted apply.
1957 const reconcileRoutes = (
1958 scriptName: string,
1959 desired: NormalizedWorkerRoute[],
1960 previous: Worker["Attributes"]["routes"],
1961 ) =>
1962 Effect.gen(function* () {
1963 const zoneIds = Array.from(
1964 new Set([
1965 ...desired.map((route) => route.zoneId),
1966 ...previous.map((route) => route.zoneId),
1967 ]),
1968 );
1969 const liveAll = yield* listWorkerRoutesInZones(scriptName, zoneIds);
1970 const desiredKeys = new Set(desired.map(routeKey));
1971 const liveByKey = new Map(liveAll.map((route) => [routeKey(route), route]));
1972
1973 const toRemove = liveAll.filter((route) => !desiredKeys.has(routeKey(route)));
1974 yield* Effect.forEach(
1975 toRemove,
1976 (route) =>
1977 workers
1978 .deleteRoute({ zoneId: route.zoneId, routeId: route.id })
1979 .pipe(Effect.catchTag("RouteNotFound", () => Effect.void)),
1980 { concurrency: "unbounded" },
1981 );
1982
1983 if (desired.length === 0) return [];
1984
1985 const attachRoute = Effect.fn(function* (route: NormalizedWorkerRoute) {
1986 const existing = liveByKey.get(routeKey(route));
1987 if (existing) return existing;
1988
1989 const zoneRoutes = yield* workers.listRoutes({ zoneId: route.zoneId }).pipe(
1990 Effect.map((response) => response.result ?? []),
1991 Effect.orElseSucceed(() => []),
1992 );
1993 const otherOwner = zoneRoutes.find(
1994 (candidate) =>
1995 candidate.pattern === route.pattern &&
1996 candidate.script &&
1997 candidate.script !== scriptName,
1998 );
1999 if (otherOwner) {
2000 return yield* Effect.die(
2001 new Error(
2002 `Cannot attach route '${route.pattern}' to Worker '${scriptName}': ` +
2003 `it is already attached to Worker '${otherOwner.script}'. ` +
2004 `Remove it from that Worker first, or pick a different pattern.`,
2005 ),
2006 );
2007 }
2008
2009 // A duplicate-pattern failure means another actor (or a crashed
2010 // previous reconcile) created the route between our observation
2011 // and now — re-list and converge if it points at this script.
2012 const created = yield* workers
2013 .createRoute({ zoneId: route.zoneId, pattern: route.pattern, script: scriptName })
2014 .pipe(
2015 // Same eventual-consistency window as `putDomain`: creating
2016 // a route right after `putScript` can race Cloudflare's
2017 // script registry, which rejects with code 10019 ("Cannot
2018 // configure a route for a Worker which does not exist") —
2019 // typed as `RouteScriptNotFound` via the createRoute patch.
2020 Effect.retry({
2021 while: (error) => error._tag === "RouteScriptNotFound",
2022 schedule: Schedule.max([Schedule.exponential(200), Schedule.recurs(15)]),
2023 }),
2024 Effect.catchTag("InvalidRoute", (originalError) =>
2025 Effect.gen(function* () {
2026 const match = yield* workers.listRoutes({ zoneId: route.zoneId }).pipe(
2027 Effect.map((response) =>
2028 (response.result ?? []).find(
2029 (candidate) =>
2030 candidate.pattern === route.pattern && candidate.script === scriptName,
2031 ),
2032 ),
2033 Effect.orElseSucceed(() => undefined),
2034 );
2035 if (!match?.id) {
2036 return yield* originalError;
2037 }
2038 return { id: match.id, pattern: match.pattern };
2039 }),
2040 ),
2041 );
2042 return {
2043 id: created.id,
2044 pattern: created.pattern,
2045 zoneId: route.zoneId,
2046 url: routePatternUrl(created.pattern),
2047 };
2048 });
2049
2050 return yield* Effect.forEach(desired, attachRoute, { concurrency: "unbounded" });
2051 });
2052
2053 const createAlchemyWorkerTags = (id: string) => [
2054 `alchemy:stack:${stack.name}`,
2055 `alchemy:stage:${stack.stage}`,
2056 `alchemy:id:${id}`,
2057 ];
2058
2059 const hasAlchemyWorkerTags = (id: string, tags: readonly string[] | undefined) => {
2060 const actualTags = new Set(tags ?? []);
2061 return createAlchemyWorkerTags(id).every((tag) => actualTags.has(tag));
2062 };
2063
2064 /**
2065 * Resolve the source script of a declared Durable Object transfer for
2066 * a class that is new to `selfScriptName`. `sources` is the
2067 * `transferredFrom` host history: each entry names a former host either
2068 * by *physical script name* or by *Worker logical id* in this stack +
2069 * stage (matched via the `alchemy:id:`/stack/stage ownership tags).
2070 * The namespace is transferred from whichever listed host currently
2071 * holds a same-class namespace; when none does (fresh stage, or every
2072 * transfer already completed) this returns `undefined` and the caller
2073 * creates the class fresh — the declaration is inert and safe to keep.
2074 * More than one match (e.g. an orphaned script from a `name` change)
2075 * fails with {@link AmbiguousDurableObjectTransfer} rather than
2076 * guessing whose data to move.
2077 */
2078 const resolveTransferSource = Effect.fn(function* (params: {
2079 accountId: string;
2080 selfScriptName: string;
2081 logicalId: string;
2082 className: string;
2083 sources: readonly string[];
2084 observedNamespaces: readonly ObservedDurableObjectNamespace[];
2085 }) {
2086 if (params.sources.length === 0) {
2087 return undefined;
2088 }
2089 // The class already lives here — e.g. a transfer committed by an
2090 // earlier deploy that stopped before its final upload. Nothing to
2091 // move.
2092 if (
2093 params.observedNamespaces.some(
2094 (ns) => ns.script === params.selfScriptName && ns.class === params.className,
2095 )
2096 ) {
2097 return undefined;
2098 }
2099 const observedScripts = yield* workers.listScripts
2100 .items({ accountId: params.accountId })
2101 .pipe(Stream.runCollect);
2102 const logicalSources = new Set(
2103 observedScripts.flatMap((script) =>
2104 script.id != null &&
2105 params.sources.some((source) => hasAlchemyWorkerTags(source, script.tags ?? []))
2106 ? [script.id]
2107 : [],
2108 ),
2109 );
2110 // Direct names remain candidates even when both listings omit the script.
2111 const candidates = new Set([
2112 ...params.sources,
2113 ...logicalSources,
2114 ...params.observedNamespaces.flatMap((ns) =>
2115 ns.class === params.className ? [ns.script] : [],
2116 ),
2117 ]);
2118 const matched: string[] = [];
2119 for (const script of candidates) {
2120 if (script === params.selfScriptName) continue;
2121 // A same-class namespace alone does not identify a declared source.
2122 const knownSource =
2123 logicalSources.has(script) ||
2124 (params.sources.includes(script) &&
2125 (observedScripts.some((observed) => observed.id === script) ||
2126 params.observedNamespaces.some((ns) => ns.script === script)));
2127 const settings = yield* getScriptSettings(params.accountId, script, undefined).pipe(
2128 Effect.catchTags({
2129 WorkerNotFound: (error) => (knownSource ? Effect.fail(error) : Effect.undefined),
2130 WorkerHasNoVersions: (error) =>
2131 knownSource || params.sources.includes(script)
2132 ? Effect.fail(error)
2133 : Effect.undefined,
2134 }),
2135 );
2136 if (
2137 settings === undefined ||
2138 (!params.sources.includes(script) &&
2139 !logicalSources.has(script) &&
2140 !params.sources.some((source) => hasAlchemyWorkerTags(source, settings.tags ?? [])))
2141 ) {
2142 continue;
2143 }
2144 const localBinding = settings.bindings?.find(
2145 (binding) =>
2146 binding.type === "durable_object_namespace" &&
2147 binding.className === params.className &&
2148 (binding.scriptName == null || binding.scriptName === script),
2149 );
2150 const namespaceId =
2151 localBinding?.type === "durable_object_namespace"
2152 ? (localBinding.namespaceId ?? undefined)
2153 : undefined;
2154 const findNamespace = (namespaces: typeof params.observedNamespaces) =>
2155 namespaces.find((ns) =>
2156 namespaceId === undefined
2157 ? ns.script === script && ns.class === params.className
2158 : ns.id === namespaceId,
2159 );
2160 let namespace = findNamespace(params.observedNamespaces);
2161 if (
2162 namespace === undefined &&
2163 (localBinding !== undefined ||
2164 Object.values(getDurableObjectTagMap(settings.tags ?? [])).includes(params.className))
2165 ) {
2166 // A known source namespace must be located, not replaced with a fresh one.
2167 namespace = yield* listDurableObjectNamespaces(params.accountId).pipe(
2168 Effect.flatMap((namespaces) => {
2169 const namespace = findNamespace(namespaces);
2170 return namespace
2171 ? Effect.succeed(namespace)
2172 : Effect.fail(
2173 new MissingDurableObjects({
2174 scriptName: script,
2175 expected: [params.className],
2176 }),
2177 );
2178 }),
2179 Effect.retry({
2180 while: (error) => error._tag === "MissingDurableObjects",
2181 schedule: Schedule.spaced("2 seconds"),
2182 times: 5,
2183 }),
2184 // The `alchemy:dos:` tag alone is stale on a *former* host: after
2185 // a `transferred_classes` migration Cloudflare rewrites the old
2186 // host's local binding to a className-less reference to the moved
2187 // namespace (left dangling once the new host is deleted), but the
2188 // former host's tags are only rewritten on its next deploy. Such a
2189 // script no longer hosts the class — it is not a transfer source.
2190 // Under `exports` the binding keeps its class name and is
2191 // repointed at the new host instead.
2192 Effect.catchTag("MissingDurableObjects", (error) =>
2193 localBinding === undefined &&
2194 settings.bindings?.some(
2195 (binding) =>
2196 binding.type === "durable_object_namespace" &&
2197 ((!binding.className &&
2198 (binding.scriptName == null || binding.scriptName === script)) ||
2199 (binding.className === params.className &&
2200 binding.scriptName != null &&
2201 binding.scriptName !== script)),
2202 )
2203 ? Effect.undefined
2204 : Effect.fail(error),
2205 ),
2206 );
2207 }
2208 if (namespace?.script === script && namespace.class === params.className) {
2209 matched.push(script);
2210 }
2211 }
2212 if (matched.length > 1) {
2213 return yield* new AmbiguousDurableObjectTransfer({
2214 scriptName: params.selfScriptName,
2215 logicalId: params.logicalId,
2216 className: params.className,
2217 sources: matched,
2218 });
2219 }
2220 return matched[0];
2221 });
2222
2223 const getDurableObjects = (bindings: readonly WorkerSettingsBinding[] | null | undefined) => {
2224 const namespaces = Object.fromEntries(
2225 (bindings ?? []).flatMap((binding) =>
2226 binding.type === "durable_object_namespace" && binding.className && binding.namespaceId
2227 ? [[binding.className, binding.namespaceId]]
2228 : [],
2229 ),
2230 );
2231 return namespaces;
2232 };
2233
2234 const isSecretBinding = (binding: { type: string }) =>
2235 binding.type === "secret_text" || binding.type === "secret_key";
2236
2237 const getSecretNames = (
2238 bindings: readonly { type: string; name: string }[] | null | undefined,
2239 ) =>
2240 (bindings ?? [])
2241 .filter(isSecretBinding)
2242 .map((binding) => binding.name)
2243 .sort();
2244
2245 const getExpectedDurableObjectClassNames = (
2246 bindings: readonly WorkerBinding[] | undefined,
2247 workerName: string,
2248 ) =>
2249 Array.from(
2250 new Set(
2251 bindings?.flatMap((binding) =>
2252 binding.type === "durable_object_namespace" &&
2253 binding.className &&
2254 (binding.scriptName === undefined || binding.scriptName === workerName)
2255 ? [binding.className]
2256 : [],
2257 ) ?? [],
2258 ),
2259 );
2260
2261 const getWorkerSettingsWithDurableObjects = Effect.fn(function* (
2262 scriptName: string,
2263 expectedClassNames: readonly string[],
2264 dispatchNamespace?: string,
2265 ) {
2266 const { accountId } = yield* yield* CloudflareEnvironment;
2267 return yield* getScriptSettings(accountId, scriptName, dispatchNamespace).pipe(
2268 Effect.flatMap((settings) => {
2269 const namespaces = getDurableObjects(settings.bindings);
2270 const missing = expectedClassNames.filter((className) => !namespaces[className]);
2271 if (missing.length > 0) {
2272 return Effect.fail(new MissingDurableObjects({ scriptName, expected: missing }));
2273 }
2274 return Effect.succeed({ settings, durableObjectNamespaces: namespaces });
2275 }),
2276 Effect.retry({
2277 // `MissingDurableObjects`: the DO bindings haven't
2278 // surfaced in the version settings yet. `WorkerHasNoVersions` /
2279 // `WorkerNotFound`: right after the first `putScript`, the
2280 // version-settings read can race the script registry — under a
2281 // busy account this read can briefly 404 with "has no versions"
2282 // (or the worker itself as not-yet-found) before the upload
2283 // propagates. All three are eventual-consistency blips.
2284 while: (error) =>
2285 error._tag === "MissingDurableObjects" ||
2286 error._tag === "WorkerHasNoVersions" ||
2287 error._tag === "WorkerNotFound" ||
2288 error._tag === "DispatchNamespaceScriptNotFound" ||
2289 error._tag === "DispatchNamespaceNotFound",
2290 schedule: Schedule.max([Schedule.exponential(100), Schedule.recurs(20)]),
2291 }),
2292 );
2293 });
2294
2295 const prepareAssets = Effect.fn(function* (assets: WorkerProps["assets"]) {
2296 if (!assets) {
2297 return undefined;
2298 }
2299
2300 if (typeof assets === "object" && "hash" in assets) {
2301 const { hash: _, ...config } = assets;
2302 return yield* readAssets(config);
2303 }
2304
2305 // Framework sources supply the directory; routing-only config has no files to read.
2306 if (typeof assets === "object" && assets.directory === undefined) {
2307 return undefined;
2308 }
2309
2310 // Handle string path or AssetsProps
2311 return yield* readAssets(typeof assets === "string" ? { directory: assets } : assets);
2312 });
2313
2314 const prepareAssetsAndBundle = (
2315 id: string,
2316 fqn: string,
2317 workerName: string,
2318 props: WorkerProps,
2319 opts: { skipAssetsRead?: boolean; selfUrl?: string } = {},
2320 ) =>
2321 Effect.gen(function* () {
2322 // Assets-only Worker: no entry module at all. The script PUT goes
2323 // out with no modules and no main_module — Cloudflare's asset
2324 // layer serves every request and applies `notFoundHandling`
2325 // (including SPA fallback) itself, exactly like Wrangler's
2326 // assets-only deploys.
2327 if (isAssetsOnly(props)) {
2328 if (!props.assets) {
2329 return yield* Effect.die(
2330 new Error(
2331 `Worker "${id}" has no main, script, or assets. Provide an entry module (main / script) or an assets directory to deploy an assets-only Worker.`,
2332 ),
2333 );
2334 }
2335 return {
2336 assets: opts.skipAssetsRead ? undefined : yield* prepareAssets(props.assets),
2337 bundle: undefined,
2338 input: undefined,
2339 additionalWorkspaces: undefined,
2340 };
2341 }
2342 // Every other Worker builds through its source provider (see
2343 // `resolveSource`): it supplies the bundle, optionally its own
2344 // assets (framework and vite builds), and the hash slots it owns.
2345 // The props-level `assets` directory is read here for sources
2346 // that don't own assets.
2347 const source = yield* resolveSource(props);
2348 const ctx = makeSourceContext({
2349 dotAlchemy,
2350 id,
2351 fqn,
2352 workerName,
2353 props,
2354 compatibility: getCompatibility(props),
2355 stack: { name: stack.name, stage: stack.stage },
2356 selfUrl: opts.selfUrl,
2357 });
2358 const [output, propsAssets] = yield* Effect.all(
2359 [
2360 source.build(ctx),
2361 source.ownsAssets || opts.skipAssetsRead
2362 ? Effect.undefined
2363 : prepareAssets(props.assets),
2364 ],
2365 { concurrency: "unbounded" },
2366 );
2367 return {
2368 assets: output.assets ?? propsAssets,
2369 bundle: output.bundle,
2370 input: output.hash.input,
2371 additionalWorkspaces: output.hash.additionalWorkspaces,
2372 };
2373 }).pipe(
2374 Effect.map(({ assets, bundle, input, additionalWorkspaces }) => ({
2375 assets,
2376 bundle: {
2377 main: bundle?.files[0].path,
2378 files: bundle?.files.map(
2379 (file) =>
2380 new File([file.content as BlobPart], file.path, {
2381 type: contentTypeForModule(file.path, file.type),
2382 }),
2383 ),
2384 },
2385 hash: {
2386 assets: assets?.hash,
2387 bundle: bundle?.hash,
2388 input,
2389 additionalWorkspaces,
2390 } satisfies Worker["Attributes"]["hash"],
2391 })),
2392 );
2393
2394 const normalizePrebuiltAssets = (
2395 assets: WorkerProps["assets"],
2396 output: Worker["Attributes"] | undefined,
2397 ) => {
2398 // An explicitly-undefined `hash` (`{ directory, hash: maybe }`) is
2399 // the hash-less shape, not a supplied hash — the same rule
2400 // `assetsChanged` applies during diff. Without the `undefined` check
2401 // a greenfield create (`output === undefined`) compares `undefined
2402 // === undefined`, sets `skip`, and uploads a Worker with no assets.
2403 if (!Predicate.hasProperty(assets, "hash") || assets.hash === undefined) {
2404 return undefined;
2405 }
2406 // `base` shapes the uploaded manifest paths (see `readAssets`); it
2407 // is alchemy-only and must not leak into the API's asset config.
2408 const { directory, hash, base, ...config } = assets;
2409 // `base` re-keys the manifest without changing the build output, so
2410 // a caller-supplied hash alone would let the skip path carry a
2411 // stale root-keyed manifest forward across a `base` change. Salt
2412 // the stored/compared hash with the prefix; unprefixed deploys keep
2413 // their existing hashes.
2414 const pathPrefix = getAssetsPathPrefix(base);
2415 const effectiveHash = pathPrefix ? `${hash}#base=${pathPrefix}` : hash;
2416 return {
2417 directory,
2418 config,
2419 hash: effectiveHash,
2420 skip: effectiveHash === output?.hash?.assets,
2421 };
2422 };
2423
2424 /**
2425 * Merge `Worker["Binding"].env` from active bindings into `news.env`.
2426 * Stack-level `worker.bind({ env })` is how a later resource (webhook
2427 * secret, etc.) attaches env without the Worker init depending on it.
2428 */
2429 const secretTextFromEnvValue = (value: unknown): string | undefined => {
2430 if (Redacted.isRedacted(value)) {
2431 const inner = Redacted.value(value);
2432 return typeof inner === "string" ? inner : undefined;
2433 }
2434 if (isRedactedMarker(value) && typeof value.value === "string") {
2435 return value.value;
2436 }
2437 return undefined;
2438 };
2439
2440 const newsWithBoundEnv = (
2441 news: WorkerProps,
2442 bindings: readonly ResourceBinding<Worker["Binding"]>[],
2443 ): { news: WorkerProps; boundKeys: string[] } => {
2444 const bound: Record<string, any> = {};
2445 for (const binding of bindings) {
2446 if ((binding as { action?: string }).action === "delete") continue;
2447 if (binding.data?.env) Object.assign(bound, binding.data.env);
2448 }
2449 const boundKeys = Object.keys(bound);
2450 if (boundKeys.length === 0) return { news, boundKeys };
2451 return { news: { ...news, env: { ...news.env, ...bound } }, boundKeys };
2452 };
2453
2454 /**
2455 * Append the standard Alchemy runtime bindings plus the user's `env`
2456 * entries (routed by shape: `Redacted` → secret_text, string →
2457 * plain_text, everything else → json) to a metadata binding list.
2458 * Shared between the full script upload and the version upload.
2459 */
2460 const appendAlchemyAndEnvBindings = (
2461 metadataBindings: WorkerBinding[],
2462 news: WorkerProps,
2463 accountId: string,
2464 workerName: string,
2465 ) => {
2466 metadataBindings.push(
2467 { type: "plain_text", name: "ALCHEMY_PHASE", text: "runtime" },
2468 { type: "plain_text", name: "ALCHEMY_WORKER_NAME", text: workerName },
2469 { type: "plain_text", name: "ALCHEMY_STACK_NAME", text: stack.name },
2470 { type: "plain_text", name: "ALCHEMY_STAGE", text: stack.stage },
2471 { type: "plain_text", name: "ALCHEMY_CLOUDFLARE_ACCOUNT_ID", text: accountId },
2472 );
2473 // Add environment variables as metadata bindings
2474 if (news.env) {
2475 for (const [key, value] of Object.entries(news.env)) {
2476 if (value === undefined) continue;
2477 if (metadataBindings.some((b) => b.name === key)) continue;
2478 const secretText = secretTextFromEnvValue(value);
2479 if (secretText !== undefined) {
2480 metadataBindings.push({ type: "secret_text", name: key, text: secretText });
2481 } else if (typeof value === "string") {
2482 metadataBindings.push({ type: "plain_text", name: key, text: value });
2483 } else {
2484 metadataBindings.push({ type: "json", name: key, json: value });
2485 }
2486 }
2487 }
2488 };
2489
2490 /**
2491 * Create a deployment routing `traffic`% to `versionId`, with the
2492 * remainder staying on the currently-live version (the
2493 * highest-percentage version of the script's latest deployment).
2494 * `traffic >= 100` — or a script with no other live version to split
2495 * against — deploys the new version at 100%.
2496 */
2497 const deployVersionTraffic = Effect.fn(function* (params: {
2498 accountId: string;
2499 scriptName: string;
2500 versionId: string;
2501 traffic: number;
2502 message: string | undefined;
2503 codeUpdateStrategy: workers.CodeUpdateStrategy | undefined;
2504 }) {
2505 const { accountId, scriptName, versionId, traffic } = params;
2506 const resolveSplit = Effect.gen(function* () {
2507 if (traffic >= 100) {
2508 return [{ versionId, percentage: 100 }];
2509 }
2510 const { deployments } = yield* workers.listScriptDeployments({ accountId, scriptName });
2511 // Deployments are returned newest-first; the live version is the
2512 // highest-percentage version of the most recent deployment.
2513 const stable = deployments[0]?.versions
2514 .filter((v) => v.versionId !== versionId)
2515 .sort((a, b) => b.percentage - a.percentage)[0];
2516 if (!stable) {
2517 // Nothing to split against (first deployment of this script).
2518 return [{ versionId, percentage: 100 }];
2519 }
2520 return [
2521 { versionId, percentage: traffic },
2522 { versionId: stable.versionId, percentage: 100 - traffic },
2523 ];
2524 });
2525 const split = yield* resolveSplit;
2526 const deployment = yield* workers.createScriptDeployment({
2527 accountId,
2528 scriptName,
2529 strategy: "percentage",
2530 versions: split,
2531 annotations: params.message ? { workersMessage: params.message } : undefined,
2532 codeUpdateStrategy: params.codeUpdateStrategy,
2533 });
2534 return deployment.id;
2535 });
2536
2537 /**
2538 * Resolve the preview-URL alias for a version worker: the
2539 * user-provided `version.alias` (validated against Cloudflare's
2540 * naming rules), or an alias derived from the stack, stage, and
2541 * logical id — stable across deploys, so the aliased preview URL
2542 * (`<alias>-<script>.<subdomain>.workers.dev`) is a durable link
2543 * that always points at the latest uploaded version. Returns
2544 * `undefined` when the parent's script name leaves no room in the
2545 * 63-character DNS label and no explicit alias was given.
2546 */
2547 const resolveVersionAlias = Effect.fn(function* (
2548 id: string,
2549 news: WorkerProps,
2550 parentName: string,
2551 ) {
2552 // `<alias>-<script name>` is a single DNS label (≤ 63 chars).
2553 const budget = 63 - parentName.length - 1;
2554 const userAlias = news.version?.alias;
2555 if (userAlias !== undefined) {
2556 if (!/^[a-z][a-z0-9-]*$/.test(userAlias)) {
2557 return yield* new WorkerVersionConfigError({
2558 message: `version.alias '${userAlias}' is invalid: aliases must start with a lowercase letter and contain only lowercase letters, digits, and dashes.`,
2559 });
2560 }
2561 if (userAlias.length > budget) {
2562 return yield* new WorkerVersionConfigError({
2563 message: `version.alias '${userAlias}' is too long: '<alias>-${parentName}' must fit in a 63-character DNS label, leaving ${Math.max(budget, 0)} characters for the alias.`,
2564 });
2565 }
2566 return userAlias;
2567 }
2568 if (budget < 4) {
2569 return undefined;
2570 }
2571 // Deterministic per (stack, stage, id) — survives updates AND
2572 // replacements so the aliased preview URL never moves. A short
2573 // hash disambiguates different stacks/stages whose readable
2574 // prefixes collide after truncation.
2575 const hash = yield* Effect.sync(() =>
2576 crypto
2577 .createHash("sha256")
2578 .update(`${stack.name}/${stack.stage}/${id}`)
2579 .digest("hex")
2580 .slice(0, 6),
2581 );
2582 const readable = `${stack.stage}-${id}`
2583 .toLowerCase()
2584 .replace(/[^a-z0-9-]+/g, "-")
2585 .replace(/^-+|-+$/g, "");
2586 const alias = [readable, hash]
2587 .filter((part) => part.length > 0)
2588 .join("-")
2589 .slice(0, budget)
2590 .replace(/-+$/, "");
2591 return /^[a-z]/.test(alias) ? alias : `v${alias}`.slice(0, budget);
2592 });
2593
2594 /**
2595 * The parent's workers.dev preview settings + account subdomain,
2596 * fetched once per version reconcile. Preview URLs (aliased and
2597 * versioned) only serve when the parent has previews enabled.
2598 */
2599 const resolveVersionPreviewContext = Effect.fn(function* (
2600 accountId: string,
2601 scriptName: string,
2602 ) {
2603 const subdomain = yield* workers.getScriptSubdomain({ accountId, scriptName }).pipe(
2604 Effect.orElseSucceed((): workers.GetScriptSubdomainResponse => ({
2605 enabled: false,
2606 previewsEnabled: false,
2607 })),
2608 );
2609 const accountSubdomain = yield* getAccountSubdomain(accountId);
2610 return { previewsEnabled: subdomain.previewsEnabled === true, accountSubdomain };
2611 });
2612
2613 /**
2614 * Reject props that can't ride along on a *version worker*
2615 * (`version.parent` set). A version carries only code, bindings, and
2616 * compatibility settings; everything script-level belongs to the
2617 * parent and must not be mutated from a version resource. Locally
2618 * hosted Durable Object / Workflow classes are rejected because their
2619 * migrations would apply to the parent script when the version
2620 * deploys.
2621 */
2622 const validateVersionWorkerProps = Effect.fn(function* (
2623 news: WorkerProps,
2624 bindings: ResourceBinding<Worker["Binding"]>[],
2625 parentName: string,
2626 ) {
2627 const forbidden = (
2628 [
2629 ["name", news.name],
2630 ["namespace", news.namespace],
2631 ["crons", news.crons],
2632 ["tailConsumers", news.tailConsumers],
2633 ["streamingTailConsumers", news.streamingTailConsumers],
2634 ["domain", news.domain],
2635 ["routes", news.routes],
2636 ["tags", news.tags],
2637 ["logpush", news.logpush],
2638 ["observability", news.observability],
2639 ["placement", news.placement],
2640 ["limits", news.limits],
2641 ["workersDev", news.workersDev],
2642 ["access", news.access],
2643 ["vite", news.vite],
2644 ] as const
2645 ).flatMap(([key, value]) => (value !== undefined ? [key] : []));
2646 if (forbidden.length > 0) {
2647 return yield* new WorkerVersionConfigError({
2648 message:
2649 `version.parent uploads a version of '${parentName}' — script-level settings belong to the parent Worker and cannot be set here: ${forbidden.join(", ")}. ` +
2650 `Remove ${forbidden.length === 1 ? "this prop" : "these props"} or configure ${forbidden.length === 1 ? "it" : "them"} on the parent.`,
2651 });
2652 }
2653 yield* validateTraffic(news.version?.traffic);
2654 const cronBindings = getCronBindings(bindings);
2655 if (cronBindings.length > 0) {
2656 return yield* new WorkerVersionConfigError({
2657 message: `Cron Triggers are script-level settings and cannot be registered from a version of '${parentName}'. Configure crons on the parent Worker.`,
2658 });
2659 }
2660 // Any locally-hosted DO class (a durable_object_namespace binding
2661 // without a foreign scriptName) or DO/Workflow export would require
2662 // migrations, which the versions API can't carry — and which would
2663 // mutate the parent's namespaces.
2664 const hostedClasses = getDurableObjectBindings(bindings, parentName);
2665 const exportedClasses = Object.keys(news.exports ?? {});
2666 if (hostedClasses.length > 0 || exportedClasses.length > 0) {
2667 return yield* new WorkerVersionConfigError({
2668 message: `A version of '${parentName}' cannot host Durable Object or Workflow classes (${[
2669 ...new Set([...hostedClasses.map((c) => c.className), ...exportedClasses]),
2670 ].join(
2671 ", ",
2672 )}): Durable Object and Workflow classes belong to the parent script. Host the classes on the parent Worker and reference them cross-script instead.`,
2673 });
2674 }
2675 });
2676
2677 /**
2678 * Reconcile a *version worker*: upload this Worker's code + bindings
2679 * as an immutable version of the parent's script (no script of its
2680 * own), then optionally shift `version.traffic`% of the parent's
2681 * traffic to it. Idempotent in the reconciler sense: every run
2682 * converges cloud state to "the parent's script has a version with
2683 * exactly this content, receiving exactly this traffic" — re-running
2684 * with changed content simply uploads the next immutable version.
2685 */
2686 const putWorkerVersion = Effect.fn(function* (
2687 id: string,
2688 fqn: string,
2689 news: WorkerProps,
2690 bindings: ResourceBinding<Worker["Binding"]>[],
2691 session: ScopedPlanStatusSession,
2692 output: Worker["Attributes"] | undefined,
2693 ) {
2694 ({ news } = newsWithBoundEnv(news, bindings));
2695 const { accountId } = yield* yield* CloudflareEnvironment;
2696 const version = news.version!;
2697 const parentName = resolveVersionParentName(version);
2698 if (parentName === undefined) {
2699 return yield* new WorkerVersionConfigError({
2700 message: `version.parent did not resolve to a Worker script name. Pass a Worker (e.g. \`yield* Cloudflare.Worker.ref(id, { stage })\`) or a literal script name.`,
2701 });
2702 }
2703 yield* validateVersionWorkerProps(news, bindings, parentName);
2704 const traffic = version.traffic ?? 0;
2705 // Resolve the alias and preview context BEFORE the upload: the
2706 // aliased preview URL (`<alias>-<script>.<subdomain>.workers.dev`)
2707 // is deterministic ahead of time — unlike the versioned URL, whose
2708 // prefix comes from the server-assigned version id — which is what
2709 // lets a `Worker.URL` (self_url) binding be baked into the
2710 // version's own bindings.
2711 const alias = yield* resolveVersionAlias(id, news, parentName);
2712 const { previewsEnabled, accountSubdomain } = yield* resolveVersionPreviewContext(
2713 accountId,
2714 parentName,
2715 );
2716 const aliasedUrl =
2717 alias !== undefined && previewsEnabled
2718 ? `https://${alias}-${parentName}.${accountSubdomain}.workers.dev`
2719 : undefined;
2720 const selfUrl = hasSelfUrlBinding(bindings) ? aliasedUrl : undefined;
2721 if (hasSelfUrlBinding(bindings) && selfUrl === undefined) {
2722 return yield* new WorkerVersionConfigError({
2723 message: previewsEnabled
2724 ? `A version of '${parentName}' binds its own URL (Worker.URL), but no preview alias fits: '<alias>-${parentName}' must stay within a 63-character DNS label. Set a short version.alias or shorten the parent's name.`
2725 : `A version of '${parentName}' binds its own URL (Worker.URL), but the parent's workers.dev previews are disabled — a version's URL is its aliased preview URL. Enable the parent's workers.dev subdomain (url: true, the default).`,
2726 });
2727 }
2728 yield* Effect.logInfo(
2729 `Cloudflare Worker version: preparing bundle for ${parentName} (from ${id})`,
2730 );
2731 const {
2732 assets,
2733 bundle,
2734 hash: preparedHash,
2735 } = yield* prepareAssetsAndBundle(id, fqn, parentName, news, { skipAssetsRead: false });
2736 const metadataHash = yield* resolveWorkerMetadataHash({
2737 props: news,
2738 bindings,
2739 accountId,
2740 stack: { name: stack.name, stage: stack.stage },
2741 selfUrl,
2742 });
2743 const hash = {
2744 ...preparedHash,
2745 metadata: metadataHash,
2746 } satisfies Worker["Attributes"]["hash"];
2747 // Lower the `Worker.URL` sentinel into the aliased preview URL —
2748 // same lowering `putWorker` performs, with the alias standing in
2749 // for the script's own URL. `Worker.Self` lowers to a
2750 // service binding on the parent script (versions have no name of
2751 // their own).
2752 const metadataBindings = bindings.flatMap((b) =>
2753 withoutDevOnlyBindings(b.data.bindings ?? []).map((item) =>
2754 item.type === "self_url"
2755 ? { type: "plain_text" as const, name: item.name, text: selfUrl! }
2756 : item.type === "self_service"
2757 ? {
2758 type: "service" as const,
2759 name: item.name,
2760 service: parentName,
2761 ...(item.entrypoint !== undefined && { entrypoint: item.entrypoint }),
2762 ...(item.props !== undefined && { props: item.props }),
2763 }
2764 : item,
2765 ),
2766 );
2767 let metadataAssets: workers.CreateScriptVersionRequest["metadata"]["assets"] | undefined;
2768 if (assets) {
2769 yield* Effect.logInfo(`Cloudflare Worker version: uploading assets for ${parentName}`);
2770 const { jwt } = yield* uploadAssets(accountId, parentName, assets, session);
2771 metadataAssets = { jwt, config: mergeAssetsConfigFiles(assets.config, assets) };
2772 metadataBindings.push({ type: "assets", name: "ASSETS" });
2773 }
2774 appendAlchemyAndEnvBindings(metadataBindings, news, accountId, parentName);
2775 const compatibility = getCompatibility(news);
2776 // A version of a parent that hosts Durable Objects must re-declare
2777 // the parent's live `exports`: Cloudflare reconciles a deployed
2778 // version against its own map and rejects splitting traffic between
2779 // versions whose maps differ.
2780 const parentExports = yield* getLiveDurableObjectExports(accountId, parentName);
2781 yield* session.note(`Uploading version of ${parentName} ...`, { kind: "status" });
2782 const created = yield* workers
2783 .createScriptVersion({
2784 accountId,
2785 scriptName: parentName,
2786 metadata: {
2787 mainModule: bundle.main!,
2788 assets: metadataAssets,
2789 bindings: metadataBindings,
2790 compatibilityDate: compatibility.date,
2791 compatibilityFlags: compatibility.flags,
2792 cacheOptions: news.cache ?? getCacheBinding(bindings),
2793 exports: nonEmptyExports({
2794 ...parentExports,
2795 ...(yield* workerEntrypointExports(
2796 parentName,
2797 news.entrypoints,
2798 Object.keys(parentExports ?? {}),
2799 )),
2800 }),
2801 annotations:
2802 alias !== undefined || version.message !== undefined || version.tag !== undefined
2803 ? {
2804 workersAlias: alias,
2805 workersMessage: version.message,
2806 workersTag: version.tag,
2807 }
2808 : undefined,
2809 },
2810 files: bundle.files,
2811 })
2812 .pipe(
2813 Effect.retry({
2814 while: isBindingTargetNotFound,
2815 schedule: bindingTargetNotFoundRetrySchedule(),
2816 }),
2817 Effect.catchTag("WorkerNotFound", () =>
2818 Effect.fail(
2819 new WorkerVersionConfigError({
2820 message: `version.parent script '${parentName}' does not exist. Deploy the parent Worker first (or check the referenced stage/stack).`,
2821 }),
2822 ),
2823 ),
2824 );
2825 const versionId = created.id ?? undefined;
2826 if (versionId === undefined) {
2827 return yield* new WorkerVersionConfigError({
2828 message: `Cloudflare did not return a version id for the uploaded version of '${parentName}'.`,
2829 });
2830 }
2831 let deploymentId: string | undefined;
2832 if (traffic > 0) {
2833 yield* session.note(`Deploying version at ${traffic}% of ${parentName}'s traffic ...`, {
2834 kind: "status",
2835 });
2836 deploymentId = yield* deployVersionTraffic({
2837 accountId,
2838 scriptName: parentName,
2839 versionId,
2840 traffic,
2841 message: version.message,
2842 codeUpdateStrategy: yield* resolveCodeUpdateStrategy(news.codeUpdateStrategy),
2843 });
2844 }
2845 // Version-affinity transform rules (`version.affinity`): a canary
2846 // rides the *parent's* zone traffic, so the rules land on the
2847 // parent's zones — observed custom-domain attachments plus, when
2848 // `parent` was passed as a Worker resource, its recorded routes.
2849 const previousAffinityZoneIds = output?.affinityZoneIds ?? [];
2850 let affinityZoneIds: string[] | undefined;
2851 if (version.affinity !== undefined || previousAffinityZoneIds.length) {
2852 const resolvedAffinity =
2853 version.affinity !== undefined
2854 ? yield* resolveVersionAffinity(version.affinity)
2855 : undefined;
2856 let hostsByZone: Map<string, AffinityZoneHost[]> | undefined;
2857 if (resolvedAffinity !== undefined) {
2858 hostsByZone = new Map();
2859 const addHost = (zoneId: string, host: AffinityZoneHost) => {
2860 const hosts = hostsByZone!.get(zoneId) ?? [];
2861 hosts.push(host);
2862 hostsByZone!.set(zoneId, hosts);
2863 };
2864 // A `version.parent` passed as a Worker resource resolves to
2865 // the parent's Attributes at reconcile time (see
2866 // resolveVersionParentName) — its recorded routes and domain
2867 // tell us the zones the parent serves on.
2868 const parentAttrs =
2869 typeof version.parent === "object" && version.parent !== null
2870 ? (version.parent as unknown as Partial<Worker["Attributes"]>)
2871 : undefined;
2872 const redirectHosts = new Set(parentAttrs?.domain?.redirects ?? []);
2873 const attached = yield* workers
2874 .listDomains({ accountId, service: parentName })
2875 .pipe(Effect.map((r) => r.result ?? []));
2876 for (const d of attached) {
2877 if (!d.hostname || !d.zoneId || redirectHosts.has(d.hostname)) {
2878 continue;
2879 }
2880 addHost(d.zoneId, { host: d.hostname, wildcard: false });
2881 }
2882 for (const route of parentAttrs?.routes ?? []) {
2883 const host = route.pattern.split("/")[0];
2884 if (!host || host.includes('"')) continue;
2885 addHost(route.zoneId, { host, wildcard: host.includes("*") });
2886 }
2887 if (hostsByZone.size === 0) {
2888 return yield* new WorkerVersionConfigError({
2889 message:
2890 `version.affinity pins users via a zone Transform Rule setting the ${AFFINITY_HEADER} header, which only sees zone traffic — the parent '${parentName}' has no custom domains (or recorded zone routes) to place the rule on. ` +
2891 `Give the parent a \`domain\` or zone \`routes\`, or pass the parent as a Worker resource so its routes are visible here.`,
2892 });
2893 }
2894 yield* session.note("Reconciling version-affinity rules ...", { kind: "status" });
2895 }
2896 const placed = yield* reconcileAffinityRules({
2897 scriptName: parentName,
2898 desired:
2899 resolvedAffinity !== undefined && hostsByZone !== undefined
2900 ? { affinity: resolvedAffinity, hostsByZone }
2901 : undefined,
2902 previousZoneIds: previousAffinityZoneIds,
2903 });
2904 affinityZoneIds = placed.length > 0 ? placed : undefined;
2905 }
2906 // The aliased URL is primary (`url`): it is stable across deploys,
2907 // re-pointing at each newly uploaded version. The per-version URL
2908 // (prefixed by the version id) rides along in `urls`.
2909 const versionedUrl = previewsEnabled
2910 ? `https://${versionId.split("-")[0]}-${parentName}.${accountSubdomain}.workers.dev`
2911 : undefined;
2912 const urls = [...(aliasedUrl ? [aliasedUrl] : []), ...(versionedUrl ? [versionedUrl] : [])];
2913 return {
2914 // A version worker never owns a script — carry the *parent*
2915 // script's immutable ID (its preview URLs are protected through
2916 // the parent).
2917 workerId:
2918 cachedWorkerId(output?.workerId, parentName) ??
2919 (yield* findWorkerId(accountId, parentName)),
2920 workerName: parentName,
2921 namespace: undefined,
2922 logpush: undefined,
2923 url: urls[0],
2924 urls,
2925 domain: undefined,
2926 tags: undefined,
2927 durableObjectNamespaces: {},
2928 accountId,
2929 routes: [],
2930 crons: [],
2931 versionOf: parentName,
2932 versionId,
2933 versionAlias: alias,
2934 deploymentId,
2935 affinityZoneIds,
2936 hash,
2937 } satisfies Worker["Attributes"];
2938 });
2939
2940 /**
2941 * Reconcile a *Preview Worker*: create/update a first-class Preview of
2942 * the parent script and upload this Worker's code + bindings as a
2943 * Preview deployment. Isolated same-Worker Durable Object classes
2944 * get their own namespace per Preview.
2945 */
2946 const putWorkerPreview = Effect.fn(function* (
2947 id: string,
2948 fqn: string,
2949 news: WorkerProps,
2950 bindings: ResourceBinding<Worker["Binding"]>[],
2951 session: ScopedPlanStatusSession,
2952 output: Worker["Attributes"] | undefined,
2953 ) {
2954 const { accountId } = yield* yield* CloudflareEnvironment;
2955 const preview = news.preview!;
2956 const parentName = resolvePreviewParentName(preview);
2957 if (parentName === undefined) {
2958 return yield* new WorkerPreviewConfigError({
2959 message: `preview.of did not resolve to a Worker script name. Pass a Worker (e.g. \`yield* Cloudflare.Worker.ref(id, { stage })\`) or a literal script name.`,
2960 });
2961 }
2962 if (news.version !== undefined) {
2963 return yield* new WorkerPreviewConfigError({
2964 message: `preview and version cannot be set together. Use preview.of for branch/PR Previews; use version.parent / version.traffic for canaries and gradual rollouts.`,
2965 });
2966 }
2967 const forbidden = (
2968 [
2969 ["name", news.name],
2970 ["namespace", news.namespace],
2971 ["crons", news.crons],
2972 ["tailConsumers", news.tailConsumers],
2973 ["streamingTailConsumers", news.streamingTailConsumers],
2974 ["domain", news.domain],
2975 ["routes", news.routes],
2976 ["workersDev", news.workersDev],
2977 ["access", news.access],
2978 ] as const
2979 ).flatMap(([key, value]) => (value !== undefined ? [key] : []));
2980 if (forbidden.length > 0) {
2981 return yield* new WorkerPreviewConfigError({
2982 message:
2983 `preview.of creates a Preview of '${parentName}' — script-level settings belong to the parent Worker and cannot be set here: ${forbidden.join(", ")}. ` +
2984 `Remove ${forbidden.length === 1 ? "this prop" : "these props"} or configure ${forbidden.length === 1 ? "it" : "them"} on the parent.`,
2985 });
2986 }
2987 const cronBindings = getCronBindings(bindings);
2988 if (cronBindings.length > 0) {
2989 return yield* new WorkerPreviewConfigError({
2990 message: `Cron Triggers are script-level settings and cannot be registered from a Preview of '${parentName}'. Configure crons on the parent Worker.`,
2991 });
2992 }
2993
2994 const budget = 63 - parentName.length - 1;
2995 const userName = preview.name;
2996 let previewName: string;
2997 if (userName !== undefined) {
2998 if (!/^[a-z][a-z0-9-]*$/.test(userName)) {
2999 return yield* new WorkerPreviewConfigError({
3000 message: `preview.name '${userName}' is invalid: names must start with a lowercase letter and contain only lowercase letters, digits, and dashes.`,
3001 });
3002 }
3003 if (userName.length > budget) {
3004 return yield* new WorkerPreviewConfigError({
3005 message: `preview.name '${userName}' is too long: '<name>-${parentName}' must fit in a 63-character DNS label, leaving ${Math.max(budget, 0)} characters for the name.`,
3006 });
3007 }
3008 previewName = userName;
3009 } else if (budget < 4) {
3010 return yield* new WorkerPreviewConfigError({
3011 message: `Cannot derive a Preview name: '<name>-${parentName}' must fit in a 63-character DNS label. Set preview.name to a short value or shorten the parent's name.`,
3012 });
3013 } else {
3014 const readable = stack.stage
3015 .toLowerCase()
3016 .replace(/[^a-z0-9-]+/g, "-")
3017 .replace(/^-+|-+$/g, "");
3018 const derived = (readable.length > 0 ? readable : `p${id}`)
3019 .slice(0, budget)
3020 .replace(/-+$/, "");
3021 previewName = /^[a-z]/.test(derived) ? derived : `p${derived}`.slice(0, budget);
3022 }
3023
3024 yield* Effect.logInfo(
3025 `Cloudflare Worker Preview: ${previewName} of ${parentName} (from ${id})`,
3026 );
3027
3028 const existingPreview = yield* workers
3029 .getPreview({ accountId, workerId: parentName, previewId: previewName })
3030 .pipe(
3031 Effect.catchTags({
3032 PreviewNotFound: () => Effect.undefined,
3033 WorkerNotFound: () =>
3034 Effect.fail(
3035 new WorkerPreviewConfigError({
3036 message: `preview.of script '${parentName}' does not exist. Deploy the parent Worker first (or check the referenced stage/stack).`,
3037 }),
3038 ),
3039 }),
3040 );
3041
3042 const previewResource =
3043 existingPreview ??
3044 (yield* workers
3045 .createPreview({
3046 accountId,
3047 workerId: parentName,
3048 name: previewName,
3049 ignoreBaseConfig: true,
3050 })
3051 .pipe(
3052 Effect.catchTag("PreviewAlreadyExists", () =>
3053 workers
3054 .getPreview({ accountId, workerId: parentName, previewId: previewName })
3055 .pipe(
3056 Effect.retry({
3057 while: (error) => error._tag === "PreviewNotFound",
3058 schedule: Schedule.spaced("500 millis"),
3059 times: 8,
3060 }),
3061 ),
3062 ),
3063 Effect.catchTag("WorkerNotFound", () =>
3064 Effect.fail(
3065 new WorkerPreviewConfigError({
3066 message: `preview.of script '${parentName}' does not exist. Deploy the parent Worker first (or check the referenced stage/stack).`,
3067 }),
3068 ),
3069 ),
3070 ));
3071
3072 const accountSubdomain = yield* getAccountSubdomain(accountId);
3073 const parentAttrs =
3074 typeof preview.of === "object" && preview.of !== null
3075 ? (preview.of as unknown as Partial<Worker["Attributes"]>)
3076 : undefined;
3077 const parentDomainName = parentAttrs?.domain?.name;
3078 const parentDomainPreviews = parentAttrs?.domain?.previews === true;
3079 const constructedUrls = [
3080 ...(parentDomainPreviews && parentDomainName
3081 ? [`https://${previewResource.slug}.${parentDomainName}`]
3082 : []),
3083 `https://${previewResource.slug}-${parentName}.${accountSubdomain}.workers.dev`,
3084 ];
3085 const stableUrl = previewResource.urls?.[0] ?? constructedUrls[0];
3086 const selfUrl = hasSelfUrlBinding(bindings) ? stableUrl : undefined;
3087
3088 yield* Effect.logInfo(
3089 `Cloudflare Worker Preview: preparing bundle for ${parentName} (preview ${previewName})`,
3090 );
3091 const {
3092 assets,
3093 bundle,
3094 hash: preparedHash,
3095 } = yield* prepareAssetsAndBundle(id, fqn, parentName, news, { skipAssetsRead: false });
3096 const metadataHash = yield* resolveWorkerMetadataHash({
3097 props: news,
3098 bindings,
3099 accountId,
3100 stack: { name: stack.name, stage: stack.stage },
3101 selfUrl,
3102 });
3103 const hash = {
3104 ...preparedHash,
3105 metadata: metadataHash,
3106 } satisfies Worker["Attributes"]["hash"];
3107
3108 const metadataBindings = bindings.flatMap((b) =>
3109 withoutDevOnlyBindings(b.data.bindings ?? []).map((item) =>
3110 item.type === "self_url"
3111 ? { type: "plain_text" as const, name: item.name, text: selfUrl! }
3112 : item.type === "self_service"
3113 ? {
3114 type: "service" as const,
3115 name: item.name,
3116 service: parentName,
3117 ...(item.entrypoint !== undefined && { entrypoint: item.entrypoint }),
3118 ...(item.props !== undefined && { props: item.props }),
3119 }
3120 : item,
3121 ),
3122 );
3123 let metadataAssets: workers.CreatePreviewDeploymentMetadata["assets"] | undefined;
3124 if (assets) {
3125 yield* Effect.logInfo(`Cloudflare Worker Preview: uploading assets for ${parentName}`);
3126 const { jwt } = yield* uploadAssets(accountId, parentName, assets, session);
3127 metadataAssets = { jwt, config: mergeAssetsConfigFiles(assets.config, assets) };
3128 metadataBindings.push({ type: "assets", name: "ASSETS" });
3129 }
3130 appendAlchemyAndEnvBindings(metadataBindings, news, accountId, parentName);
3131
3132 const hostedClasses = getDurableObjectBindings(bindings, parentName);
3133 const classNames = [...new Set(hostedClasses.map((c) => c.className))];
3134 let migrations: unknown = undefined;
3135 if (classNames.length > 0) {
3136 const latest = yield* workers
3137 .getPreviewDeployment({
3138 accountId,
3139 workerId: parentName,
3140 previewId: previewResource.id,
3141 deploymentId: "latest",
3142 })
3143 .pipe(
3144 Effect.catchTag(
3145 ["PreviewNotFound", "PreviewDeploymentNotFound"],
3146 () => Effect.undefined,
3147 ),
3148 );
3149 const oldTag = latest?.migrationTag ?? undefined;
3150 const previous = output?.previewDoClasses ?? [];
3151 if (oldTag === undefined) {
3152 migrations = { new_tag: "alchemy:v1", new_sqlite_classes: classNames };
3153 } else {
3154 const added = classNames.filter((c) => !previous.includes(c));
3155 const deleted = previous.filter((c) => !classNames.includes(c));
3156 if (added.length > 0 || deleted.length > 0) {
3157 migrations = {
3158 old_tag: oldTag,
3159 new_tag: bumpMigrationTagVersion(oldTag) ?? "alchemy:v1",
3160 ...(added.length > 0 ? { new_sqlite_classes: added } : {}),
3161 ...(deleted.length > 0 ? { deleted_classes: deleted } : {}),
3162 };
3163 }
3164 }
3165 }
3166
3167 const compatibility = getCompatibility(news);
3168 const annotations =
3169 preview.message !== undefined || preview.tag !== undefined
3170 ? {
3171 ...(preview.message !== undefined ? { "workers/message": preview.message } : {}),
3172 ...(preview.tag !== undefined ? { "workers/tag": preview.tag } : {}),
3173 }
3174 : undefined;
3175
3176 yield* session.note(`Uploading Preview ${previewName} of ${parentName} ...`, {
3177 kind: "status",
3178 });
3179 const deployment = yield* workers.createPreviewDeployment({
3180 accountId,
3181 workerId: parentName,
3182 previewId: previewResource.id,
3183 metadata: {
3184 mainModule: bundle.main!,
3185 assets: metadataAssets,
3186 compatibilityDate: compatibility.date,
3187 compatibilityFlags: compatibility.flags,
3188 cacheOptions: news.cache ?? getCacheBinding(bindings),
3189 annotations,
3190 migrations,
3191 exports: nonEmptyExports(
3192 yield* workerEntrypointExports(parentName, news.entrypoints, classNames),
3193 ),
3194 env: bindingsToPreviewEnv(metadataBindings),
3195 },
3196 files: bundle.files,
3197 });
3198
3199 const refreshed = yield* workers
3200 .getPreview({ accountId, workerId: parentName, previewId: previewResource.id })
3201 .pipe(Effect.catchTag("PreviewNotFound", () => Effect.succeed(previewResource)));
3202
3203 const urls = [
3204 ...new Set([...(refreshed.urls ?? []), ...constructedUrls, ...(deployment.urls ?? [])]),
3205 ];
3206 return {
3207 workerId:
3208 cachedWorkerId(output?.workerId, parentName) ??
3209 (yield* findWorkerId(accountId, parentName)),
3210 workerName: parentName,
3211 namespace: undefined,
3212 logpush: undefined,
3213 url: urls[0],
3214 urls,
3215 domain: undefined,
3216 tags: undefined,
3217 durableObjectNamespaces: {},
3218 accountId,
3219 routes: [],
3220 crons: [],
3221 previewOf: parentName,
3222 previewId: previewResource.id,
3223 previewName,
3224 previewSlug: previewResource.slug,
3225 previewDoClasses: classNames.length > 0 ? classNames : undefined,
3226 deploymentId: deployment.id,
3227 hash,
3228 } satisfies Worker["Attributes"];
3229 });
3230
3231 const putWorker = Effect.fn(function* (
3232 id: string,
3233 fqn: string,
3234 news: WorkerProps,
3235 bindings: ResourceBinding<Worker["Binding"]>[],
3236 olds: WorkerProps | undefined,
3237 output: Worker["Attributes"] | undefined,
3238 session: ScopedPlanStatusSession,
3239 existingSettings?: workers.GetScriptScriptAndVersionSettingResponse,
3240 ) {
3241 news = newsWithBoundEnv(news, bindings).news;
3242 const { accountId } = yield* yield* CloudflareEnvironment;
3243 // Prefer the deployed name: regenerating would target a different
3244 // script if the generator's output for this id ever drifts.
3245 const name = output?.workerName ?? (yield* createWorkerName(id, news.name));
3246 // When set, this Worker is a Workers for Platforms "user worker"
3247 // uploaded into a dispatch namespace rather than a routable
3248 // account-level script. The put/settings calls switch endpoints and
3249 // the subdomain / custom-domain / cron reconciliation is skipped.
3250 const dispatchNamespace = resolveNamespaceName(news?.namespace);
3251 yield* validateTraffic(news.version?.traffic);
3252 if (news.version !== undefined && dispatchNamespace) {
3253 return yield* new WorkerVersionConfigError({
3254 message: `Workers for Platforms user workers do not support versions or gradual deployments — remove the version prop from '${name}'.`,
3255 });
3256 }
3257 // Resolve the Worker's own URL up front when a `Worker.URL` binding
3258 // is present: the value must exist before the bundle is built (Vite
3259 // inlines VITE_*-prefixed env into the client bundle) and before the
3260 // metadata bindings are assembled (the `self_url` sentinel lowers
3261 // into a plain_text binding below).
3262 const selfUrl = hasSelfUrlBinding(bindings)
3263 ? dispatchNamespace
3264 ? yield* Effect.die(
3265 `Worker "${name}" binds its own URL (Worker.URL), but a dispatch-namespace user worker is invoked via dynamic dispatch and has no URL of its own.`,
3266 )
3267 : yield* resolveSelfUrl(name, news, accountId)
3268 : undefined;
3269 yield* Effect.logInfo(
3270 `Cloudflare Worker ${olds ? "update" : "create"}: preparing bundle for ${name}`,
3271 );
3272 // If the caller handed us a precomputed asset hash that matches
3273 // what we previously stored, we can skip walking the directory
3274 // entirely and tell Cloudflare to keep the assets it already
3275 // has bound to this script. The disk read is the expensive
3276 // part; the script PUT happens either way.
3277 const prebuiltAssets = normalizePrebuiltAssets(news.assets, output);
3278 const {
3279 assets,
3280 bundle,
3281 hash: preparedHash,
3282 } = yield* prepareAssetsAndBundle(id, fqn, name, news, {
3283 skipAssetsRead: prebuiltAssets?.skip,
3284 selfUrl,
3285 });
3286 // When the caller supplied a precomputed hash (e.g. via
3287 // `Command.Build`), store *that* hash in output state so the
3288 // next diff can short-circuit by comparing it directly. The
3289 // hash that `readAssets` produces is the manifest-derived
3290 // hash, which is shaped differently from any upstream
3291 // build-input hash and will never match it on the next pass.
3292 const metadataHash = yield* resolveWorkerMetadataHash({
3293 props: news,
3294 bindings,
3295 accountId,
3296 stack: { name: stack.name, stage: stack.stage },
3297 selfUrl,
3298 });
3299 const hash = {
3300 ...preparedHash,
3301 assets: prebuiltAssets?.hash ?? preparedHash.assets,
3302 metadata: metadataHash,
3303 } satisfies Worker["Attributes"]["hash"];
3304 // `transferredFrom` is alchemy-only transfer metadata on
3305 // durable_object_namespace bindings — it drives the
3306 // `transferred_classes` migration below and must be stripped from the
3307 // wire-shape binding before upload.
3308 const metadataBindings = bindings.flatMap((b) =>
3309 withoutDevOnlyBindings(b.data.bindings ?? []).map((item): WireWorkerBinding => {
3310 // Lower the `Worker.URL` sentinel into the resolved URL —
3311 // Cloudflare has no native binding for it.
3312 if (item.type === "self_url") {
3313 return { type: "plain_text", name: item.name, text: selfUrl! };
3314 }
3315 // Lower the `Worker.Self` sentinel into a service
3316 // binding targeting this Worker's own physical name.
3317 if (item.type === "self_service") {
3318 return {
3319 type: "service",
3320 name: item.name,
3321 service: name,
3322 ...(item.entrypoint !== undefined && { entrypoint: item.entrypoint }),
3323 ...(item.props !== undefined && { props: item.props }),
3324 };
3325 }
3326 if (
3327 item.type === "durable_object_namespace" &&
3328 (item.transferredFrom !== undefined || item.storage !== undefined)
3329 ) {
3330 const { transferredFrom: _, storage: __, ...rest } = item;
3331 return rest;
3332 }
3333 // `queueId` (mode discrimination) and `shim` (dev-mode remote
3334 // producer) are alchemy-only metadata on queue bindings — strip
3335 // them from the wire shape.
3336 if (item.type === "queue" && (item.queueId !== undefined || item.shim !== undefined)) {
3337 const { queueId: _, shim: __, ...rest } = item;
3338 return rest;
3339 }
3340 return item;
3341 }),
3342 );
3343 const expectedDurableObjectClassNames = getExpectedDurableObjectClassNames(
3344 metadataBindings,
3345 name,
3346 );
3347 let metadataAssets: workers.PutScriptRequest["metadata"]["assets"] | undefined;
3348 let keepAssets = false;
3349 if (prebuiltAssets?.skip) {
3350 // Hash matched what's already on Cloudflare: keep the
3351 // existing asset manifest and skip the upload session.
3352 yield* Effect.logInfo(
3353 `Cloudflare Worker update: assets unchanged for ${name}, keeping existing`,
3354 );
3355 keepAssets = true;
3356 // `keepAssets` only preserves the uploaded files — the PUT
3357 // replaces the asset config wholesale. The skip path never
3358 // walked the directory, so read just `_headers`/`_redirects`
3359 // here or a no-op deploy would wipe their rules.
3360 metadataAssets = {
3361 config: mergeAssetsConfigFiles(
3362 prebuiltAssets.config,
3363 yield* readAssetsConfigFiles(prebuiltAssets.directory),
3364 ),
3365 };
3366 metadataBindings.push({ type: "assets", name: "ASSETS" });
3367 } else if (assets) {
3368 // We had to read the directory. Even after the read, the
3369 // computed hash may match what's already deployed (e.g.
3370 // legacy `string` / `AssetsProps` shapes that don't carry a
3371 // precomputed hash, or a precomputed hash that disagreed with
3372 // disk). In that case still keep the existing manifest and
3373 // skip the upload session — Cloudflare's content-addressed
3374 // session would no-op on every byte anyway.
3375 if (assets.hash === prebuiltAssets?.hash) {
3376 yield* Effect.logInfo(
3377 `Cloudflare Worker update: assets unchanged for ${name}, keeping existing`,
3378 );
3379 keepAssets = true;
3380 // Fold the build-emitted `_headers`/`_redirects` into the PUT
3381 // config: source providers (Astro/SvelteKit/Waku/Nuxt) hash the
3382 // files and carry them on the read result, but only `readAssets`
3383 // pre-merges them — without this, framework header/redirect
3384 // rules never reach Cloudflare. Idempotent for pre-merged
3385 // configs (explicit config wins).
3386 metadataAssets = { config: mergeAssetsConfigFiles(assets.config, assets) };
3387 } else {
3388 yield* Effect.logInfo(
3389 `Cloudflare Worker ${olds ? "update" : "create"}: uploading assets for ${name}`,
3390 );
3391 const { jwt } = yield* uploadAssets(
3392 accountId,
3393 name,
3394 assets,
3395 session,
3396 dispatchNamespace,
3397 );
3398 metadataAssets = {
3399 jwt,
3400 // Same `_headers`/`_redirects` fold as the keep path above.
3401 config: mergeAssetsConfigFiles(assets.config, assets),
3402 };
3403 }
3404 metadataBindings.push({ type: "assets", name: "ASSETS" });
3405 }
3406 appendAlchemyAndEnvBindings(metadataBindings, news, accountId, name);
3407 yield* Effect.logInfo(
3408 `Cloudflare Worker ${olds ? "update" : "create"}: uploading script for ${name}`,
3409 );
3410 const size =
3411 bundle.files
3412 ?.filter((file) => !file.name.endsWith(".map"))
3413 .reduce((acc, file) => acc + file.size, 0) ?? 0;
3414 const sizeKB = size / 1024;
3415 const sizeMB = sizeKB / 1024;
3416 const bundleSize = `${sizeKB > 1024 ? `${sizeMB.toFixed(2)} MB` : `${sizeKB.toFixed(2)} KB`}`;
3417 yield* session.note(`Uploading worker (${bundleSize}) ...`, { kind: "status" });
3418
3419 // Read existing worker settings for migration tracking
3420 const oldSettings =
3421 existingSettings ??
3422 (yield* workers.getScriptScriptAndVersionSetting({ accountId, scriptName: name }).pipe(
3423 Effect.map((s) => s as typeof s | undefined),
3424 Effect.orElseSucceed(() => undefined),
3425 ));
3426
3427 const oldTags = Array.from(new Set(oldSettings?.tags ?? []));
3428 const oldBindings = oldSettings?.bindings ?? [];
3429
3430 // Parse the DO logical-id→class mapping from script tags (packed
3431 // `alchemy:dos:` and legacy per-DO `alchemy:do:` formats)
3432 const oldDoClassNameByLogicalId = getDurableObjectTagMap(oldTags);
3433 const currentDoBindings = getDurableObjectBindings(bindings, name);
3434
3435 // Domain models named their classes differently in earlier Domain
3436 // versions. Map each old class to the logical id of its new name, so
3437 // the rename below carries its data over instead of deleting it.
3438 const domainClasses = bindings.flatMap((b) => b.data.domainClasses ?? []);
3439 const deployedDomainVersion = DomainVersion.deployedVersion(oldTags);
3440 yield* DomainVersion.refuseDowngrade({ scriptName: name, deployed: deployedDomainVersion });
3441 if (domainClasses.length > 0) {
3442 const renamed = yield* DomainVersion.migrate({
3443 scriptName: name,
3444 deployed: deployedDomainVersion,
3445 classes: domainClasses,
3446 deployedClasses: new Set([
3447 ...Object.values(oldDoClassNameByLogicalId),
3448 ...oldBindings.flatMap((old) =>
3449 old.type === "durable_object_namespace" &&
3450 "className" in old &&
3451 old.className &&
3452 (!("scriptName" in old) || old.scriptName === undefined || old.scriptName === name)
3453 ? [old.className]
3454 : [],
3455 ),
3456 ]),
3457 });
3458 for (const { from, to } of renamed) {
3459 for (const [logicalId, className] of Object.entries(oldDoClassNameByLogicalId)) {
3460 if (className === from) delete oldDoClassNameByLogicalId[logicalId];
3461 }
3462 // A Domain class's logical id is its class name.
3463 oldDoClassNameByLogicalId[to] = from;
3464 }
3465 }
3466 const currentDoClassNameByLogicalId = Object.fromEntries(
3467 currentDoBindings.map((binding) => [binding.logicalId, binding.className]),
3468 );
3469
3470 // Compute delete-class candidates. Candidates are validated against
3471 // observed namespace ownership below — a class may already have been
3472 // transferred to another script by its new host's deploy.
3473 // Several bindings may name one class (e.g. two Containers sharing a
3474 // Durable Object class): a class stays while any binding hosts it.
3475 const currentDoClasses = new Set(currentDoBindings.map((binding) => binding.className));
3476 const deletedClassCandidates: string[] = [];
3477 for (const [logicalId, className] of Object.entries(oldDoClassNameByLogicalId)) {
3478 if (
3479 !currentDoClassNameByLogicalId[logicalId] &&
3480 !currentDoClasses.has(className) &&
3481 !deletedClassCandidates.includes(className)
3482 ) {
3483 deletedClassCandidates.push(className);
3484 }
3485 }
3486
3487 // Backward compatibility for old workers that have DO bindings but no
3488 // alchemy:do tags yet. Cross-script bindings (`scriptName` set to
3489 // anything other than this worker) are NEVER candidates for
3490 // delete-class migrations — the class lives on the foreign script
3491 // and we don't own its lifecycle.
3492 if (Object.keys(oldDoClassNameByLogicalId).length === 0) {
3493 for (const oldBinding of oldBindings) {
3494 const ownedLocally = !("scriptName" in oldBinding) || oldBinding.scriptName === name;
3495 if (
3496 oldBinding.type === "durable_object_namespace" &&
3497 "className" in oldBinding &&
3498 oldBinding.className &&
3499 ownedLocally &&
3500 !currentDoBindings.some((binding) => binding.bindingName === oldBinding.name) &&
3501 !currentDoClasses.has(oldBinding.className) &&
3502 !deletedClassCandidates.includes(oldBinding.className)
3503 ) {
3504 deletedClassCandidates.push(oldBinding.className);
3505 }
3506 }
3507 }
3508
3509 // Class names the current deploy references *cross-script* (mapped to
3510 // the foreign script). A class that both leaves the "hosted here" set
3511 // and shows up here has moved to another Worker — Cloudflare rejects
3512 // deleting a class while any binding in the upload references its
3513 // class name, and deleting would destroy the namespace's data.
3514 const crossScriptClassTargets = new Map<string, string>();
3515 for (const item of metadataBindings) {
3516 if (
3517 item.type === "durable_object_namespace" &&
3518 item.className &&
3519 typeof item.scriptName === "string" &&
3520 item.scriptName !== name
3521 ) {
3522 crossScriptClassTargets.set(item.className, item.scriptName);
3523 }
3524 }
3525
3526 // One account-level namespace listing is the observed Durable Object
3527 // state for this deploy: the `exports` map declares every namespace
3528 // this script owns (with its storage backend), the destination of a
3529 // transfer checks the source still hosts the class, and the former
3530 // host checks whether a to-be-deleted class was already transferred
3531 // away. Dispatch-namespace user workers keep the legacy `migrations`
3532 // flow — their namespaces don't surface on the account-level list.
3533 const mayTransferIn = currentDoBindings.some(
3534 (binding) =>
3535 !oldDoClassNameByLogicalId[binding.logicalId] && binding.transferredFrom !== undefined,
3536 );
3537 const hostedDurableObjectsBefore = oldBindings.some(
3538 (binding) =>
3539 binding.type === "durable_object_namespace" &&
3540 (!("scriptName" in binding) ||
3541 binding.scriptName === undefined ||
3542 binding.scriptName === name),
3543 );
3544 const observedNamespaces =
3545 deletedClassCandidates.length > 0 ||
3546 mayTransferIn ||
3547 currentDoBindings.length > 0 ||
3548 hostedDurableObjectsBefore
3549 ? yield* listDurableObjectNamespaces(accountId, dispatchNamespace)
3550 : [];
3551 const hosts = (
3552 namespaces: readonly { script: string; class: string }[],
3553 scriptName: string,
3554 className: string,
3555 ) => namespaces.some((ns) => ns.script === scriptName && ns.class === className);
3556 const deletedClasses: string[] = [];
3557 for (const className of deletedClassCandidates) {
3558 if (dispatchNamespace) {
3559 deletedClasses.push(className);
3560 continue;
3561 }
3562 const targetScriptName = crossScriptClassTargets.get(className);
3563 const namespaceId =
3564 oldBindings.flatMap((binding) =>
3565 binding.type === "durable_object_namespace" &&
3566 "className" in binding &&
3567 binding.className === className &&
3568 (!("scriptName" in binding) ||
3569 binding.scriptName === undefined ||
3570 binding.scriptName === name) &&
3571 "namespaceId" in binding &&
3572 typeof binding.namespaceId === "string"
3573 ? [binding.namespaceId]
3574 : [],
3575 )[0] ??
3576 output?.durableObjectNamespaces?.[className] ??
3577 observedNamespaces.find((ns) => ns.script === name && ns.class === className)?.id;
3578 if (targetScriptName === undefined) {
3579 const findNamespace = (namespaces: typeof observedNamespaces) =>
3580 namespaces.find((ns) =>
3581 namespaceId === undefined
3582 ? ns.script === name && ns.class === className
3583 : ns.id === namespaceId,
3584 );
3585 // Absence from an account listing does not prove a transfer.
3586 const namespace =
3587 findNamespace(observedNamespaces) ??
3588 (yield* listDurableObjectNamespaces(accountId, dispatchNamespace).pipe(
3589 Effect.flatMap((namespaces) => {
3590 const namespace = findNamespace(namespaces);
3591 return namespace
3592 ? Effect.succeed(namespace)
3593 : Effect.fail(
3594 new MissingDurableObjects({ scriptName: name, expected: [className] }),
3595 );
3596 }),
3597 Effect.retry({
3598 while: (error) => error._tag === "MissingDurableObjects",
3599 schedule: Schedule.spaced("2 seconds"),
3600 times: 5,
3601 }),
3602 ));
3603 if (namespace.script === name && namespace.class === className) {
3604 deletedClasses.push(className);
3605 }
3606 continue;
3607 }
3608 // A missing listing is inconclusive; the original namespace must appear on the new host.
3609 const transferred = (namespaces: typeof observedNamespaces) =>
3610 namespaceId !== undefined &&
3611 namespaces.some(
3612 (ns) =>
3613 ns.id === namespaceId && ns.script === targetScriptName && ns.class === className,
3614 );
3615 const namespaces = yield* listDurableObjectNamespaces(accountId, dispatchNamespace).pipe(
3616 Effect.repeat({
3617 schedule: Schedule.spaced("2 seconds"),
3618 until: (observed) =>
3619 transferred(observed) ||
3620 (hosts(observed, name, className) && hosts(observed, targetScriptName, className)),
3621 times: 5,
3622 }),
3623 );
3624 if (transferred(namespaces)) {
3625 continue;
3626 }
3627 // local → cross-script transition without a transfer. Fail before
3628 // any upload: Cloudflare would reject the combined delete + binding
3629 // anyway, and silently deleting would destroy the namespace's
3630 // data. See the error's docs for the two ways out
3631 // (`transferredFrom` on the new host, or a two-phase removal).
3632 return yield* new DurableObjectTransferRequired({
3633 scriptName: name,
3634 className,
3635 targetScriptName,
3636 });
3637 }
3638
3639 // Collect container-backed classes so we can send container metadata.
3640 // A Durable Object-managed class merges the images of every bound
3641 // Container under one entry; `name` and `images` are only set for it.
3642 const containerRows = bindings.flatMap((b) => b.data.containers ?? []);
3643 yield* assertBindingContainersOnAsyncClasses(
3644 containerRows,
3645 effectNativeDurableObjectClasses(news.exports),
3646 );
3647 const containerClasses = (yield* mergeWorkerContainers(containerRows)).map(
3648 ({ className, name, images }) => ({ className, name, images }),
3649 );
3650
3651 // Classes the deployed script hosts locally, by migration tag or by
3652 // an observed local Durable Object binding.
3653 const deployedDoClasses = new Set([
3654 ...Object.values(oldDoClassNameByLogicalId),
3655 ...oldBindings.flatMap((old) =>
3656 old.type === "durable_object_namespace" &&
3657 "className" in old &&
3658 old.className &&
3659 (!("scriptName" in old) || old.scriptName === undefined || old.scriptName === name)
3660 ? [old.className]
3661 : [],
3662 ),
3663 ]);
3664
3665 // Compute new, renamed, and transferred classes
3666 const newClasses: string[] = [];
3667 const newSqliteClasses: string[] = [];
3668 const renamedClasses: { from: string; to: string }[] = [];
3669 const transferredClasses: { from: string; fromScript: string; to: string }[] = [];
3670 for (const binding of currentDoBindings) {
3671 let previousClassName: string | undefined = oldDoClassNameByLogicalId[binding.logicalId];
3672 if (!previousClassName) {
3673 // No DO metadata tag maps this logical id to a class — the
3674 // worker was created outside Alchemy (raw API / Wrangler) or
3675 // before these tags existed. Fall back to matching the observed
3676 // cloud binding by binding name so adoption reuses the existing
3677 // class instead of asking Cloudflare to create one that already
3678 // exists (which fails the migration). This is the "first deploy
3679 // must match the existing class name" path; once we write the
3680 // `alchemy:dos:` tag, subsequent renames are driven by logical id.
3681 const observed = oldBindings.find(
3682 (old) =>
3683 old.type === "durable_object_namespace" &&
3684 "className" in old &&
3685 old.className &&
3686 // Only a *locally-owned* binding proves the class exists on
3687 // this script. A cross-script binding under the same name —
3688 // e.g. this worker previously referenced another host's
3689 // class and now hosts its own — points at a foreign
3690 // namespace and must not suppress the create migration
3691 // (Cloudflare rejects a local binding for a class the
3692 // script isn't configured to implement).
3693 (!("scriptName" in old) ||
3694 old.scriptName === undefined ||
3695 old.scriptName === name) &&
3696 old.name === binding.bindingName,
3697 );
3698 if (observed && "className" in observed && observed.className) {
3699 previousClassName = observed.className;
3700 }
3701 }
3702 // Another binding already hosts this class on the deployed script
3703 // (several bindings may name one class): the class exists, so a
3704 // binding added for it creates nothing.
3705 if (
3706 (!previousClassName || previousClassName !== binding.className) &&
3707 deployedDoClasses.has(binding.className)
3708 ) {
3709 continue;
3710 }
3711 // A logical id that moved to another class while its old class is
3712 // still hosted by another binding is a new class, not a rename.
3713 if (
3714 previousClassName !== undefined &&
3715 previousClassName !== binding.className &&
3716 currentDoClasses.has(previousClassName)
3717 ) {
3718 previousClassName = undefined;
3719 }
3720 if (!previousClassName) {
3721 // A class new to this script is a host move when the declaration
3722 // says so: `transferredFrom` lists the former host(s) — moves
3723 // are always declared, never inferred, because a class deleted
3724 // on one worker and created on another is otherwise ambiguous
3725 // between "move the data" and "delete + fresh namespace". The
3726 // declared source must be observed to still host the namespace;
3727 // otherwise (fresh stage, transfer already completed) fall
3728 // through to a plain create.
3729 const fromScript = dispatchNamespace
3730 ? undefined
3731 : yield* resolveTransferSource({
3732 accountId,
3733 selfScriptName: name,
3734 logicalId: binding.logicalId,
3735 className: binding.className,
3736 sources: normalizeTransferSources(binding.transferredFrom, name),
3737 observedNamespaces,
3738 });
3739 if (fromScript !== undefined) {
3740 // Data-preserving move: ship Cloudflare's
3741 // `transferred_classes` migration instead of creating a
3742 // fresh class.
3743 transferredClasses.push({
3744 from: binding.className,
3745 fromScript,
3746 to: binding.className,
3747 });
3748 continue;
3749 }
3750 // Default all new Durable Object classes to SQLite. Cloudflare
3751 // recommends SQLite for new namespaces, and container-backed
3752 // Durable Objects require it. Several bindings may name one class
3753 // (e.g. two Containers sharing a class); create it once.
3754 if (!newSqliteClasses.includes(binding.className)) {
3755 newSqliteClasses.push(binding.className);
3756 }
3757 } else if (
3758 previousClassName !== binding.className &&
3759 !renamedClasses.some(
3760 (rename) => rename.from === previousClassName && rename.to === binding.className,
3761 )
3762 ) {
3763 renamedClasses.push({ from: previousClassName, to: binding.className });
3764 }
3765 }
3766
3767 yield* Effect.logInfo(
3768 `Cloudflare Worker put: durable object reconciliation ${JSON.stringify({
3769 oldDoClassNameByLogicalId,
3770 currentDoClassNameByLogicalId,
3771 deletedClasses,
3772 renamedClasses,
3773 transferredClasses,
3774 newSqliteClasses,
3775 })}`,
3776 );
3777
3778 // Pack every DO logical-id→class mapping into as few `alchemy:dos:`
3779 // tags as possible — one tag per DO blows Cloudflare's 10-tag limit
3780 // at 7+ bindings (#811).
3781 const alchemyDoTags = encodeDurableObjectTags(currentDoBindings);
3782
3783 // The Domain version goes up with every upload that can change the
3784 // classes, in the same request, so the tag and the classes never disagree.
3785 const domainTags =
3786 domainClasses.length > 0 ? [DomainVersion.versionTag(DomainVersion.DOMAIN_VERSION)] : [];
3787 const alchemyTags = [...createAlchemyWorkerTags(id), ...alchemyDoTags, ...domainTags];
3788 const metadataTags = Array.from(new Set([...alchemyTags, ...(news.tags ?? [])]));
3789 yield* validateWorkerTags(name, metadataTags, alchemyTags.length);
3790
3791 // Cloudflare's declarative `exports` map: the complete Durable Object
3792 // lifecycle of this script. Every namespace Cloudflare reports for
3793 // this script stays declared with its observed storage backend
3794 // (adopted classes Alchemy never bound included — an undeclared
3795 // namespace is rejected, never silently deleted), then this deploy's
3796 // creates, renames, deletes and incoming transfers are applied on top.
3797 const exportsMap = buildDurableObjectExports({
3798 scriptName: name,
3799 observedNamespaces,
3800 hostedClasses: currentDoBindings.map((binding) => binding.className),
3801 declaredStorage: new Map(
3802 currentDoBindings.flatMap((binding) =>
3803 binding.storage === undefined ? [] : [[binding.className, binding.storage] as const],
3804 ),
3805 ),
3806 renamedClasses,
3807 deletedClasses,
3808 transferredClasses,
3809 });
3810 Object.assign(
3811 exportsMap,
3812 yield* workerEntrypointExports(name, news.entrypoints, Object.keys(exportsMap)),
3813 );
3814 const transferringIn = new Set(transferredClasses.map((transfer) => transfer.to));
3815
3816 const metadataContainers = containerClasses;
3817
3818 const compatibility = getCompatibility(news);
3819 const tailConsumers = resolveTailConsumers(news.tailConsumers);
3820 const streamingTailConsumers = resolveTailConsumers(news.streamingTailConsumers);
3821 const observability = resolveObservability(news, bindings);
3822 const metadata: workers.PutScriptRequest["metadata"] = {
3823 annotations: news.version
3824 ? { workersMessage: news.version.message, workersTag: news.version.tag }
3825 : undefined,
3826 assets: metadataAssets,
3827 bindings: metadataBindings,
3828 bodyPart: undefined,
3829 cacheOptions: news.cache ?? getCacheBinding(bindings),
3830 compatibilityDate: compatibility.date,
3831 compatibilityFlags: compatibility.flags,
3832 containers: metadataContainers.length > 0 ? metadataContainers : undefined,
3833 keepAssets,
3834 keepBindings: undefined,
3835 limits: news.limits,
3836 logpush: news.logpush,
3837 mainModule: bundle.main,
3838 exports: nonEmptyExports(exportsMap),
3839 observability,
3840 placement: news.placement,
3841 tags: metadataTags,
3842 tailConsumers,
3843 streamingTailConsumers,
3844 usageModel: undefined,
3845 codeUpdateStrategy: yield* resolveCodeUpdateStrategy(news.codeUpdateStrategy),
3846 };
3847 const rolloutTraffic = getSelfRolloutTraffic(news);
3848 let versionId: string | undefined;
3849 let deploymentId: string | undefined;
3850 let worker: {
3851 id?: string | null;
3852 logpush?: boolean | null;
3853 /** The immutable script id (Cloudflare's script "tag"). */
3854 tag?: string | null;
3855 };
3856 // A gradual rollout (`version.traffic` < 100) deploys through the
3857 // versions API instead of the full-cutover script PUT. That's only
3858 // possible when the script already has a live deployment to split
3859 // traffic against (otherwise the first deploy takes 100%), and only
3860 // for changes a version can carry — code, bindings, compatibility
3861 // settings, cache. Script-level settings in the upload metadata
3862 // (tags, observability, limits, placement, logpush) keep their live
3863 // values until the next full deploy, matching
3864 // `wrangler versions upload` semantics.
3865 if (
3866 rolloutTraffic !== undefined &&
3867 existingSettings !== undefined &&
3868 output?.hash !== undefined &&
3869 !dispatchNamespace
3870 ) {
3871 const migratedClasses = [
3872 ...newClasses,
3873 ...newSqliteClasses,
3874 ...deletedClasses,
3875 ...renamedClasses.map((r) => r.to),
3876 ...transferredClasses.map((t) => t.to),
3877 ];
3878 if (migratedClasses.length > 0) {
3879 return yield* new WorkerVersionConfigError({
3880 message: `This deploy of '${name}' changes Durable Object classes (${migratedClasses.join(", ")}). Durable Object lifecycle changes cannot ride a gradual rollout. Deploy at 100% (remove version.traffic) first, then resume gradual rollouts.`,
3881 });
3882 }
3883 if (rolloutTraffic > 0) {
3884 // Cloudflare rejects a split between versions that declare
3885 // different `exports` — including the first deploy after a
3886 // Worker moves from `migrations` to `exports`.
3887 const liveExports = yield* getLiveDurableObjectExports(accountId, name);
3888 if (!sameDurableObjectExports(metadata.exports, liveExports)) {
3889 return yield* new WorkerVersionConfigError({
3890 message: `This deploy of '${name}' changes its Durable Object exports${liveExports === undefined ? " (its live version still uses migrations)" : ""}. A gradual rollout needs every version to declare the same exports. Deploy at 100% (remove version.traffic) first, then resume gradual rollouts.`,
3891 });
3892 }
3893 }
3894 yield* session.note(`Uploading version of ${name} (${bundleSize}) ...`, {
3895 kind: "status",
3896 });
3897 const created = yield* workers
3898 .createScriptVersion({
3899 accountId,
3900 scriptName: name,
3901 metadata: {
3902 mainModule: metadata.mainModule!,
3903 assets: metadata.assets,
3904 bindings: metadata.bindings,
3905 keepAssets: metadata.keepAssets,
3906 compatibilityDate: metadata.compatibilityDate,
3907 compatibilityFlags: metadata.compatibilityFlags,
3908 cacheOptions: metadata.cacheOptions,
3909 // No lifecycle changes reach this path (checked above): the
3910 // map only re-declares the live classes, as Cloudflare
3911 // requires once a Worker uses `exports`.
3912 exports: metadata.exports,
3913 annotations:
3914 news.version?.alias !== undefined ||
3915 news.version?.message !== undefined ||
3916 news.version?.tag !== undefined
3917 ? {
3918 workersAlias: news.version?.alias,
3919 workersMessage: news.version?.message,
3920 workersTag: news.version?.tag,
3921 }
3922 : undefined,
3923 },
3924 files: bundle.files,
3925 })
3926 .pipe(
3927 Effect.retry({
3928 while: isBindingTargetNotFound,
3929 schedule: bindingTargetNotFoundRetrySchedule(),
3930 }),
3931 );
3932 versionId = created.id ?? undefined;
3933 if (versionId === undefined) {
3934 return yield* new WorkerVersionConfigError({
3935 message: `Cloudflare did not return a version id for the uploaded version of '${name}'.`,
3936 });
3937 }
3938 if (rolloutTraffic > 0) {
3939 yield* session.note(`Deploying version at ${rolloutTraffic}% of traffic ...`, {
3940 kind: "status",
3941 });
3942 deploymentId = yield* deployVersionTraffic({
3943 accountId,
3944 scriptName: name,
3945 versionId,
3946 traffic: rolloutTraffic,
3947 message: news.version?.message,
3948 codeUpdateStrategy: metadata.codeUpdateStrategy,
3949 });
3950 }
3951 worker = { id: name, logpush: existingSettings.logpush };
3952 } else {
3953 if (rolloutTraffic !== undefined) {
3954 // First deploy of this script (or a pre-create placeholder is
3955 // the only thing live) — there is no previous version worth
3956 // splitting traffic with, so this deploy takes 100%.
3957 yield* Effect.logInfo(
3958 `Cloudflare Worker ${name}: no previous live version to split traffic with; deploying at 100%`,
3959 );
3960 }
3961 if (transferringIn.size > 0) {
3962 // A transfer is two-phase under `exports`: this Worker first
3963 // declares the class `expecting-transfer` (Cloudflare rejects a
3964 // binding to it until the namespace arrives, so that binding is
3965 // held back, and its `alchemy:dos` tag too — a crash before the
3966 // commit then re-plans the transfer instead of creating a fresh
3967 // namespace), then the former host commits with a `transferred`
3968 // tombstone, then the full upload below binds the moved class.
3969 const stagedTags = Array.from(
3970 new Set([
3971 ...createAlchemyWorkerTags(id),
3972 ...encodeDurableObjectTags(
3973 currentDoBindings.filter((binding) => !transferringIn.has(binding.className)),
3974 ),
3975 ...domainTags,
3976 ...(news.tags ?? []),
3977 ]),
3978 );
3979 yield* putWorkerScript({
3980 accountId,
3981 scriptName: name,
3982 dispatchNamespace,
3983 metadata: {
3984 ...metadata,
3985 tags: stagedTags,
3986 bindings: metadata.bindings?.filter(
3987 (binding) =>
3988 !(
3989 binding.type === "durable_object_namespace" &&
3990 transferringIn.has(binding.className) &&
3991 (binding.scriptName === undefined || binding.scriptName === name)
3992 ),
3993 ),
3994 },
3995 files: bundle.files,
3996 });
3997 for (const fromScript of new Set(transferredClasses.map((t) => t.fromScript))) {
3998 yield* commitDurableObjectTransfer({
3999 accountId,
4000 fromScript,
4001 toScript: name,
4002 classNames: transferredClasses
4003 .filter((transfer) => transfer.fromScript === fromScript)
4004 .map((transfer) => transfer.from),
4005 observedNamespaces,
4006 });
4007 }
4008 }
4009 worker = yield* putWorkerScript({
4010 accountId,
4011 scriptName: name,
4012 dispatchNamespace,
4013 metadata: {
4014 ...metadata,
4015 exports: metadata.exports && settleTransfers(metadata.exports),
4016 },
4017 files: bundle.files,
4018 });
4019 }
4020
4021 const { settings, durableObjectNamespaces } = yield* getWorkerSettingsWithDurableObjects(
4022 name,
4023 expectedDurableObjectClassNames,
4024 dispatchNamespace,
4025 );
4026 // Workers for Platforms user workers are invoked via dynamic dispatch,
4027 // never routed directly — they have no workers.dev subdomain, custom
4028 // domains, zone routes, or cron triggers. Skip all of that
4029 // reconciliation.
4030 if (dispatchNamespace) {
4031 return {
4032 workerId:
4033 worker.tag ??
4034 cachedWorkerId(output?.workerId, name) ??
4035 (yield* new WorkerIdNotFound({
4036 scriptName: name,
4037 message: `Cloudflare Worker: the dispatch-namespace upload for '${name}' did not return the script's immutable ID`,
4038 })),
4039 workerName: name,
4040 namespace: dispatchNamespace,
4041 logpush: worker.logpush ?? undefined,
4042 url: undefined,
4043 tags: settings.tags ?? metadata.tags,
4044 durableObjectNamespaces,
4045 accountId,
4046 urls: [],
4047 domain: undefined,
4048 routes: [],
4049 crons: [],
4050 tailConsumers:
4051 settings.tailConsumers?.map((c) => ({ service: c.service })) ?? tailConsumers,
4052 // The settings read endpoint doesn't expose
4053 // `streaming_tail_consumers`; record what this deploy uploaded.
4054 streamingTailConsumers,
4055 hash,
4056 } satisfies Worker["Attributes"];
4057 }
4058 // Cloudflare keeps a secret binding that a script upload omits, even
4059 // with an empty `keep_bindings`, so a secret dropped from `env` would
4060 // stay bound. Delete the secrets an earlier deploy uploaded and this
4061 // one did not; secrets set outside Alchemy (`wrangler secret put`,
4062 // the dashboard) are left alone. State written before `secretNames`
4063 // existed falls back to the previous `env`. Deletes run only after a
4064 // full upload: each one deploys a new version at 100%, which would
4065 // end a gradual rollout, so a rollout keeps owning the removed names.
4066 const uploadedSecretNames = getSecretNames(metadata.bindings);
4067 const previousSecretNames =
4068 output?.secretNames ??
4069 Object.entries(olds?.env ?? {}).flatMap(([key, value]) =>
4070 secretTextFromEnvValue(value) === undefined ? [] : [key],
4071 );
4072 const removedSecretNames = previousSecretNames.filter(
4073 (secretName) => !uploadedSecretNames.includes(secretName),
4074 );
4075 if (versionId === undefined) {
4076 const liveSecretNames = getSecretNames(settings.bindings);
4077 for (const secretName of removedSecretNames) {
4078 if (!liveSecretNames.includes(secretName)) continue;
4079 yield* session.note(`Deleting removed secret ${secretName} ...`, { kind: "status" });
4080 yield* workers
4081 .deleteScriptSecret({ accountId, scriptName: name, secretName })
4082 .pipe(Effect.catchTag("SecretNotFound", () => Effect.void));
4083 }
4084 }
4085 const secretNames =
4086 versionId === undefined
4087 ? uploadedSecretNames
4088 : [...new Set([...uploadedSecretNames, ...removedSecretNames])].sort();
4089 const issuesEnabled = observability.issues?.enabled ?? false;
4090 if (
4091 versionId === undefined &&
4092 (settings.observability?.issues?.enabled ?? false) !== issuesEnabled
4093 ) {
4094 // PATCH replaces observability; preserve the full observed configuration.
4095 const observed = settings.observability;
4096 yield* workers
4097 .patchScriptSetting({
4098 accountId,
4099 scriptName: name,
4100 observability: {
4101 ...observed,
4102 headSamplingRate: observed?.headSamplingRate ?? undefined,
4103 redactQueryString: observed?.redactQueryString ?? undefined,
4104 logs: observed?.logs
4105 ? {
4106 ...observed.logs,
4107 destinations: observed.logs.destinations ?? undefined,
4108 headSamplingRate: observed.logs.headSamplingRate ?? undefined,
4109 persist: observed.logs.persist ?? undefined,
4110 }
4111 : undefined,
4112 traces: observed?.traces
4113 ? {
4114 ...observed.traces,
4115 destinations: observed.traces.destinations ?? undefined,
4116 enabled: observed.traces.enabled ?? undefined,
4117 headSamplingRate: observed.traces.headSamplingRate ?? undefined,
4118 persist: observed.traces.persist ?? undefined,
4119 propagationPolicy: observed.traces.propagationPolicy ?? undefined,
4120 }
4121 : undefined,
4122 issues: { enabled: issuesEnabled },
4123 },
4124 })
4125 .pipe(
4126 Effect.retry({
4127 while: (error) => error._tag === "WorkerNotFound",
4128 schedule: Schedule.exponential("100 millis"),
4129 times: 6,
4130 }),
4131 );
4132 }
4133 // Reconcile the workers.dev settings against observed cloud state.
4134 // We can't diff `news.workersDev` against `olds.workersDev` here
4135 // because both default to `undefined` (meaning "enable") — that
4136 // comparison would skip the API call on every deploy where the user
4137 // never set the prop, leaving the subdomain in whatever state
4138 // Cloudflare currently has it (disabled by default, or whatever
4139 // a previous failed/external action left it as).
4140 const workersDev = resolveWorkersDev(news.workersDev);
4141 const observedSubdomain = yield* workers
4142 .getScriptSubdomain({ accountId, scriptName: name })
4143 .pipe(
4144 Effect.orElseSucceed((): workers.GetScriptSubdomainResponse => ({
4145 enabled: false,
4146 previewsEnabled: false,
4147 })),
4148 );
4149 if (
4150 workersDev.enabled !== observedSubdomain.enabled ||
4151 workersDev.previewsEnabled !== observedSubdomain.previewsEnabled
4152 ) {
4153 yield* session.note(
4154 `${workersDev.enabled || workersDev.previewsEnabled ? "Enabling" : "Disabling"} workers.dev subdomain...`,
4155 { kind: "status" },
4156 );
4157 // Cloudflare's script registry is eventually consistent — for the
4158 // first few hundred ms after `putScript` returns, POST /subdomain
4159 // can still get back `WorkerNotFound` (a generic "unknown error"
4160 // body), or a bare 500 surfaced as `InternalServerError` /
4161 // `UnknownCloudflareError` (code 10013). Bigger uploads race harder.
4162 // Retry the subdomain toggle on those transient tags with a short
4163 // exponential backoff; same pattern we use elsewhere in this
4164 // provider for DO-namespace propagation and for `putScript` itself.
4165 yield* setWorkerSubdomain(name, workersDev).pipe(
4166 Effect.retry({
4167 while: (error) =>
4168 error._tag === "WorkerNotFound" ||
4169 error._tag === "InternalServerError" ||
4170 error._tag === "UnknownCloudflareError",
4171 schedule: Schedule.max([Schedule.exponential(200), Schedule.recurs(15)]),
4172 }),
4173 );
4174 }
4175 // Custom domains are managed only when `domain` is declared on props
4176 // (#942): an omitted `domain` leaves live attachments alone — and
4177 // spares a plain workers.dev Worker the listDomains call on every
4178 // deploy (#926) — while `domain: null` explicitly detaches
4179 // everything. When managed, the canonical name + aliases + redirect
4180 // hostnames are all attached (DNS + edge certificate); redirect
4181 // hostnames additionally get a redirect rule, which runs before the
4182 // Worker so those requests never invoke it. Unmanaged domains
4183 // persisted in state carry forward so read keeps observing them.
4184 const manageCustomDomains = news.domain !== undefined;
4185 const domainConfig = yield* resolveWorkerDomain(news.domain);
4186 const previousDomain = stateWorkerDomain(output);
4187 let effectiveDomain = manageCustomDomains ? domainConfig : previousDomain;
4188 if (!manageCustomDomains && previousDomain !== undefined) {
4189 // Unmanaged, but state remembers domains: observe which of them
4190 // are actually still attached and carry only those forward —
4191 // stale state entries (e.g. legacy records whose attach never
4192 // happened, or hostnames detached out-of-band) must not
4193 // resurface in `urls`. Plain workers.dev Workers (no persisted
4194 // domains) never pay this listDomains call (#926).
4195 const live = new Set(
4196 yield* workers.listDomains({ accountId, service: name }).pipe(
4197 Effect.map((r) => (r.result ?? []).flatMap((d) => (d.hostname ? [d.hostname] : []))),
4198 Effect.orElseSucceed(() => [] as string[]),
4199 ),
4200 );
4201 const serving = [
4202 ...(live.has(previousDomain.name) ? [previousDomain.name] : []),
4203 ...previousDomain.aliases.filter((h) => live.has(h)),
4204 ];
4205 effectiveDomain =
4206 serving.length > 0
4207 ? {
4208 name: serving[0],
4209 aliases: serving.slice(1),
4210 redirects: previousDomain.redirects.filter((h) => live.has(h)),
4211 }
4212 : undefined;
4213 }
4214 if (manageCustomDomains) {
4215 const desiredHostnames = domainConfig
4216 ? [domainConfig.name, ...domainConfig.aliases, ...domainConfig.redirects]
4217 : [];
4218 yield* session.note(`Reconciling custom domains (${desiredHostnames.length}) ...`, {
4219 kind: "status",
4220 });
4221 // Capture hostname → zone for *currently attached* domains before
4222 // reconcile detaches removed ones — a removed redirect hostname's
4223 // zone is otherwise unresolvable and its rule couldn't be cleaned.
4224 const liveBeforeReconcile = yield* workers.listDomains({ accountId, service: name }).pipe(
4225 Effect.map((r) =>
4226 (r.result ?? []).flatMap((d) =>
4227 d.hostname && d.zoneId ? [[d.hostname, d.zoneId] as const] : [],
4228 ),
4229 ),
4230 Effect.orElseSucceed(() => []),
4231 );
4232 const reconciled = yield* reconcileDomains(
4233 name,
4234 desiredHostnames,
4235 domainConfig?.zone,
4236 domainConfig?.previews,
4237 );
4238 const zoneIdByHostname = new Map([
4239 ...liveBeforeReconcile,
4240 ...reconciled.map((d) => [d.hostname, d.zoneId] as const),
4241 ]);
4242 yield* reconcileRedirectRules({
4243 scriptName: name,
4244 domain: domainConfig,
4245 zoneIdByHostname,
4246 previousRedirects: previousDomain?.redirects ?? [],
4247 });
4248 effectiveDomain = domainConfig;
4249 }
4250 const urls = yield* computeWorkerUrls({
4251 scriptName: name,
4252 workersDev,
4253 domain: effectiveDomain,
4254 uploadedVersionId: versionId,
4255 uploadedVersionAlias: news.version?.alias,
4256 });
4257 const desiredRoutes = yield* normalizeRoutes(news.routes);
4258 const previousRoutes = output?.routes ?? [];
4259 if (desiredRoutes.length > 0 || previousRoutes.length > 0) {
4260 yield* session.note(`Reconciling worker routes (${desiredRoutes.length}) ...`, {
4261 kind: "status",
4262 });
4263 }
4264 const routes = yield* reconcileRoutes(name, desiredRoutes, previousRoutes);
4265 // Version-affinity transform rules (`version.affinity`): pin each
4266 // user to one version during gradual rollouts by filling the
4267 // version-key header from a stable request property, on every zone
4268 // this Worker serves on. Runs after the domain/route reconciles so
4269 // freshly attached surfaces resolve their zones, and also when only
4270 // *previous* state holds rules, so removing affinity converges.
4271 const affinity = news.version?.parent == null ? news.version?.affinity : undefined;
4272 const previousAffinityZoneIds = output?.affinityZoneIds ?? [];
4273 let affinityZoneIds: string[] | undefined;
4274 if (affinity !== undefined || previousAffinityZoneIds.length > 0) {
4275 const resolvedAffinity =
4276 affinity !== undefined ? yield* resolveVersionAffinity(affinity) : undefined;
4277 let hostsByZone: Map<string, AffinityZoneHost[]> | undefined;
4278 if (resolvedAffinity !== undefined) {
4279 hostsByZone = new Map();
4280 const addHost = (zoneId: string, host: AffinityZoneHost) => {
4281 const hosts = hostsByZone!.get(zoneId) ?? [];
4282 hosts.push(host);
4283 hostsByZone!.set(zoneId, hosts);
4284 };
4285 // Serving hostnames from *observed* domain attachments (covers
4286 // managed, unmanaged, and adopted domains alike); redirect
4287 // hostnames 301 before the Worker and never need a key.
4288 const redirectHosts = new Set(effectiveDomain?.redirects ?? []);
4289 const attached = yield* workers
4290 .listDomains({ accountId, service: name })
4291 .pipe(Effect.map((r) => r.result ?? []));
4292 for (const d of attached) {
4293 if (!d.hostname || !d.zoneId || redirectHosts.has(d.hostname)) {
4294 continue;
4295 }
4296 addHost(d.zoneId, { host: d.hostname, wildcard: false });
4297 }
4298 for (const route of routes) {
4299 const host = route.pattern.split("/")[0];
4300 if (!host || host.includes('"')) continue;
4301 addHost(route.zoneId, { host, wildcard: host.includes("*") });
4302 }
4303 if (hostsByZone.size === 0) {
4304 return yield* new WorkerVersionConfigError({
4305 message:
4306 `version.affinity pins users via a zone Transform Rule setting the ${AFFINITY_HEADER} header, which only sees zone traffic — give '${name}' a custom domain (\`domain\`) or zone \`routes\`. ` +
4307 `On the bare workers.dev URL, clients must send the header themselves.`,
4308 });
4309 }
4310 yield* session.note("Reconciling version-affinity rules ...", { kind: "status" });
4311 }
4312 const placed = yield* reconcileAffinityRules({
4313 scriptName: name,
4314 desired:
4315 resolvedAffinity !== undefined && hostsByZone !== undefined
4316 ? { affinity: resolvedAffinity, hostsByZone }
4317 : undefined,
4318 previousZoneIds: previousAffinityZoneIds,
4319 });
4320 affinityZoneIds = placed.length > 0 ? placed : undefined;
4321 }
4322 const desiredCrons = normalizeCrons([...getCronBindings(bindings), ...(news.crons ?? [])]);
4323 const previousCrons = output?.crons ?? [];
4324 // Same gating as read: skip getScriptSchedule when neither props nor
4325 // prior state indicate cron management (#926).
4326 const crons =
4327 desiredCrons.length > 0 || previousCrons.length > 0
4328 ? yield* reconcileCrons(name, desiredCrons, previousCrons, session)
4329 : [];
4330 if (!dispatchNamespace && versionId === undefined) {
4331 const { deployments } = yield* workers.listScriptDeployments({
4332 accountId,
4333 scriptName: name,
4334 });
4335 const active = deployments[0];
4336 deploymentId = active?.id;
4337 versionId = active?.versions.find((version) => version.percentage === 100)?.versionId;
4338 }
4339 return {
4340 // The immutable script ID. The gradual-rollout branch deploys via
4341 // the versions API (no script PUT response), and rows persisted by
4342 // older releases carried the script *name* here — both fall back
4343 // to a lazy listing lookup.
4344 workerId:
4345 worker.tag ??
4346 cachedWorkerId(output?.workerId, name) ??
4347 (yield* findWorkerId(accountId, name)),
4348 workerName: name,
4349 namespace: undefined,
4350 logpush: worker.logpush ?? undefined,
4351 url: urls[0],
4352 urls,
4353 domain: effectiveDomain,
4354 tags: settings.tags ?? metadata.tags,
4355 durableObjectNamespaces,
4356 accountId,
4357 routes,
4358 crons,
4359 // Observed post-upload settings are authoritative: the gradual
4360 // rollout branch above deploys via the versions API, which leaves
4361 // script-level settings (tail consumers included) at their live
4362 // values until the next full deploy.
4363 tailConsumers:
4364 settings.tailConsumers?.map((c) => ({ service: c.service })) ?? tailConsumers,
4365 // GET script-settings has no `streaming_tail_consumers` field (the
4366 // API only carries it on upload metadata), so the uploaded value is
4367 // authoritative here. In the gradual-rollout branch the versions
4368 // API leaves script-level settings live-as-is, matching how the
4369 // metadata surface treats every other script-level field.
4370 streamingTailConsumers,
4371 versionOf: undefined,
4372 versionId,
4373 deploymentId,
4374 affinityZoneIds,
4375 secretNames,
4376 hash,
4377 } satisfies Worker["Attributes"];
4378 });
4379
4380 // Compare the desired assets against the deployed asset-content hash.
4381 //
4382 // For `AssetsWithHash` (the documented `Command.Build` contract) the
4383 // upstream build already produced an authoritative hash — compare
4384 // strings without touching the filesystem. Reading the directory here
4385 // would crash when the prior state was written on a different machine
4386 // and the path doesn't exist locally, blocking any local reapply even
4387 // though the precomputed hash is right there in props.
4388 //
4389 // For the plain `string` / `AssetsProps` shapes there is no hash in
4390 // props, so read + hash the directory exactly like the apply path does
4391 // (`readAssets`) and compare against the stored content hash — an
4392 // unchanged tree converges to a noop plan instead of a forever-dirty
4393 // conservative update. The overall read cost is unchanged: previously
4394 // every plan reported "changed" and `putWorker` read the tree during
4395 // apply only to discover nothing changed (`keepAssets`); now the diff
4396 // reads it and a match skips reconcile entirely. A directory that is
4397 // missing or invalid at plan time (e.g. produced by an upstream build
4398 // step that only runs during apply) degrades to "changed" — apply
4399 // reads it once and either uploads or surfaces the real typed error.
4400 const assetsChanged = Effect.fn(function* (
4401 assets: WorkerProps["assets"],
4402 output: Worker["Attributes"],
4403 ) {
4404 if (!assets) {
4405 return false;
4406 }
4407 // An explicitly-undefined `hash` (`{ directory, hash: maybe }`) is
4408 // the hash-less shape, not a supplied hash — fall through to the
4409 // directory read instead of comparing undefined forever-dirty.
4410 if (Predicate.hasProperty(assets, "hash") && assets.hash !== undefined) {
4411 return assets.hash !== output.hash?.assets;
4412 }
4413 const read = yield* prepareAssets(assets).pipe(
4414 Effect.catchTag(
4415 ["PlatformError", "AssetTooLargeError", "TooManyAssetsError"],
4416 () => Effect.undefined,
4417 ),
4418 );
4419 return read === undefined || read.hash !== output.hash?.assets;
4420 });
4421
4422 const hasChanged = Effect.fn(function* (
4423 id: string,
4424 fqn: string,
4425 props: WorkerProps,
4426 output: Worker["Attributes"],
4427 bindings: readonly ResourceBinding<Worker["Binding"]>[] | undefined,
4428 accountId: string,
4429 ) {
4430 // #745: metadata-only edits (compatibility, observability, placement,
4431 // limits, logpush, env literals, bindings, subdomain config, tags)
4432 // don't touch the bundle/vite/asset-content hashes below, so compare a
4433 // hash of that surface first. Skipped when bindings are still
4434 // unresolved: the hash can't be computed deterministically here, and
4435 // the eventual apply stores it once bindings resolve.
4436 if (bindings) {
4437 // For a version worker, `Worker.URL` resolves to the *aliased
4438 // preview URL* (see `putWorkerVersion`) — recompute the same
4439 // value here so the metadata hash matches what the apply stored
4440 // and unchanged deploys stay noops.
4441 const versionParent =
4442 props.version?.parent != null
4443 ? (resolveVersionParentName(props.version) ?? output.versionOf)
4444 : undefined;
4445 const previewParent =
4446 props.preview?.of != null
4447 ? (resolvePreviewParentName(props.preview) ?? output.previewOf)
4448 : undefined;
4449 const resolveBoundSelfUrl = Effect.gen(function* () {
4450 if (previewParent !== undefined) {
4451 return output.url;
4452 }
4453 if (versionParent !== undefined) {
4454 const alias = yield* resolveVersionAlias(id, props, versionParent);
4455 return alias !== undefined
4456 ? `https://${alias}-${versionParent}.${yield* getAccountSubdomain(accountId)}.workers.dev`
4457 : undefined;
4458 }
4459 return yield* resolveSelfUrl(output.workerName, props, accountId);
4460 });
4461 const selfUrl = hasSelfUrlBinding(bindings) ? yield* resolveBoundSelfUrl : undefined;
4462 const metadataHash = yield* resolveWorkerMetadataHash({
4463 props,
4464 bindings,
4465 accountId,
4466 stack: { name: stack.name, stage: stack.stage },
4467 selfUrl,
4468 });
4469 if (metadataHash !== output.hash?.metadata) {
4470 return true;
4471 }
4472 }
4473 // Assets-only Worker — there is no bundle to hash. A stored bundle
4474 // hash means the Worker previously had a script and is being
4475 // converted to assets-only, which must deploy.
4476 if (isAssetsOnly(props)) {
4477 if (output.hash?.bundle !== undefined) {
4478 return true;
4479 }
4480 // No assets either — the config is invalid; report "changed" so
4481 // the apply runs and surfaces the descriptive error.
4482 if (!props.assets) {
4483 return true;
4484 }
4485 return yield* assetsChanged(props.assets, output);
4486 }
4487 // The source recomputes the hash slots it owns (without building
4488 // where it can) and any defined slot that differs from state means
4489 // an update. `additionalWorkspaces` is auxiliary metadata for the
4490 // input hash, never a change signal.
4491 const source = yield* resolveSource(props);
4492 const slots = yield* source.hash(
4493 makeSourceContext({
4494 dotAlchemy,
4495 id,
4496 fqn,
4497 workerName: output.workerName,
4498 props,
4499 compatibility: getCompatibility(props),
4500 stack: { name: stack.name, stage: stack.stage },
4501 }),
4502 output.hash,
4503 );
4504 for (const slot of ["bundle", "input", "assets"] as const) {
4505 if (slots[slot] !== undefined && slots[slot] !== output.hash?.[slot]) {
4506 return true;
4507 }
4508 }
4509 if (source.ownsAssets) {
4510 // Source-owned assets are covered by the `input` hash.
4511 return false;
4512 }
4513 if (props.source || props.vite) {
4514 // An external or vite build may write the `assets` directory
4515 // itself, so it can't be read before the build: only a supplied
4516 // hash proves it unchanged.
4517 if (!props.assets) {
4518 return false;
4519 }
4520 const assetsHash = Predicate.hasProperty(props.assets, "hash")
4521 ? props.assets.hash
4522 : undefined;
4523 return assetsHash === undefined || assetsHash !== output.hash?.assets;
4524 }
4525 return yield* assetsChanged(props.assets, output);
4526 });
4527
4528 return Worker.Provider.of({
4529 stables: ["workerId", "workerName"],
4530 list: () =>
4531 Effect.gen(function* () {
4532 const { accountId } = yield* yield* CloudflareEnvironment;
4533 // Account-scoped enumeration of every Worker script. The
4534 // per-script `read` makes several extra calls (subdomain,
4535 // settings, domains, schedule) to fully hydrate
4536 // url/durableObjectNamespaces/domains/crons. Doing that for
4537 // every script on the account is both expensive (4 calls × N)
4538 // and fragile — a single script with a binding shape the
4539 // settings schema doesn't know about would break the whole
4540 // listing (the same reason `read` deliberately avoids
4541 // `listScripts`). For `list()` we hydrate the core identifying
4542 // and settings fields that come straight from the script
4543 // metadata and leave the binding-derived fields at the same
4544 // defaults `read` returns when those sub-resources are absent
4545 // (`url: undefined`, `durableObjectNamespaces: {}`,
4546 // `domains: []`, `crons: []`). `accountId` + `workerName` are
4547 // sufficient for `delete`.
4548 return yield* workers.listScripts.pages({ accountId }).pipe(
4549 Stream.runCollect,
4550 Effect.map((chunk) =>
4551 Array.from(chunk).flatMap((page) =>
4552 // Annotate the element type as the full `Attributes` shape
4553 // (incl. the optional `hash`) so it matches `read` exactly.
4554 // `list()` is an inference source for the provider's resource
4555 // type; a narrower element (e.g. via `satisfies`, which omits
4556 // `hash`) would derail `Res` inference and cascade every
4557 // lifecycle method's requirement channel to `never`.
4558 (page.result ?? []).flatMap((script): Worker["Attributes"][] =>
4559 script.id
4560 ? [
4561 {
4562 accountId,
4563 // Practically always present. Fall back to the
4564 // name (healed by the per-script read), never
4565 // the "" that marks an unuploaded stub.
4566 workerId: script.tag ?? script.id,
4567 workerName: script.id,
4568 namespace: undefined,
4569 logpush: script.logpush ?? undefined,
4570 url: undefined,
4571 tags: script.tags ?? undefined,
4572 durableObjectNamespaces: {},
4573 urls: [],
4574 domain: undefined,
4575 routes: [],
4576 crons: [],
4577 },
4578 ]
4579 : [],
4580 ),
4581 ),
4582 ),
4583 );
4584 }),
4585 diff: Effect.fn(function* ({ id, fqn, news: desired, olds, output, newBindings }) {
4586 const { accountId } = yield* yield* CloudflareEnvironment;
4587 // Effect-valued `env` entries (tagged Worker classes / resource
4588 // Effects — the circular-bindings pattern) never resolve at plan
4589 // time and are dropped from persisted props by `stripUnresolved`
4590 // at the commit boundary. Their deploy-time identity is carried by
4591 // the resolved binding data, which the metadata hash below covers.
4592 // Strip them before the resolution check so a tag in `env` doesn't
4593 // force the raw-props fallback — which compares the Effect's JSON
4594 // form against the stripped stored props and re-plans an update
4595 // forever (#874).
4596 const news = stripEffects(desired);
4597 if (!isResolved(news)) return undefined;
4598 if ((output?.accountId ?? accountId) !== accountId) {
4599 return { action: "replace" };
4600 }
4601 // An account-level script and a dispatch-namespace ("user worker")
4602 // script are distinct cloud resources; moving a Worker into, out of,
4603 // or between namespaces requires a replacement.
4604 const newNamespace = resolveNamespaceName(news.namespace);
4605 const oldNamespace = output?.namespace ?? resolveNamespaceName(olds?.namespace);
4606 if (newNamespace !== oldNamespace) {
4607 return { action: "replace" };
4608 }
4609 // A version worker (version.parent), a Preview Worker
4610 // (preview.of), and a script-owning Worker are distinct cloud
4611 // resources — switching mode or parent is a replacement.
4612 const newIsVersion = news.version?.parent != null;
4613 const oldIsVersion = output?.versionOf !== undefined || olds?.version?.parent != null;
4614 if (newIsVersion !== oldIsVersion) {
4615 return { action: "replace" };
4616 }
4617 if (newIsVersion) {
4618 const newParent = resolveVersionParentName(news.version);
4619 const oldParent = output?.versionOf ?? resolveVersionParentName(olds?.version);
4620 if (newParent !== undefined && oldParent !== undefined && newParent !== oldParent) {
4621 return { action: "replace" };
4622 }
4623 }
4624 const newIsPreview = news.preview?.of != null;
4625 const oldIsPreview = output?.previewOf !== undefined || olds?.preview?.of != null;
4626 if (newIsPreview !== oldIsPreview) {
4627 return { action: "replace" };
4628 }
4629 if (newIsPreview) {
4630 const newParent = resolvePreviewParentName(news.preview);
4631 const oldParent = output?.previewOf ?? resolvePreviewParentName(olds?.preview);
4632 if (newParent !== undefined && oldParent !== undefined && newParent !== oldParent) {
4633 return { action: "replace" };
4634 }
4635 }
4636 const oldWorkerName = output?.workerName ?? (yield* createWorkerName(id, olds?.name));
4637 // Auto-generated names are engine-owned: the deployed name stays
4638 // authoritative even if the generator would name this id
4639 // differently today (a Worker replace would also destroy its
4640 // Durable Object storage). Only an explicit user-provided name
4641 // can force a replace.
4642 const workerName = news.name ?? oldWorkerName;
4643 if (workerName !== oldWorkerName) {
4644 return { action: "replace" };
4645 }
4646 if (!output) {
4647 return;
4648 }
4649 // Compare the full domain config — name, aliases (ordered: they
4650 // drive `urls` order), and redirects — against persisted state
4651 // (with legacy `domains`-list state migrated on the fly).
4652 const newDomainConfig = yield* resolveWorkerDomain(news.domain);
4653 const oldDomainConfig = stateWorkerDomain(output);
4654 const domainKey = (d: ResolvedWorkerDomain | undefined) =>
4655 d === undefined
4656 ? ""
4657 : JSON.stringify([
4658 d.name,
4659 d.aliases,
4660 [...d.redirects].sort(),
4661 d.zone ?? null,
4662 d.previews === true,
4663 ]);
4664 // An omitted `domain` unmanages the surface (#942): reconcile
4665 // carries previously-observed custom domains forward in state, so
4666 // comparing the empty desired config against those would report a
4667 // dirty plan on every deploy, forever. Only a declared `domain`
4668 // (including `null`, the explicit detach-all) participates.
4669 const domainsChanged =
4670 news.domain !== undefined && domainKey(newDomainConfig) !== domainKey(oldDomainConfig);
4671 const newCrons = normalizeCrons([
4672 ...(Array.isArray(newBindings)
4673 ? getCronBindings(newBindings as ResourceBinding<Worker["Binding"]>[])
4674 : []),
4675 ...(news.crons ?? []),
4676 ]).sort();
4677 const oldCrons = [...(output?.crons ?? [])].sort();
4678 const cronsChanged =
4679 newCrons.length !== oldCrons.length ||
4680 newCrons.some((cron, index) => cron !== oldCrons[index]);
4681 const newRouteKeys = (yield* normalizeRoutes(news.routes)).map(routeKey).sort();
4682 const oldRouteKeys = (output?.routes ?? []).map(routeKey).sort();
4683 const routesChanged =
4684 newRouteKeys.length !== oldRouteKeys.length ||
4685 newRouteKeys.some((key, index) => key !== oldRouteKeys[index]);
4686 // `url` is `urls[0]`: the canonical custom domain when one is
4687 // configured (or carried forward from state when the surface is
4688 // unmanaged, #942/#975), else the stable workers.dev URL. It's
4689 // stable across this update exactly when the recomputed value
4690 // matches what's deployed. Carry it forward as a stable only
4691 // then, so downstream resources that reference `worker.url`
4692 // (e.g. a GitHub Webhook delivery URL built via
4693 // `Output.interpolate`) resolve it to a concrete value during
4694 // planning instead of an unresolved Output — otherwise every
4695 // worker update spuriously re-updates them. Previews-only mode
4696 // and version workers derive `url` from version preview URLs —
4697 // never assumed stable here.
4698 const newWorkersDev = resolveWorkersDev(news.workersDev);
4699 const effectiveDomainConfig =
4700 news.domain !== undefined ? newDomainConfig : oldDomainConfig;
4701 const newUrl = newIsVersion
4702 ? undefined
4703 : effectiveDomainConfig !== undefined
4704 ? `https://${effectiveDomainConfig.name}`
4705 : newWorkersDev.enabled
4706 ? (output.urls ?? []).find(
4707 (u) =>
4708 isWorkersDevHostname(urlHostname(u)) &&
4709 urlHostname(u).startsWith(`${workerName}.`),
4710 )
4711 : undefined;
4712 const urlStable = newUrl !== undefined && newUrl === output.url;
4713 // `durableObjectNamespaces` maps each hosted DO class name to the
4714 // namespace id Cloudflare assigned it. Those ids are permanent for
4715 // the lifetime of a (worker, class) pair, so the map only changes
4716 // when a class is added or removed — never on a plain code/config
4717 // update. Carry it forward as a stable whenever the set of local DO
4718 // class names is unchanged, for the same reason as `url` above:
4719 // downstream resources that bind a DO namespace via
4720 // `worker.durableObjectNamespaces[name]` (e.g. a Container attached
4721 // to a DO) must resolve it to a concrete value during planning.
4722 // Otherwise the binding holds an unresolved Output, which
4723 // `diffBindings` treats as "changed", spuriously re-updating the
4724 // bound resource on every deploy. Class names are structural (not the
4725 // namespace id), so this comparison holds even when `newBindings` is
4726 // otherwise unresolved.
4727 const newDoClassNames = Array.isArray(newBindings)
4728 ? getExpectedDurableObjectClassNames(
4729 (newBindings as ResourceBinding<Worker["Binding"]>[]).flatMap(
4730 (b) => b.data.bindings ?? [],
4731 ),
4732 workerName,
4733 ).sort()
4734 : [];
4735 const oldDoClassNames = Object.keys(output.durableObjectNamespaces ?? {}).sort();
4736 const doNamespacesStable =
4737 oldWorkerName === workerName &&
4738 newDoClassNames.length === oldDoClassNames.length &&
4739 newDoClassNames.every((name, i) => name === oldDoClassNames[i]);
4740 // Rows persisted by older releases carried the script *name* in
4741 // `workerId` (interrupted precreates a provisional ""). Plan one
4742 // update even when nothing else changed, so reconcile re-records
4743 // the immutable Worker ID.
4744 const legacyWorkerId = cachedWorkerId(output.workerId, output.workerName) === undefined;
4745 if (
4746 legacyWorkerId ||
4747 domainsChanged ||
4748 routesChanged ||
4749 cronsChanged ||
4750 (yield* hasChanged(
4751 id,
4752 fqn,
4753 news,
4754 output,
4755 Array.isArray(newBindings)
4756 ? (newBindings as ResourceBinding<Worker["Binding"]>[])
4757 : undefined,
4758 accountId,
4759 ))
4760 ) {
4761 // The immutable script ID is always stable across an update —
4762 // except the healing update above, where its value is about to
4763 // change from the legacy shape to the real ID (downstream
4764 // consumers must see the fresh value).
4765 const stables: string[] = legacyWorkerId ? [] : ["workerId"];
4766 if (oldWorkerName === workerName) {
4767 stables.push("workerName");
4768 }
4769 if (urlStable) {
4770 stables.push("url");
4771 }
4772 if (doNamespacesStable) {
4773 stables.push("durableObjectNamespaces");
4774 }
4775 return { action: "update", stables: stables.length > 0 ? stables : undefined };
4776 }
4777 // Machine-local source paths and resource-backed `env` values have
4778 // already been compared by their content hashes and canonical
4779 // binding data. Ignore those representations in the raw fallback so
4780 // checkout paths and resource attribute projections do not force
4781 // perpetual updates (#745).
4782 if (Array.isArray(newBindings)) {
4783 const normalizeComparedProps = (props: WorkerProps) => {
4784 // `codeUpdateStrategy` applies to a deploy, not to stored
4785 // state: changing it alone must not redeploy (and so reset)
4786 // the Worker's Durable Objects.
4787 const { env: _env, codeUpdateStrategy: _codeUpdateStrategy, ...rest } = props;
4788 return {
4789 ...rest,
4790 ...(props.main !== undefined ? { main: "<source>" } : undefined),
4791 ...(props.assets
4792 ? {
4793 assets: {
4794 ...(typeof props.assets === "string" ? undefined : props.assets),
4795 directory: "<source>",
4796 },
4797 }
4798 : undefined),
4799 ...(props.vite ? { vite: { ...props.vite, rootDir: "<source>" } } : undefined),
4800 };
4801 };
4802 if (
4803 olds !== undefined &&
4804 !havePropsChanged(normalizeComparedProps(olds), normalizeComparedProps(news))
4805 ) {
4806 return { action: "noop" };
4807 }
4808 }
4809 }),
4810 observe: Effect.fn(function* ({ id, news }) {
4811 // The script precreate (or, for a dispatch-namespace worker,
4812 // reconcile) writes to. A version/preview worker uploads to its
4813 // parent's script and claims none of its own.
4814 if (news.version?.parent != null || news.preview?.of != null) return undefined;
4815 // Neither name nor namespace can be checked until it resolves.
4816 if (!isResolved(news.name) || !isResolved(news.namespace)) return Unresolved;
4817 const { accountId } = yield* yield* CloudflareEnvironment;
4818 const name = yield* createWorkerName(id, news.name);
4819 const namespace = resolveNamespaceName(news.namespace);
4820 if (
4821 namespace !== undefined &&
4822 (yield* findDispatchNamespaceScript(accountId, namespace, name)) === undefined
4823 ) {
4824 return undefined;
4825 }
4826 const settings = yield* getScriptSettings(accountId, name, namespace).pipe(
4827 Effect.catchTags({
4828 WorkerNotFound: () => Effect.undefined,
4829 WorkerHasNoVersions: () => Effect.undefined,
4830 DispatchNamespaceScriptNotFound: () => Effect.undefined,
4831 DispatchNamespaceNotFound: () => Effect.undefined,
4832 }),
4833 );
4834 if (settings === undefined) return undefined;
4835 const observed = { workerName: name };
4836 return hasAlchemyWorkerTags(id, settings.tags ?? []) ? observed : Unowned(observed);
4837 }),
4838 precreate: Effect.fn(function* ({ id, news, session, bindings }) {
4839 const { accountId } = yield* yield* CloudflareEnvironment;
4840 yield* assertCloudflareTelemetryCompatibility(news as WorkerProps, bindings);
4841 const name = yield* createWorkerName(id, news.name);
4842 // A version worker uploads to its parent's script during
4843 // reconcile; pre-creating a placeholder script under this
4844 // resource's own generated name would leave a stray script behind.
4845 // Version workers can't host Durable Object / Workflow classes, so
4846 // no placeholder is needed for circular bindings either. (`news`
4847 // is raw here — `version.parent` may be an unresolved ref, but its
4848 // *presence* is statically known.)
4849 if (news.version?.parent != null || news.preview?.of != null) {
4850 yield* Effect.logInfo(
4851 `Cloudflare Worker precreate: skipping stub for ${news.preview?.of != null ? "Preview" : "version"} worker ${id}`,
4852 );
4853 return {
4854 // Provisional: a version worker resolves its parent's
4855 // immutable ID at reconcile — nothing observes this stub row
4856 // (version workers have no circular bindings).
4857 workerId: "",
4858 workerName: name,
4859 namespace: undefined,
4860 logpush: undefined,
4861 url: undefined,
4862 tags: undefined,
4863 durableObjectNamespaces: {},
4864 accountId,
4865 urls: [],
4866 domain: undefined,
4867 routes: [],
4868 crons: [],
4869 } satisfies Worker["Attributes"];
4870 }
4871 // A Workers for Platforms user worker can't be pre-created: precreate
4872 // runs on raw, *unresolved* props (so resources in a dependency cycle
4873 // can signal early), meaning a `namespace` that references the
4874 // namespace resource is still an unresolved Output here, and the
4875 // namespace itself may not be deployed yet. There's also nothing to
4876 // pre-create — a user worker is dispatched to by name, never bound to
4877 // circularly. Return a stub; `reconcile` performs the real upload
4878 // once props resolve and the namespace exists.
4879 if (news.namespace != null) {
4880 yield* Effect.logInfo(
4881 `Cloudflare Worker precreate: skipping stub for dispatch-namespace worker ${name}`,
4882 );
4883 return {
4884 // Provisional: reconcile records the real immutable ID from
4885 // the dispatch upload — nothing observes this stub row (user
4886 // workers are dispatched by name, never bound circularly).
4887 workerId: "",
4888 workerName: name,
4889 // Recorded only once resolved: cleanup deletes from this
4890 // namespace, and must not fall back to the account endpoint.
4891 namespace: isResolved(news.namespace)
4892 ? resolveNamespaceName(news.namespace)
4893 : undefined,
4894 logpush: undefined,
4895 url: undefined,
4896 tags: undefined,
4897 durableObjectNamespaces: {},
4898 accountId,
4899 urls: [],
4900 domain: undefined,
4901 routes: [],
4902 crons: [],
4903 } satisfies Worker["Attributes"];
4904 }
4905 const dispatchNamespace = resolveNamespaceName(news.namespace);
4906 const exportMap = news.exports ?? {};
4907 // A worker hosts Durable Object classes from two independent sources:
4908 // Effect-native DO *exports* (classes defined in the worker entry) and
4909 // DO *bindings* declared in `env` — e.g. a bare `Cloudflare.DurableObject`
4910 // that fronts a Container image. The placeholder must declare *every*
4911 // hosted class so each namespace is created here. A class that exists
4912 // only as a binding (a container-fronted DO) is otherwise absent from
4913 // this stub, and a resource caught in a worker<->container dependency
4914 // cycle — which resolves `worker.durableObjectNamespaces[className]`
4915 // against the precreate stub rather than the final reconcile output —
4916 // fails because the namespace id it needs never surfaced.
4917 const exportDerived = Object.keys(exportMap)
4918 .filter((logicalId) => isDurableObjectExport(exportMap[logicalId]))
4919 .map((logicalId) => ({ logicalId, className: logicalId }));
4920 // Transfer-destination classes are excluded from the placeholder
4921 // entirely (class list, bindings, tags): Cloudflare forbids
4922 // creating the destination class of a `transferred_classes`
4923 // migration ahead of the transfer, so `reconcile` must perform it
4924 // with the real upload. (`transferredFrom` may still be an
4925 // unresolved Output here — precreate runs on raw props — but only
4926 // its presence matters.)
4927 const durableObjects = mergeDurableObjectClasses(
4928 exportDerived,
4929 getDurableObjectBindings(bindings, name),
4930 ).filter((binding) => !binding.transferredFrom);
4931 const doClasses = durableObjects.map((binding) => binding.className);
4932 // Only attach container metadata for classes actually fronted by a
4933 // Container binding (mirrors reconcile's `containerClasses`).
4934 // Mapping every DO class to a container would wrongly mark plain DOs
4935 // as container-backed in the placeholder.
4936 yield* assertBindingContainersOnAsyncClasses(
4937 bindings.flatMap((b) => b.data.containers ?? []),
4938 exportDerived.map((binding) => binding.className),
4939 );
4940 const containers = Array.from(
4941 new Set(bindings.flatMap((b) => (b.data.containers ?? []).map((c) => c.className))),
4942 ).map((className) => ({ className }));
4943 const alchemyDoTags = encodeDurableObjectTags(durableObjects);
4944 const alchemyTags = [...createAlchemyWorkerTags(id), ...alchemyDoTags];
4945 const tags = Array.from(new Set([...alchemyTags, ...(news.tags ?? [])]));
4946 yield* validateWorkerTags(name, tags, alchemyTags.length);
4947 yield* Effect.logInfo(`Cloudflare Worker precreate: starting ${name}`);
4948 yield* Effect.logInfo(
4949 `Cloudflare Worker precreate: durable objects ${JSON.stringify(durableObjects)}`,
4950 );
4951 const existingSettings = yield* getScriptSettings(
4952 accountId,
4953 name,
4954 dispatchNamespace,
4955 ).pipe(
4956 // A freshly pre-created stub can briefly report "has no
4957 // versions" before its first version registers — treat it the
4958 // same as a missing worker (nothing to adopt yet). For a user
4959 // worker the dispatch-namespace endpoints report a missing
4960 // script as `DispatchNamespaceScriptNotFound` (and a missing
4961 // namespace as `DispatchNamespaceNotFound`).
4962 Effect.catchTags({
4963 WorkerNotFound: () => Effect.undefined,
4964 WorkerHasNoVersions: () => Effect.undefined,
4965 DispatchNamespaceScriptNotFound: () => Effect.undefined,
4966 DispatchNamespaceNotFound: () => Effect.undefined,
4967 }),
4968 );
4969 let durableObjectNamespaces = getDurableObjects(existingSettings?.bindings);
4970
4971 let placeholder: { tag?: string | null } | undefined;
4972 if (existingSettings) {
4973 // Engine has already cleared this resource for write via
4974 // `observe` or `read` + AdoptPolicy. Either we own it (matching
4975 // tags) or the user opted in to a takeover (`--adopt` / `adopt(true)`).
4976 yield* Effect.logInfo(`Cloudflare Worker precreate: reusing existing ${name}`);
4977 } else {
4978 yield* session.note("Pre-creating worker...", { kind: "status" });
4979 const compatibility = getCompatibility(news);
4980 const mainModule = "main.js";
4981 const placeholderScript = makePlaceholderScript(doClasses);
4982 placeholder = yield* putWorkerScript({
4983 accountId,
4984 scriptName: name,
4985 dispatchNamespace,
4986 metadata: {
4987 mainModule,
4988 bindings:
4989 doClasses.length > 0
4990 ? doClasses.map((className) => ({
4991 type: "durable_object_namespace" as const,
4992 name: className,
4993 className,
4994 }))
4995 : undefined,
4996 // Spreading `getCompatibility` here would set `date`/`flags`,
4997 // which are not metadata keys — the placeholder would upload
4998 // with no compatibility date or flags at all.
4999 compatibilityDate: compatibility.date,
5000 compatibilityFlags: compatibility.flags,
Showing first 5,000 of 6,174 lines. View raw