The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 03:37 UTC
| 1 | import * as workers from "@distilled.cloud/cloudflare/workers"; |
| 2 | import { type MemoOptions } from "alchemy/Command/Memo"; |
| 3 | import type { Dependencies } from "alchemy/Dependencies"; |
| 4 | import type { DnsConfig } from "alchemy/DNS/Adapter"; |
| 5 | import type { InputProps } from "alchemy/Input"; |
| 6 | import type { Named, Tag } from "alchemy/Named"; |
| 7 | import type * as Output from "alchemy/Output"; |
| 8 | import { |
| 9 | Platform, |
| 10 | type Main, |
| 11 | type MainRpc, |
| 12 | type MakeShape, |
| 13 | type PlatformIdentity, |
| 14 | type PlatformProps, |
| 15 | type PlatformServices, |
| 16 | } from "alchemy/Platform"; |
| 17 | import { |
| 18 | isResourceOfType, |
| 19 | Resource, |
| 20 | type ResourceClass, |
| 21 | type ResourceClassLike, |
| 22 | } from "alchemy/Resource"; |
| 23 | import type { Rpc } from "alchemy/Rpc"; |
| 24 | import type { RuntimeContext } from "alchemy/RuntimeContext"; |
| 25 | import type { Self as SelfService } from "alchemy/Self"; |
| 26 | import { isPathWithin } from "alchemy/Util/isPathWithin"; |
| 27 | import type { WebhookHost } from "alchemy/WebhookHost"; |
| 28 | import type { ConfigError } from "effect/Config"; |
| 29 | import type * as Duration from "effect/Duration"; |
| 30 | import * as Effect from "effect/Effect"; |
| 31 | import type * as Layer from "effect/Layer"; |
| 32 | import * as Redacted from "effect/Redacted"; |
| 33 | import path from "pathe"; |
| 34 | import { CloudflareEnvironment } from "../CloudflareEnvironment.ts"; |
| 35 | import type { Container } from "../Containers/Container.ts"; |
| 36 | import type { DevContainerImage } from "../Containers/ContainerApplication.ts"; |
| 37 | import type { DomainClass } from "../Domain/Version.ts"; |
| 38 | import type { DevOrigin } from "../Hyperdrive/Connection.ts"; |
| 39 | import type { Providers } from "../Providers.ts"; |
| 40 | import type { DispatchNamespace } from "../WorkersForPlatforms/DispatchNamespace.ts"; |
| 41 | import type { WorkflowBinding, WorkflowLike } from "../Workflows/Workflow.ts"; |
| 42 | import type { Reference as ZoneReference } from "../Zone/lookup.ts"; |
| 43 | import { type Assets, type AssetsConfig, type AssetsProps } from "./Assets.ts"; |
| 44 | import { Request } from "./Request.ts"; |
| 45 | import type { ModuleRule } from "./Sources/Prebuilt.ts"; |
| 46 | import type { WorkerBuildOptions } from "./Sources/Rolldown.ts"; |
| 47 | import type { WorkerAccessConfig, WorkerAccessIdentity } from "./WorkerAccess.ts"; |
| 48 | import { bindWorkerAsyncBindings } from "./WorkerAsyncBindings.ts"; |
| 49 | import type { WorkerBinding, WorkerBindingResource } from "./WorkerBinding.ts"; |
| 50 | import { transformWorkerDomainProps } from "./WorkerDomainDns.ts"; |
| 51 | import { WorkerEnvironment, WorkerTypeId } from "./WorkerRuntime.ts"; |
| 52 | import { |
| 53 | makeWorkerRuntimeContext, |
| 54 | type WorkerExport, |
| 55 | type WorkerRuntimeContext, |
| 56 | } from "./WorkerRuntimeContext.ts"; |
| 57 | |
| 58 | export * from "./WorkerRuntime.ts"; |
| 59 | export { WorkerDomainDnsError } from "./WorkerDomainDns.ts"; |
| 60 | |
| 61 | export const isWorker = <T>(value: T): value is T & Worker => isResourceOfType(value, WorkerTypeId); |
| 62 | |
| 63 | /** |
| 64 | * Assets configuration that includes a pre-computed hash. |
| 65 | * When hash is provided, it's used directly for diffing instead of computing from directory contents. |
| 66 | * This is useful when integrating with Build resources that produce a deterministic hash. |
| 67 | */ |
| 68 | export interface AssetsWithHash extends AssetsProps { |
| 69 | /** |
| 70 | * Pre-computed hash of the assets. When provided, this hash is used for diffing |
| 71 | * to determine if the worker needs to be redeployed. |
| 72 | */ |
| 73 | hash: string; |
| 74 | } |
| 75 | |
| 76 | export interface WorkerObservability extends Exclude< |
| 77 | workers.PutScriptRequest["metadata"]["observability"], |
| 78 | undefined |
| 79 | > {} |
| 80 | |
| 81 | export interface WorkerLimits extends Exclude< |
| 82 | workers.PutScriptRequest["metadata"]["limits"], |
| 83 | undefined |
| 84 | > {} |
| 85 | |
| 86 | export interface WorkerCache extends Exclude< |
| 87 | workers.PutScriptRequest["metadata"]["cacheOptions"], |
| 88 | undefined |
| 89 | > {} |
| 90 | |
| 91 | /** |
| 92 | * Per-entrypoint settings for one of a Worker's exports, keyed in |
| 93 | * {@link WorkerProps.entrypoints} by export name. |
| 94 | */ |
| 95 | export interface WorkerEntrypointSettings { |
| 96 | /** |
| 97 | * Workers Cache override for this entrypoint. `enabled` replaces the |
| 98 | * Worker-wide `cache.enabled` for calls into this entrypoint only; |
| 99 | * `crossVersionCache` stays Worker-wide. |
| 100 | */ |
| 101 | cache?: { |
| 102 | /** Whether Workers Cache is checked before invoking this entrypoint. */ |
| 103 | enabled: boolean; |
| 104 | }; |
| 105 | } |
| 106 | |
| 107 | export type WorkerPlacement = Exclude<workers.PutScriptRequest["metadata"]["placement"], undefined>; |
| 108 | |
| 109 | /** |
| 110 | * How a deploy rolls new code out to the Worker's running Durable Objects. |
| 111 | * |
| 112 | * - `{ mode: "deferred" }` — an active object keeps running its current code |
| 113 | * while it waits to hibernate, for up to `maxDelay`, so in-flight work can |
| 114 | * finish. Hibernation API WebSockets stay connected when the object picks |
| 115 | * up the new code after hibernating. |
| 116 | * - `{ mode: "immediate" }` — every object resets onto the new code as soon |
| 117 | * as the deploy lands. |
| 118 | * |
| 119 | * Deferral is best effort: an object can still reset before `maxDelay` |
| 120 | * elapses, e.g. during a Cloudflare runtime update. |
| 121 | */ |
| 122 | export type WorkerCodeUpdateStrategy = |
| 123 | | { mode: "immediate" } |
| 124 | | { |
| 125 | mode: "deferred"; |
| 126 | /** |
| 127 | * The longest an active Durable Object may keep running old code before |
| 128 | * it is forced onto the new code — e.g. `"1 minute"`, `"30 seconds"`, or |
| 129 | * a `Duration`. Between 0 and 24 hours, millisecond precision. |
| 130 | * @default "5 minutes" |
| 131 | */ |
| 132 | maxDelay?: Duration.Input; |
| 133 | }; |
| 134 | |
| 135 | export type WorkerServices = |
| 136 | | Worker |
| 137 | | WebhookHost |
| 138 | | Request |
| 139 | | WorkerEnvironment |
| 140 | | CloudflareEnvironment |
| 141 | | Container.Application<any> |
| 142 | | SelfService; |
| 143 | |
| 144 | export type WorkerShape<Req = never> = Main<WorkerServices | Req> & MainRpc<WorkerServices | Req>; |
| 145 | |
| 146 | export type WorkerEnv = Record< |
| 147 | string, |
| 148 | | string |
| 149 | | number |
| 150 | | boolean |
| 151 | | null |
| 152 | | readonly unknown[] |
| 153 | | { readonly [key: string]: unknown } |
| 154 | | Redacted.Redacted<string> |
| 155 | >; |
| 156 | |
| 157 | export type WorkerBindingProps = { |
| 158 | [bindingName in string]: WorkerBindingResource | Effect.Effect<WorkerBindingResource, any, any>; |
| 159 | }; |
| 160 | |
| 161 | export type NormalizedBindings< |
| 162 | Bindings extends WorkerBindingProps = {}, |
| 163 | AssetsConfig extends WorkerAssetsConfig | undefined = undefined, |
| 164 | > = { |
| 165 | // Containers are declarations and Outputs stay deferred at declaration time. |
| 166 | [B in keyof Bindings]: Bindings[B] extends Container.Decl.Any | Output.Output<any, any> |
| 167 | ? Bindings[B] |
| 168 | : Bindings[B] extends Effect.Effect<infer T extends WorkerBindingResource, any, any> |
| 169 | ? T |
| 170 | : Extract<Bindings[B], WorkerBindingResource>; |
| 171 | } & (undefined extends AssetsConfig ? {} : { ASSETS: Assets }); |
| 172 | |
| 173 | /** |
| 174 | * An external Worker's declared `env` as exposed on its declaration |
| 175 | * (`worker.env`): every entry is the binding value as declared (with |
| 176 | * Effect-valued entries resolved), except a Workflow binding, which surfaces |
| 177 | * as a {@link WorkflowBinding} carrying the Workflow's physical name as an |
| 178 | * `Output` of the current deploy. |
| 179 | */ |
| 180 | export type WorkerEnvBindings<Bindings> = { |
| 181 | readonly [B in keyof Bindings]: Bindings[B] extends WorkflowLike<infer Params> |
| 182 | ? WorkflowBinding<Params> |
| 183 | : Bindings[B]; |
| 184 | }; |
| 185 | |
| 186 | export type WorkerAssetsConfig = |
| 187 | | string |
| 188 | | (AssetsConfig & { directory?: never }) |
| 189 | | AssetsProps |
| 190 | | AssetsWithHash; |
| 191 | |
| 192 | /** |
| 193 | * Fine-grained control over the Worker's `workers.dev` surface. The two |
| 194 | * toggles are independent on the Cloudflare API. |
| 195 | */ |
| 196 | export interface WorkersDevConfig { |
| 197 | /** |
| 198 | * Serve the Worker at its stable `workers.dev` URL |
| 199 | * (`https://<worker-name>.<account-subdomain>.workers.dev`). |
| 200 | * @default true |
| 201 | */ |
| 202 | enabled?: boolean; |
| 203 | /** |
| 204 | * Enable version preview URLs — a distinct |
| 205 | * `https://<version-prefix>-<worker-name>.<account-subdomain>.workers.dev` |
| 206 | * URL per uploaded version, plus stable aliased preview URLs |
| 207 | * (`https://<alias>-...`) for versions uploaded with an alias. |
| 208 | * |
| 209 | * When previews are enabled but {@link enabled} is `false`, the current |
| 210 | * version's preview URL becomes the Worker's primary `url` output. |
| 211 | * @default true |
| 212 | */ |
| 213 | previewsEnabled?: boolean; |
| 214 | } |
| 215 | |
| 216 | /** |
| 217 | * The Worker's custom-domain configuration: one canonical hostname, plus |
| 218 | * optional aliases that also serve the Worker and redirect hostnames that |
| 219 | * 301 to the canonical name. |
| 220 | */ |
| 221 | export interface WorkerDomainConfig { |
| 222 | /** |
| 223 | * The canonical hostname (e.g. `"example.com"`). Attached to the Worker |
| 224 | * as a Cloudflare custom domain — DNS record and edge certificate are |
| 225 | * managed automatically. The Cloudflare zone is inferred from the |
| 226 | * hostname unless {@link zoneId}, {@link zone}, or {@link zoneName} is |
| 227 | * set. The zone must already exist in the account. |
| 228 | * |
| 229 | * When set, `https://<name>` is the Worker's primary `url` output. |
| 230 | */ |
| 231 | name: string; |
| 232 | /** |
| 233 | * Additional hostnames that serve the Worker (e.g. `"www.example.com"`, |
| 234 | * `"api.example.com"`). Each is attached as its own custom domain. |
| 235 | * Order matters: aliases follow `name` in the `urls` output. |
| 236 | */ |
| 237 | aliases?: string[]; |
| 238 | /** |
| 239 | * Hostnames that permanently redirect (HTTP 301, path and query |
| 240 | * preserved) to {@link name} — e.g. `"old.example.com"`. Each is |
| 241 | * attached as a custom domain (for DNS + TLS) with a redirect rule in |
| 242 | * the zone's `http_request_dynamic_redirect` phase, which runs before |
| 243 | * the Worker — redirected requests never invoke it. Redirect hostnames |
| 244 | * serve no content, so they appear in the `domain` output but never in |
| 245 | * `urls`. |
| 246 | */ |
| 247 | redirects?: string[]; |
| 248 | /** |
| 249 | * Cloudflare zone ID for every hostname in this config. Equivalent to |
| 250 | * Wrangler's `zone_id`. Wins over {@link zone} / {@link zoneName}. |
| 251 | * When omitted, each hostname's zone is looked up by name |
| 252 | * (`GET /zones?name=`), not by listing the account's first page of zones. |
| 253 | */ |
| 254 | zoneId?: string; |
| 255 | /** |
| 256 | * Cloudflare zone name, e.g. `"example.com"`. Equivalent to Wrangler's |
| 257 | * `zone_name`. |
| 258 | */ |
| 259 | zoneName?: string; |
| 260 | /** |
| 261 | * Zone reference — a zone ID, zone name, or `{ zoneId, name? }` object. |
| 262 | * Alternative to {@link zoneId} / {@link zoneName}. |
| 263 | */ |
| 264 | zone?: ZoneReference; |
| 265 | /** |
| 266 | * Opt into custom-domain Worker Previews (private beta). When `true`, |
| 267 | * Previews of this Worker are served at `<preview-name>.<name>` (and a |
| 268 | * pinned `<deployment-id>-<preview-name>.<name>` per deploy). Cloudflare |
| 269 | * provisions a wildcard DNS record and certificate. Equivalent to |
| 270 | * Wrangler's `previews_enabled` on a custom-domain route. |
| 271 | * |
| 272 | * Unset, the field is not sent to Cloudflare — existing custom-domain |
| 273 | * attaches are unchanged. This is a **parent** setting: enable it on |
| 274 | * the production Worker, not on the Preview Worker. A dedicated Preview |
| 275 | * hostname (`previews.example.com`) avoids colliding with existing |
| 276 | * subdomains. |
| 277 | * |
| 278 | * @default false |
| 279 | */ |
| 280 | previews?: boolean; |
| 281 | /** |
| 282 | * The DNS host that publishes this domain's records. Omit it (or pass |
| 283 | * `Cloudflare.DNS.Adapter()`) for hostnames in a Cloudflare zone of the |
| 284 | * account: they attach as native custom domains, exactly as without |
| 285 | * `dns`. |
| 286 | * |
| 287 | * Any other adapter (`AWS.Route53.Adapter()`, `Hetzner.DNS.Adapter()`) |
| 288 | * serves the hostnames through |
| 289 | * [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/start/advanced-settings/worker-as-origin/): |
| 290 | * {@link name} and each alias become a |
| 291 | * `Cloudflare.CustomHostname.CustomHostname` on the SaaS zone |
| 292 | * ({@link zoneId} / {@link zone} / {@link zoneName}, required), the |
| 293 | * DNS host publishes their ownership and certificate-validation TXT |
| 294 | * records plus a `CNAME` to {@link cnameTarget}, and the Worker gets a |
| 295 | * `<hostname>/*` route on the SaaS zone instead of a custom domain. |
| 296 | * {@link redirects} and {@link previews} are not supported on this path, |
| 297 | * and the Worker's `url` stays its `workers.dev` URL. Declare the SaaS |
| 298 | * zone's `Cloudflare.CustomHostname.FallbackOrigin` once yourself — |
| 299 | * several Workers can share one SaaS zone. |
| 300 | * |
| 301 | * See [DNS Adapters](/infrastructure-as-code/dns-adapters). |
| 302 | */ |
| 303 | dns?: DnsConfig; |
| 304 | /** |
| 305 | * Hostname in the SaaS zone that custom hostnames CNAME to, typically |
| 306 | * the zone's fallback origin (`FallbackOrigin`'s `origin`). Required |
| 307 | * when {@link dns} names a DNS host other than Cloudflare; unused |
| 308 | * otherwise. |
| 309 | */ |
| 310 | cnameTarget?: string; |
| 311 | } |
| 312 | |
| 313 | export interface WorkerRouteConfig { |
| 314 | /** |
| 315 | * URL pattern to match incoming requests against, e.g. |
| 316 | * `"subdomain.example.com/*"` or `"example.com/api/*"`. |
| 317 | */ |
| 318 | pattern: string; |
| 319 | /** |
| 320 | * Cloudflare zone ID. Equivalent to Wrangler's `zone_id`. |
| 321 | */ |
| 322 | zoneId?: string; |
| 323 | /** |
| 324 | * Cloudflare zone name, e.g. `"example.com"`. Equivalent to Wrangler's |
| 325 | * `zone_name`. |
| 326 | */ |
| 327 | zoneName?: string; |
| 328 | /** |
| 329 | * Zone reference — a zone ID, zone name, or `{ zoneId, name? }` object. |
| 330 | * Alternative to `zoneId` / `zoneName`. |
| 331 | */ |
| 332 | zone?: ZoneReference; |
| 333 | } |
| 334 | |
| 335 | /** |
| 336 | * Version-affinity configuration — keeps each user on one version for the |
| 337 | * duration of a gradual rollout. |
| 338 | * |
| 339 | * Percentages route each request independently, so one user can bounce |
| 340 | * between versions mid-rollout. Cloudflare pins a request to a version |
| 341 | * deterministically when it carries a `Cloudflare-Workers-Version-Key` |
| 342 | * header: the key is hashed and assigned a version from the current |
| 343 | * percentages, so equal keys always land on the same version, and pinned |
| 344 | * users only move forward as percentages rise. |
| 345 | * |
| 346 | * Setting `affinity` provisions that header as infrastructure: a `rewrite` |
| 347 | * Transform Rule in the `http_request_late_transform` phase of every zone |
| 348 | * the Worker serves on (custom domains and zone routes), scoped to the |
| 349 | * Worker's hostnames, filling the header from the configured source. The |
| 350 | * rule is updated in place as the config changes and removed when |
| 351 | * `affinity` is removed or the Worker is destroyed; other rules in the |
| 352 | * zone's shared entrypoint are left untouched. |
| 353 | * |
| 354 | * Exactly one of {@link cookie}, {@link header}, or {@link key} may be |
| 355 | * set; {@link ip} combines with `cookie`/`header` as a fallback or stands |
| 356 | * alone as the sole source. |
| 357 | * |
| 358 | * Transform Rules only see **zone traffic** — the Worker must have a |
| 359 | * `domain` or `routes` (or, with `version.parent`, the parent must). |
| 360 | * A workers.dev-only Worker fails the deploy with |
| 361 | * `WorkerVersionConfigError`; on the bare workers.dev URL clients must |
| 362 | * send the header themselves. |
| 363 | */ |
| 364 | export interface WorkerVersionAffinity { |
| 365 | /** |
| 366 | * Pin by the value of this request cookie (e.g. a session id). Requests |
| 367 | * without the cookie fall back to {@link ip} when set, otherwise they |
| 368 | * route independently by percentage. |
| 369 | */ |
| 370 | cookie?: string; |
| 371 | /** |
| 372 | * Pin by the value of this request header (e.g. a tenant or user id |
| 373 | * your edge already stamps, or a stable auth claim forwarded as a |
| 374 | * header). Requests without the header fall back to {@link ip} when |
| 375 | * set, otherwise they route independently by percentage. |
| 376 | */ |
| 377 | header?: string; |
| 378 | /** |
| 379 | * Pin by client IP. On its own (`{ ip: true }`) every request is keyed |
| 380 | * by `ip.src`; combined with {@link cookie} or {@link header} it is the |
| 381 | * fallback for requests missing the primary source (e.g. sticky by |
| 382 | * session cookie, falling back to sticky IP before the cookie is set). |
| 383 | */ |
| 384 | ip?: boolean; |
| 385 | /** |
| 386 | * Escape hatch: a raw [Rules-language](https://developers.cloudflare.com/ruleset-engine/rules-language/) |
| 387 | * expression that computes the version key — e.g. a JWT claim via API |
| 388 | * Shield's `http.request.jwt.claims`, or any composite of request |
| 389 | * fields. Applied to every request on the Worker's hostnames; cannot be |
| 390 | * combined with the other sources. |
| 391 | */ |
| 392 | key?: string; |
| 393 | } |
| 394 | |
| 395 | /** |
| 396 | * Versioning configuration for a Worker deploy — controls Worker |
| 397 | * [versions and gradual deployments](https://developers.cloudflare.com/workers/configuration/versions-and-deployments/). |
| 398 | * |
| 399 | * Two modes, selected by {@link parent}: |
| 400 | * |
| 401 | * - **Version worker** (`parent` set): instead of creating its own script, |
| 402 | * this Worker uploads an immutable *version* to the referenced parent |
| 403 | * Worker's script. With `traffic: 0` (the default) the parent's live |
| 404 | * deployment is untouched and the version is reachable only at its |
| 405 | * preview URL (`<version-prefix>-<name>.<subdomain>.workers.dev`) — |
| 406 | * the PR-preview use case. With `traffic > 0` the version becomes a |
| 407 | * canary taking that percentage of the parent's traffic. |
| 408 | * - **Gradual rollout** (`parent` omitted): when this Worker deploys |
| 409 | * itself, the newly uploaded version receives {@link traffic} percent |
| 410 | * and the currently-live version keeps the remainder, instead of the |
| 411 | * default 100% cutover. |
| 412 | * |
| 413 | * A gradual rollout carries only what a version can: code, static assets, |
| 414 | * bindings, compatibility settings, and cache configuration. A deploy that |
| 415 | * creates, renames, deletes or moves Durable Object classes must go out at |
| 416 | * 100% (class lifecycle changes cannot ride a rollout), and script-level settings |
| 417 | * (tags, observability, limits, placement, logpush) keep their live |
| 418 | * values until the next full deploy. |
| 419 | */ |
| 420 | export interface WorkerVersionOptions { |
| 421 | /** |
| 422 | * The Worker that owns the script this version is uploaded to. Accepts a |
| 423 | * Worker reference — typically `yield* Cloudflare.Worker.ref(id, { stage, |
| 424 | * stack })` for a Worker deployed in another stage/stack, or a |
| 425 | * locally-declared Worker — or a literal script name as an escape hatch. |
| 426 | * |
| 427 | * When set, this resource does not create a script of its own: it |
| 428 | * uploads a version (code + static assets + bindings + compatibility |
| 429 | * settings) to the parent's script. Script-level settings apply immediately |
| 430 | * to *all* versions of the parent, so they cannot be set on a version worker — |
| 431 | * `name`, `namespace`, `crons`, `domain`, `routes`, `tags`, |
| 432 | * `logpush`, `observability`, `placement`, `limits`, and `subdomain` are |
| 433 | * rejected, as are locally-hosted Durable Object or Workflow classes |
| 434 | * (their migrations would mutate the parent). |
| 435 | * |
| 436 | * Changing the parent replaces the resource (a version belongs to |
| 437 | * exactly one script). |
| 438 | */ |
| 439 | parent?: string | Worker; |
| 440 | /** |
| 441 | * Percentage of traffic (0–100) the newly uploaded version receives; the |
| 442 | * currently-live version keeps the remainder. Cloudflare deployments |
| 443 | * split between at most two versions, so one canary can be active per |
| 444 | * script at a time. |
| 445 | * |
| 446 | * With {@link parent} set, defaults to `0`: the version is |
| 447 | * preview-URL-only and the parent's live deployment is untouched. |
| 448 | * Without `parent`, defaults to `100` (today's full cutover); `0` means |
| 449 | * "upload the version without deploying it" (the equivalent of |
| 450 | * `wrangler versions upload`). |
| 451 | * |
| 452 | * Percentages replace the previous deployment, they never add. Each |
| 453 | * versioned deploy splits its new version against the *stable* version — |
| 454 | * the majority holder of the current deployment — so deploying at 10 and |
| 455 | * then at 20 yields the second version at 20% against the stable version |
| 456 | * at 80%, with the earlier 10% version dropped from routing entirely |
| 457 | * (still uploaded, but unreachable even via a version-override header). |
| 458 | * With unchanged code that replacement is exactly a ramp; with changed |
| 459 | * code it swaps canaries. The first deploy of a script always goes to |
| 460 | * 100%, since there is no previous version to split with. |
| 461 | * |
| 462 | * Note that a subsequent full deploy of the parent (or of this Worker |
| 463 | * itself, at the default 100) resets traffic to 100% of its own new |
| 464 | * version. |
| 465 | */ |
| 466 | traffic?: number; |
| 467 | /** |
| 468 | * Preview-URL alias for the uploaded version. Aliased preview URLs |
| 469 | * (`<alias>-<name>.<subdomain>.workers.dev`) are stable — each upload |
| 470 | * with the same alias re-points the URL at the new version — which is |
| 471 | * what makes them useful as shareable PR-preview links and lets |
| 472 | * `Worker.URL` resolve before the version exists. |
| 473 | * |
| 474 | * For a version worker ({@link parent} set) an alias is derived |
| 475 | * automatically from the stack, stage, and logical id, so every version |
| 476 | * worker gets a stable preview URL out of the box; set this to override |
| 477 | * it. Must start with a lowercase letter, contain only lowercase |
| 478 | * letters, digits, and dashes, and `<alias>-<worker-name>` must fit in |
| 479 | * 63 characters (a DNS label). |
| 480 | */ |
| 481 | alias?: string; |
| 482 | /** |
| 483 | * Keep each user on one version for the duration of the rollout by |
| 484 | * pinning them to a stable request property — a session cookie, a |
| 485 | * header, the client IP, or a raw Rules-language expression: |
| 486 | * |
| 487 | * ```typescript |
| 488 | * version: { |
| 489 | * traffic: 10, |
| 490 | * // sticky by session cookie, falling back to sticky IP |
| 491 | * affinity: { cookie: "session_id", ip: true }, |
| 492 | * } |
| 493 | * ``` |
| 494 | * |
| 495 | * Provisions a Transform Rule that fills the |
| 496 | * `Cloudflare-Workers-Version-Key` header on the zones the Worker |
| 497 | * serves on — the Worker (or, with {@link parent}, the parent) must |
| 498 | * have a `domain` or `routes`. With `parent` set, the rule lands on the |
| 499 | * parent's zones, pinning users across the canary split. See |
| 500 | * {@link WorkerVersionAffinity}. |
| 501 | */ |
| 502 | affinity?: WorkerVersionAffinity; |
| 503 | /** |
| 504 | * Human-readable annotation attached to the uploaded version, shown in |
| 505 | * the Cloudflare dashboard and `wrangler versions list`. |
| 506 | */ |
| 507 | message?: string; |
| 508 | /** |
| 509 | * Machine-readable tag annotation attached to the uploaded version |
| 510 | * (e.g. a git commit SHA or PR number). |
| 511 | */ |
| 512 | tag?: string; |
| 513 | } |
| 514 | |
| 515 | /** |
| 516 | * Worker Preview configuration — uploads this Worker as a first-class |
| 517 | * [Preview](https://developers.cloudflare.com/workers/previews/) of |
| 518 | * another Worker's script instead of creating a script of its own. |
| 519 | * |
| 520 | * Distinct from {@link WorkerVersionOptions}: a version is an immutable |
| 521 | * upload onto the parent script (gradual rollouts, canaries, Version |
| 522 | * URLs). A Preview is a named copy with its own variables, secrets, |
| 523 | * bindings, and isolated same-Worker Durable Object / Container state. |
| 524 | * Cloudflare recommends Previews for branch and pull-request testing. |
| 525 | * |
| 526 | * Mutually exclusive with {@link WorkerVersionOptions.parent}. |
| 527 | */ |
| 528 | export interface WorkerPreviewOptions { |
| 529 | /** |
| 530 | * The Worker this Preview belongs to. Accepts a Worker reference — |
| 531 | * typically `yield* Cloudflare.Worker.ref(id, { stage, stack })` for |
| 532 | * a Worker deployed in another stage/stack, or a locally-declared |
| 533 | * Worker — or a literal script name as an escape hatch. |
| 534 | * |
| 535 | * When set, this resource does not create a script of its own: it |
| 536 | * creates (or updates) a Preview of the parent's script and deploys |
| 537 | * this Worker's code, assets, and bindings to it. Script-level |
| 538 | * settings that belong to the parent — `name`, `namespace`, `crons`, |
| 539 | * `domain`, `routes`, `workersDev`, `access` — cannot be set on a |
| 540 | * Preview Worker. Locally-hosted Durable Object and Workflow classes |
| 541 | * *are* allowed: each Preview gets its own isolated namespace. |
| 542 | * |
| 543 | * Changing the parent replaces the resource (a Preview belongs to |
| 544 | * exactly one script). |
| 545 | */ |
| 546 | of: string | Worker; |
| 547 | /** |
| 548 | * Preview name. Defaults to a DNS-safe form of the stack stage |
| 549 | * (`pr-123`, `feat-login`). Appears in Preview URLs: |
| 550 | * `https://<name>-<worker>.<subdomain>.workers.dev` and, when the |
| 551 | * parent has {@link WorkerDomainConfig.previews} enabled, |
| 552 | * `https://<name>.<domain>`. |
| 553 | * |
| 554 | * Must start with a lowercase letter, contain only lowercase letters, |
| 555 | * digits, and dashes, and `<name>-<worker-name>` must fit in 63 |
| 556 | * characters (a DNS label). |
| 557 | */ |
| 558 | name?: string; |
| 559 | /** |
| 560 | * Human-readable annotation attached to the Preview deployment, |
| 561 | * shown in the Cloudflare dashboard. |
| 562 | */ |
| 563 | message?: string; |
| 564 | /** |
| 565 | * Machine-readable tag annotation attached to the Preview deployment |
| 566 | * (e.g. a git commit SHA or PR number). |
| 567 | */ |
| 568 | tag?: string; |
| 569 | } |
| 570 | |
| 571 | export interface WorkerProps< |
| 572 | // PERF: unconstrained for the same reason as `Worker<Bindings>` above — |
| 573 | // the `extends WorkerBindingProps` proof is expensive for generic mapped |
| 574 | // types and the call-site overloads already constrain user input. |
| 575 | Bindings = any, |
| 576 | Assets extends WorkerAssetsConfig | undefined = WorkerAssetsConfig | undefined, |
| 577 | > extends PlatformProps { |
| 578 | /** |
| 579 | * Worker name override. If omitted, Alchemy derives a deterministic physical |
| 580 | * name from the stack, stage, and logical ID. |
| 581 | */ |
| 582 | name?: string; |
| 583 | /** |
| 584 | * Deploy this Worker into a Workers for Platforms dispatch namespace as a |
| 585 | * "user worker" — a customer Worker that a platform Worker dispatches to at |
| 586 | * runtime via a dynamic-dispatch binding — instead of as a regular |
| 587 | * account-level Worker. |
| 588 | * |
| 589 | * Accepts the namespace name or a {@link DispatchNamespace} resource. The |
| 590 | * Worker's put/read/delete switch from the account-level |
| 591 | * `/workers/scripts` endpoints to the dispatch-namespace |
| 592 | * `/workers/dispatch/namespaces/:namespace/scripts` endpoints. |
| 593 | * |
| 594 | * User workers are not directly routable: they have no `workers.dev` |
| 595 | * subdomain, custom domains, or cron triggers, so {@link url}, |
| 596 | * {@link domain}, and {@link crons} are ignored when this is set. Changing |
| 597 | * the namespace (or moving a Worker in or out of one) replaces the Worker, |
| 598 | * since an account-level script and a dispatch-namespace script are |
| 599 | * distinct cloud resources. |
| 600 | * |
| 601 | * @see https://developers.cloudflare.com/cloudflare-for-platforms/workers-for-platforms/ |
| 602 | */ |
| 603 | namespace?: string | DispatchNamespace; |
| 604 | /** |
| 605 | * Worker versions & gradual deployments. Set `version.parent` to upload |
| 606 | * this Worker as a canary *version* of another Worker's script |
| 607 | * instead of creating its own; set `version.traffic` below 100 to |
| 608 | * gradually roll out a deploy of this Worker's own script. For branch |
| 609 | * and pull-request testing, use {@link preview} instead. See |
| 610 | * {@link WorkerVersionOptions}. |
| 611 | */ |
| 612 | version?: WorkerVersionOptions; |
| 613 | /** |
| 614 | * Opt into Cloudflare's [Worker Previews](https://developers.cloudflare.com/workers/previews/) |
| 615 | * (private beta). Unset, this Worker deploys as a normal script and none |
| 616 | * of the Preview APIs are called. Set `preview.of` to upload this Worker |
| 617 | * as a Preview of another Worker's script instead: own URL, bindings, |
| 618 | * and isolated Durable Object state; the parent's live deployment is |
| 619 | * untouched. Mutually exclusive with {@link version.parent}. See |
| 620 | * {@link WorkerPreviewOptions}. |
| 621 | */ |
| 622 | preview?: WorkerPreviewOptions; |
| 623 | /** |
| 624 | * Controls the Worker's `workers.dev` surface. |
| 625 | * |
| 626 | * - `true` (the default) — serve the Worker at its stable `workers.dev` |
| 627 | * URL and enable version preview URLs. |
| 628 | * - `false` — no `workers.dev` URLs at all. |
| 629 | * - An object — toggle the stable URL and version previews independently, |
| 630 | * e.g. `{ enabled: false, previewsEnabled: true }` keeps the stable URL |
| 631 | * off while each deployed version stays reachable at its preview URL. |
| 632 | * |
| 633 | * @default true |
| 634 | */ |
| 635 | workersDev?: boolean | WorkersDevConfig; |
| 636 | /** |
| 637 | * Protect this Worker with Cloudflare Access. Two forms: |
| 638 | * |
| 639 | * **Dedicated** — `{ policies, ... }` declares an Access application |
| 640 | * owned by this Worker (namespaced under it as `<Worker>/Access`), |
| 641 | * created, updated, and deleted with it: |
| 642 | * ```ts |
| 643 | * access: { |
| 644 | * policies: [ |
| 645 | * { decision: "allow", include: [{ emailDomain: "example.com" }] }, |
| 646 | * ], |
| 647 | * } |
| 648 | * ``` |
| 649 | * |
| 650 | * **Shared** — pass a `Cloudflare.Access.Application` directly to enroll |
| 651 | * into it. Access policies are application-wide: every enrolled Worker |
| 652 | * is gated by the same policy set: |
| 653 | * ```ts |
| 654 | * access: TeamOnly |
| 655 | * ``` |
| 656 | * |
| 657 | * Either way the Worker's `worker` destination — and a `preview_worker` |
| 658 | * destination unless `previews: false` (dedicated form) — is pushed onto |
| 659 | * the application, covering custom domains, routes, the `workers.dev` |
| 660 | * URL, and version preview URLs. Removing the prop (or deleting the |
| 661 | * Worker) un-enrolls it. |
| 662 | * |
| 663 | * At runtime, read the authenticated identity from `ctx.access` via |
| 664 | * `Cloudflare.Access.Context`; under `alchemy dev`, simulate it with |
| 665 | * `dev: { access: ... }`. Also accepted by every `Cloudflare.Website.*` |
| 666 | * framework. See the |
| 667 | * [Protect a Worker with Access](/cloudflare/security/access) guide. |
| 668 | */ |
| 669 | access?: WorkerAccessConfig; |
| 670 | /** |
| 671 | * Static assets to serve. Can be: |
| 672 | * - A string path to the assets directory |
| 673 | * - An AssetsProps object with directory and config |
| 674 | * - An object with path and hash (e.g., from a Build resource) |
| 675 | * |
| 676 | * Plans hash the directory contents, so an unchanged tree converges to a |
| 677 | * noop. Supplying a precomputed `hash` (e.g. from a Build resource) makes |
| 678 | * that hash authoritative instead — the directory is not read during |
| 679 | * planning at all. |
| 680 | * |
| 681 | * Requests are served assets-first by default: a request matching a file |
| 682 | * never invokes the Worker. `runWorkerFirst` inverts that — `true` routes |
| 683 | * every request through the Worker ahead of the asset layer (serve files |
| 684 | * yourself via the `ASSETS` binding), and a glob array (e.g. `["/api/*"]`) |
| 685 | * routes only matching paths worker-first. The same routing applies under |
| 686 | * `alchemy dev`. |
| 687 | * |
| 688 | * When neither {@link main} nor {@link script} is provided, the Worker is |
| 689 | * deployed **assets-only**: no script is uploaded at all and Cloudflare's |
| 690 | * asset layer serves every request, applying `htmlHandling` / |
| 691 | * `notFoundHandling` (including single-page-application fallback) itself. |
| 692 | */ |
| 693 | assets?: Assets; |
| 694 | /** @internal used by Cloudflare.Website.Vite resource */ |
| 695 | vite?: ViteOptions; |
| 696 | /** |
| 697 | * An external source provider for this Worker — a package that builds |
| 698 | * the assets and server bundle (and serves local dev) in place of the |
| 699 | * built-in bundling pipeline. Used by framework integrations |
| 700 | * (Next/OpenNext, Astro, SvelteKit, Waku); most users configure it |
| 701 | * through the framework's `Website.*` wrapper rather than directly. |
| 702 | * |
| 703 | * The named package must be installed in your project — it is loaded |
| 704 | * with a dynamic `import()` and its default export must satisfy the |
| 705 | * `WorkerSourceModule` contract (`{ make(options) }`). |
| 706 | * |
| 707 | * Mutually exclusive with {@link script}, {@link vite}, and |
| 708 | * {@link main} — a source is self-contained; a provider that needs a |
| 709 | * custom entry takes it in its own `options`. |
| 710 | */ |
| 711 | source?: WorkerSourceDescriptor; |
| 712 | logpush?: boolean; |
| 713 | /** |
| 714 | * Cloudflare Workers Observability settings. Controls Workers Logs |
| 715 | * (`logs`) and Workers Traces (`traces`), each with their own |
| 716 | * `enabled`, `headSamplingRate`, and `persist` toggles. |
| 717 | * |
| 718 | * If omitted, defaults to `{ enabled: true, logs: { enabled: true, |
| 719 | * invocationLogs: true } }`. Traces are off by default — opt in via |
| 720 | * `traces: { enabled: true, ... }`. |
| 721 | * |
| 722 | * Set `issues: { enabled: true }` to enable Workers Issues error detection |
| 723 | * across full deployments. Setting it to `false` or omitting `issues` |
| 724 | * disables Issues on the next full deployment. Version-only uploads and |
| 725 | * gradual rollouts keep the parent's live observability settings. |
| 726 | */ |
| 727 | observability?: WorkerObservability; |
| 728 | /** |
| 729 | * Workers Cache settings. When `enabled` is `true`, Cloudflare checks a |
| 730 | * regionally tiered cache in front of the Worker on every HTTP request — |
| 731 | * cache hits are served from the edge without invoking the Worker at all. |
| 732 | * The Worker controls what gets cached via standard response headers |
| 733 | * (`Cache-Control`, `Cache-Tag`, `Vary`), including |
| 734 | * `stale-while-revalidate`. |
| 735 | * |
| 736 | * Set `crossVersionCache: true` to share cached responses across Worker |
| 737 | * versions (by default the cache is scoped to a single version, so every |
| 738 | * deploy starts cold). |
| 739 | * |
| 740 | * If omitted, Workers Cache is disabled — unless the Worker's init phase |
| 741 | * enables it via `yield* Cloudflare.cache()`, which is the preferred way |
| 742 | * for Effect-native Workers (and also returns the runtime purge client). |
| 743 | * When both are set, this prop takes precedence. |
| 744 | * |
| 745 | * @see https://blog.cloudflare.com/workers-cache/ |
| 746 | */ |
| 747 | cache?: WorkerCache; |
| 748 | /** |
| 749 | * Per-entrypoint settings, keyed by export name: `default` for the |
| 750 | * default export, or the class name of a named `WorkerEntrypoint`. |
| 751 | * Entrypoints you leave out inherit the Worker-wide settings. |
| 752 | * |
| 753 | * Today the only setting is `cache`: a per-entrypoint `cache.enabled` |
| 754 | * overrides the Worker-wide {@link cache} for that entrypoint. Workers |
| 755 | * Cache only applies to `fetch()` invocations (including loopback calls |
| 756 | * through `ctx.exports`); custom RPC methods always bypass it. |
| 757 | * |
| 758 | * Names must not collide with Durable Object classes hosted by this |
| 759 | * Worker. |
| 760 | * |
| 761 | * Previews upload their own settings, and the versions of a gradual |
| 762 | * rollout may differ. `alchemy dev` does not emulate Workers Cache: |
| 763 | * locally, every entrypoint runs on every request. |
| 764 | */ |
| 765 | entrypoints?: Record<string, WorkerEntrypointSettings>; |
| 766 | tags?: string[]; |
| 767 | /** |
| 768 | * Path to the Worker's entry module. Bundled with rolldown before |
| 769 | * upload. Mutually exclusive with {@link script} — provide at most one. |
| 770 | * Omit both (with {@link assets} set) to deploy an assets-only Worker. |
| 771 | * |
| 772 | * A `.py` entry deploys a Python Worker instead: no bundling runs — the |
| 773 | * entry plus every sibling `.py` file upload as Python modules, the |
| 774 | * `python_workers` compatibility flag is added, and dependencies from |
| 775 | * `pyproject.toml` (or a prebuilt `python_modules/` directory) are |
| 776 | * vendored alongside. See the Python Workers section above. |
| 777 | */ |
| 778 | main?: string; |
| 779 | /** |
| 780 | * Raw module source for the Worker. When provided, bundling is bypassed |
| 781 | * entirely and this string is uploaded as a single ESM module |
| 782 | * (`main.js`). Useful for tiny inline workers (tests, fixtures, |
| 783 | * one-offs) and any case where you've already produced the final |
| 784 | * bundle elsewhere. Mutually exclusive with {@link main}. |
| 785 | */ |
| 786 | script?: string; |
| 787 | compatibility?: { |
| 788 | date?: string; |
| 789 | /** |
| 790 | * Cloudflare runtime compatibility flags. |
| 791 | * |
| 792 | * For external Workers with `bundle: false`, an explicitly provided array |
| 793 | * is used exactly as declared, including `[]`. Omit this field to apply |
| 794 | * Alchemy's defaults. |
| 795 | * |
| 796 | * For all other Workers, supplied flags extend Alchemy's defaults: |
| 797 | * - `new_module_registry` is added unless `legacy_module_registry` is set. |
| 798 | * - `nodejs_compat` is added for dates before `2026-08-04` unless |
| 799 | * `no_nodejs_compat` is set. External Workers also require a date on or |
| 800 | * after `2024-09-23` for this default. |
| 801 | * - Effect Workers get `handle_cross_request_promise_resolution` for dates |
| 802 | * before `2024-10-14`; explicitly disabling it is rejected. |
| 803 | * - Python Workers get `python_workers` instead of the JavaScript defaults. |
| 804 | * |
| 805 | * Duplicate flags are removed when defaults are applied. |
| 806 | * |
| 807 | * Add `enable_request_signal` to interrupt an Effect `fetch` handler when |
| 808 | * the client disconnects: the handler's finalizers run as an interruption |
| 809 | * and the Worker stays alive until they finish. Without the flag, |
| 810 | * Cloudflare cancels the request and its finalizers never run. `alchemy |
| 811 | * dev` does not report client disconnects. |
| 812 | */ |
| 813 | flags?: ( |
| 814 | | "nodejs_compat" |
| 815 | | "nodejs_compat_v2" |
| 816 | | "no_nodejs_compat" |
| 817 | | "nodejs_als" |
| 818 | | "new_module_registry" |
| 819 | | "legacy_module_registry" |
| 820 | | "handle_cross_request_promise_resolution" |
| 821 | | "no_handle_cross_request_promise_resolution" |
| 822 | | "python_workers" |
| 823 | | (string & {}) |
| 824 | )[]; |
| 825 | }; |
| 826 | limits?: WorkerLimits; |
| 827 | placement?: WorkerPlacement; |
| 828 | /** |
| 829 | * How each deploy rolls new code out to this Worker's running Durable |
| 830 | * Objects. Cloudflare defers updates by default: an active object keeps |
| 831 | * running its current code for up to 5 minutes while it waits to |
| 832 | * hibernate. Use `{ mode: "immediate" }` when an object must run the new |
| 833 | * code right after the deploy (during an incident, or when a test drives |
| 834 | * it straight away), or set a different `maxDelay`. |
| 835 | * |
| 836 | * Applies per deploy, not as a stored setting: changing only this prop |
| 837 | * does not redeploy the Worker; the next deploy uses it. See |
| 838 | * {@link WorkerCodeUpdateStrategy}. |
| 839 | * |
| 840 | * @default { mode: "deferred", maxDelay: "5 minutes" } |
| 841 | */ |
| 842 | codeUpdateStrategy?: WorkerCodeUpdateStrategy; |
| 843 | /** |
| 844 | * Tracks Durable Object and Workflow exports and captured SQL migrations |
| 845 | * for Effect-native Workers only. |
| 846 | * Populated automatically from bindings; do not set manually. |
| 847 | * @internal |
| 848 | */ |
| 849 | exports?: Record<string, WorkerExport>; |
| 850 | /** |
| 851 | * Environment variables and native Cloudflare Bindings to bind to |
| 852 | * the Worker. Accepts: |
| 853 | * |
| 854 | * - Resource references (R2 bucket, KV namespace, D1 database, |
| 855 | * another Worker, Durable Object, etc.) — emitted as the |
| 856 | * corresponding native binding. |
| 857 | * - `effect/Config` values (`Config.Redacted`, `Config.String`, |
| 858 | * `Config.Number`, …) — resolved at deploy time and bound as |
| 859 | * `secret_text` on Cloudflare regardless of the `Config` |
| 860 | * constructor used. See |
| 861 | * [Secrets & env](/cloudflare/security/secrets-env). |
| 862 | * - Literal values — routed by shape: `Redacted<string>` → |
| 863 | * `secret_text`, `string` → `plain_text`, anything else → `json`. |
| 864 | * - `Output` values that resolve to a plain env value (e.g. |
| 865 | * `Alchemy.makeRandom`) — classified at deploy time by their |
| 866 | * resolved value using the literal rules above. Whole-resource |
| 867 | * Outputs (`Output.of(bucket)`) are rejected at deploy time; bind |
| 868 | * the resource itself instead. |
| 869 | * |
| 870 | * In Effect-native Workers you can alternatively `yield*` a |
| 871 | * `Config` in the Init phase to register the binding implicitly; |
| 872 | * `env` is the only option for async (non-Effect) Workers. |
| 873 | * |
| 874 | * Alchemy also binds its runtime variables to every Worker: |
| 875 | * `ALCHEMY_PHASE`, `ALCHEMY_WORKER_NAME`, `ALCHEMY_STACK_NAME`, |
| 876 | * `ALCHEMY_STAGE` and `ALCHEMY_CLOUDFLARE_ACCOUNT_ID`. They appear in |
| 877 | * `env` and, when `process.env` is populated, in `process.env`. |
| 878 | */ |
| 879 | env?: Bindings; |
| 880 | /** |
| 881 | * Cron expressions that trigger the Worker's scheduled handler. |
| 882 | * |
| 883 | * This is how async (non-Effect) Workers configure Cron Triggers — the |
| 884 | * entry module exports its own `scheduled` handler and this prop attaches |
| 885 | * the schedules at deploy time. Effect-native Workers usually skip this |
| 886 | * prop and call `Cloudflare.Workers.cron(expression, handler)` in the Init |
| 887 | * phase instead, which attaches the expression and registers the runtime |
| 888 | * listener in one step. |
| 889 | * |
| 890 | * Pass an empty array to remove all Cron Triggers. |
| 891 | */ |
| 892 | crons?: string[]; |
| 893 | /** |
| 894 | * Tail Workers that consume this Worker's execution traces. Each entry is |
| 895 | * another {@link Worker} (or a literal script name) that exports a `tail()` |
| 896 | * handler; after each invocation of this Worker, Cloudflare delivers the |
| 897 | * invocation's trace events (console logs, exceptions, event metadata) to |
| 898 | * every listed consumer. |
| 899 | * |
| 900 | * Pass the consumer Worker resource directly — Alchemy resolves it to its |
| 901 | * deployed script name and deploys the consumer before this Worker — or a |
| 902 | * plain script name string for a tail Worker managed outside this stack. |
| 903 | * |
| 904 | * Changing the list is an in-place update. Omitting the prop (or passing |
| 905 | * `[]`) deploys this Worker with no tail consumers attached. |
| 906 | * |
| 907 | * @see https://developers.cloudflare.com/workers/observability/logs/tail-workers/ |
| 908 | */ |
| 909 | tailConsumers?: (string | Worker)[]; |
| 910 | /** |
| 911 | * Streaming Tail Workers that consume this Worker's execution events as |
| 912 | * they happen. Each entry is another {@link Worker} (or a literal script |
| 913 | * name) that exports a `tailStream()` handler; Cloudflare invokes it with |
| 914 | * the invocation's `onset` event *while this Worker is still executing*, |
| 915 | * and the returned handler receives every subsequent event of the session |
| 916 | * (`log`, `spanOpen`, ...) ending with the terminal `outcome`. |
| 917 | * |
| 918 | * This differs from {@link tailConsumers}: a plain tail consumer's `tail()` |
| 919 | * handler receives the completed `TraceItem`s only after the producer's |
| 920 | * invocation finishes, while a streaming tail consumer observes events |
| 921 | * live, per-session, during execution. |
| 922 | * |
| 923 | * Pass the consumer Worker resource directly — Alchemy resolves it to its |
| 924 | * deployed script name and deploys the consumer before this Worker — or a |
| 925 | * plain script name string for a streaming tail Worker managed outside |
| 926 | * this stack. |
| 927 | * |
| 928 | * Changing the list is an in-place update. Omitting the prop (or passing |
| 929 | * `[]`) deploys this Worker with no streaming tail consumers attached. |
| 930 | * |
| 931 | * Streaming tail workers are experimental on Cloudflare's cloud: the |
| 932 | * configuration deploys, but production does not yet deliver events — |
| 933 | * Cloudflare rejects the `streaming_tail_worker` compatibility flag as |
| 934 | * "experimental and cannot yet be used in Workers deployed to |
| 935 | * Cloudflare", so a deployed consumer cannot enable its `tailStream()` |
| 936 | * handler. Under `alchemy dev`, local delivery is fully emulated. |
| 937 | * |
| 938 | * @see https://developers.cloudflare.com/workers/observability/logs/tail-workers/ |
| 939 | */ |
| 940 | streamingTailConsumers?: (string | Worker)[]; |
| 941 | /** |
| 942 | * The Worker's custom domain: one canonical hostname, plus optional |
| 943 | * `aliases` that also serve the Worker and `redirects` that 301 to the |
| 944 | * canonical name. A bare string is shorthand for `{ name }`. Pin the |
| 945 | * zone with `zoneId` / `zone` / `zoneName` (same as {@link routes}); |
| 946 | * otherwise each hostname is looked up by name. The zone must already |
| 947 | * exist in the account. |
| 948 | * |
| 949 | * When set, `https://<name>` becomes the Worker's primary `url` output, |
| 950 | * ranking above the `workers.dev` URL. See {@link WorkerDomainConfig}. |
| 951 | * |
| 952 | * Omitting the prop leaves custom domains unmanaged — attachments made |
| 953 | * outside Alchemy are preserved. Pass `null` to explicitly detach every |
| 954 | * custom domain (and remove their redirect rules). |
| 955 | */ |
| 956 | domain?: string | WorkerDomainConfig | null; |
| 957 | /** |
| 958 | * Zone routes that map URL patterns to this Worker. Equivalent to Wrangler's |
| 959 | * `routes` array — provide `zoneName` or `zoneId` (or `zone`) alongside each |
| 960 | * `pattern`. When the zone is omitted, it is inferred from the pattern's |
| 961 | * hostname. |
| 962 | * |
| 963 | * `alchemy dev` emulates zone routing locally: a Worker whose custom |
| 964 | * {@link domain} matches a route's hostname serves the routes on its own |
| 965 | * dev URL, and each route's `url` attribute is a local listener for its |
| 966 | * hostname. |
| 967 | */ |
| 968 | routes?: WorkerRouteConfig[]; |
| 969 | /** |
| 970 | * Extra bundler options applied on top of the standard rolldown |
| 971 | * input/output options used to build this Worker. Includes the generic |
| 972 | * bundle extras (pure-annotation packages, bundle analyzer) plus |
| 973 | * `input` and `output` overrides. Input plugins run before Alchemy's |
| 974 | * plugins; `input.resolve.alias` takes precedence over Node compatibility |
| 975 | * shims. The entry remains {@link main}. Ignored when {@link bundle} is |
| 976 | * `false`. See {@link WorkerBuildOptions}. |
| 977 | */ |
| 978 | build?: WorkerBuildOptions; |
| 979 | /** |
| 980 | * Whether to bundle {@link main} with rolldown before upload. |
| 981 | * |
| 982 | * Set to `false` when `main` already points at a complete, |
| 983 | * runtime-ready ESM Worker produced by an external tool (OpenNext, |
| 984 | * a separate rolldown/esbuild pipeline, etc.). The entry and every |
| 985 | * file around it matching {@link rules} are uploaded byte-for-byte — |
| 986 | * no bundling, no minification, no transformation. Module names are |
| 987 | * the files' POSIX paths relative to the entry's directory, matching |
| 988 | * Wrangler's `no_bundle` contract. |
| 989 | * |
| 990 | * Re-bundling such artifacts is unsafe: dynamic `import()` calls the |
| 991 | * upstream tool relies on can be rewritten in ways that break runtime |
| 992 | * behavior. |
| 993 | * |
| 994 | * Durable Object and Workflow classes must be exported by the prebuilt |
| 995 | * entry itself — {@link exports} is not applied when `bundle` is |
| 996 | * `false`. |
| 997 | * |
| 998 | * @default true |
| 999 | */ |
| 1000 | bundle?: boolean; |
| 1001 | /** |
| 1002 | * Module rules selecting files uploaded as their own Worker modules, |
| 1003 | * mirroring Wrangler's `rules`. Globs match POSIX-style paths relative to |
| 1004 | * the directory containing {@link main}, and `**\/` matches any depth. |
| 1005 | * Each rule's `type` decides how a file is imported: `Text` as a `string`, |
| 1006 | * `Data` as an `ArrayBuffer`, `CompiledWasm` as a `WebAssembly.Module`. |
| 1007 | * Without one, the extension decides (`.wasm` CompiledWasm, |
| 1008 | * `.txt`/`.html`/`.sql` Text), and other files are Data. When rules |
| 1009 | * overlap, the first match decides. |
| 1010 | * |
| 1011 | * When Alchemy bundles {@link main}, rules add to the built-in ones |
| 1012 | * (`.wasm`, `.bin`, `.txt`, `.html`, `.sql`) and are checked first: an |
| 1013 | * imported file that matches is uploaded as a module instead of bundled. |
| 1014 | * JavaScript, TypeScript and JSON are always bundled, and imports inside |
| 1015 | * nested `?worker` modules don't use rules. For files outside the entry's |
| 1016 | * directory, globs may start with `../` or be absolute. `!` globs exclude |
| 1017 | * across your rules; an excluded `.txt` or `.wasm` still matches the |
| 1018 | * built-in rules. |
| 1019 | * |
| 1020 | * When {@link bundle} is `false`, every file in the entry's directory that |
| 1021 | * matches is uploaded, and the rules replace {@link defaultModuleRules}. |
| 1022 | * |
| 1023 | * Rules don't apply to an inline {@link script}, a {@link source} |
| 1024 | * provider or a Python {@link main}. |
| 1025 | * |
| 1026 | * ```ts |
| 1027 | * // worker.ts |
| 1028 | * import font from "./font.ttf"; // ArrayBuffer |
| 1029 | * import readme from "./README.md"; // string |
| 1030 | * |
| 1031 | * // alchemy.run.ts |
| 1032 | * rules: [{ globs: ["**\/*.ttf"] }, { type: "Text", globs: ["**\/*.md"] }] |
| 1033 | * |
| 1034 | * // modules.d.ts, so TypeScript knows the imports |
| 1035 | * declare module "*.ttf" { const data: ArrayBuffer; export default data; } |
| 1036 | * declare module "*.md" { const text: string; export default text; } |
| 1037 | * ``` |
| 1038 | * |
| 1039 | * @default none when bundling; {@link defaultModuleRules} with `bundle: false` |
| 1040 | */ |
| 1041 | rules?: ModuleRule[]; |
| 1042 | /** |
| 1043 | * Options for the local dev server that runs this Worker under `alchemy dev`. |
| 1044 | * Each Worker is served on its own port. |
| 1045 | * |
| 1046 | * Use `{ mode: "external" }` to skip starting a local Worker entirely — |
| 1047 | * useful when an external dev server (e.g. one spawned via `Command.Dev`) |
| 1048 | * is serving the content this Worker would otherwise host. |
| 1049 | */ |
| 1050 | dev?: |
| 1051 | | { |
| 1052 | /** |
| 1053 | * Run this Worker in `workerd` locally (the default). |
| 1054 | * @default "worker" |
| 1055 | */ |
| 1056 | mode?: "worker"; |
| 1057 | /** |
| 1058 | * Host the local dev server binds to. |
| 1059 | * @default "localhost" |
| 1060 | */ |
| 1061 | host?: string; |
| 1062 | /** |
| 1063 | * Port the local dev server listens on. If the port is unavailable, |
| 1064 | * the next free port is used unless {@link strictPort} is `true`. |
| 1065 | * @default 1337 |
| 1066 | */ |
| 1067 | port?: number; |
| 1068 | /** |
| 1069 | * When `true`, fail instead of falling back to another port if |
| 1070 | * {@link port} is already in use. |
| 1071 | * @default false |
| 1072 | */ |
| 1073 | strictPort?: boolean; |
| 1074 | /** |
| 1075 | * Whether the local runtime's Cache API simulator |
| 1076 | * (`caches.default` / `caches.open()`) stores responses. Set |
| 1077 | * `false` to make every cache operation a no-op — matching |
| 1078 | * production behaviour on `workers.dev` subdomains, where the |
| 1079 | * Cache API silently does nothing. |
| 1080 | * @default true |
| 1081 | */ |
| 1082 | cache?: boolean; |
| 1083 | /** |
| 1084 | * Override the `request.cf` blob served to this Worker locally. |
| 1085 | * Defaults to a static placeholder (Miniflare's Austin/DFW blob); |
| 1086 | * pass e.g. `{ colo: "LHR", country: "GB" }` to simulate a |
| 1087 | * different edge location. |
| 1088 | */ |
| 1089 | cf?: Record<string, unknown>; |
| 1090 | /** |
| 1091 | * Stub the authenticated Access state in local dev. In production, |
| 1092 | * `ctx.access` is populated by Cloudflare's edge after a request |
| 1093 | * passes the Access login wall — locally there is no edge and no |
| 1094 | * login, so without this stub `ctx.access` is always `undefined` |
| 1095 | * and identity-dependent code paths can't run. When set, every |
| 1096 | * request served by `alchemy dev` behaves as if this one user had |
| 1097 | * logged in: `ctx.access` carries the given audience and |
| 1098 | * `getIdentity()` resolves the given identity. Omit to simulate |
| 1099 | * unauthenticated requests. Inert on deploy — the deployed Worker |
| 1100 | * always gets the real edge-populated `ctx.access`. |
| 1101 | */ |
| 1102 | access?: { |
| 1103 | /** |
| 1104 | * Simulated Access application audience (AUD) tag. |
| 1105 | * @default "dev" |
| 1106 | */ |
| 1107 | aud?: string; |
| 1108 | /** |
| 1109 | * Simulated identity returned by `ctx.access.getIdentity()`, |
| 1110 | * e.g. `{ email: "dev@example.com" }`. |
| 1111 | */ |
| 1112 | identity?: WorkerAccessIdentity; |
| 1113 | }; |
| 1114 | /** |
| 1115 | * Overrides for the `workerd` process that runs this Worker |
| 1116 | * locally. Inert on deploy. |
| 1117 | */ |
| 1118 | workerd?: { |
| 1119 | /** |
| 1120 | * Path to the workerd binary to run instead of the one from the |
| 1121 | * `workerd` npm package. Use it where the npm binary can't |
| 1122 | * start, e.g. NixOS. Set `ALCHEMY_WORKERD_PATH` instead to |
| 1123 | * change the binary for every workerd process alchemy starts. |
| 1124 | */ |
| 1125 | path?: string; |
| 1126 | /** |
| 1127 | * Extra V8 flags, e.g. `["--max-old-space-size=4096"]` to raise |
| 1128 | * the heap limit. Applied after `ALCHEMY_WORKERD_V8_FLAGS`, so |
| 1129 | * they win when both set the same flag. |
| 1130 | */ |
| 1131 | v8Flags?: string[]; |
| 1132 | /** Extra environment variables for the workerd process. */ |
| 1133 | env?: Record<string, string>; |
| 1134 | }; |
| 1135 | } |
| 1136 | | { |
| 1137 | /** |
| 1138 | * Don't start a local Worker; an external dev server is running instead. |
| 1139 | */ |
| 1140 | mode: "external"; |
| 1141 | /** |
| 1142 | * URL the external dev server is reachable at, if applicable. |
| 1143 | * This will be returned as the `url` attribute of the Worker resource. |
| 1144 | */ |
| 1145 | url?: string; |
| 1146 | }; |
| 1147 | } |
| 1148 | |
| 1149 | /** |
| 1150 | * A serializable reference to an external Worker source provider. |
| 1151 | * Persists in state (`olds`) and crosses the local-provider RPC |
| 1152 | * boundary, so it must stay plain JSON data — the implementation is |
| 1153 | * resolved by dynamically importing {@link provider}. |
| 1154 | */ |
| 1155 | export interface WorkerSourceDescriptor { |
| 1156 | /** |
| 1157 | * Module specifier resolved with `import()`, e.g. |
| 1158 | * `"@alchemy.run/cloudflare-next"`. The module's default export must |
| 1159 | * satisfy the `WorkerSourceModule` contract. |
| 1160 | */ |
| 1161 | readonly provider: string; |
| 1162 | /** |
| 1163 | * How the source serves local development. Server-mode sources run in an |
| 1164 | * isolated child process; bundle-mode sources stream rebuilds back to the |
| 1165 | * local Worker host. |
| 1166 | */ |
| 1167 | readonly devMode: "server" | "bundle"; |
| 1168 | /** |
| 1169 | * The framework project root. Server-mode dev children are spawned with |
| 1170 | * this directory as their working directory — some framework dev servers |
| 1171 | * (e.g. `next dev`, which 404s every route when `process.cwd()` differs |
| 1172 | * from its `dir`) require cwd to be the project root. Relative paths |
| 1173 | * resolve against the engine's working directory. Defaults to the |
| 1174 | * engine's working directory. |
| 1175 | */ |
| 1176 | readonly rootDir?: string; |
| 1177 | /** |
| 1178 | * The JS runtime the server-mode dev child must run under. Some framework |
| 1179 | * dev servers are runtime-sensitive — `next dev` (Turbopack) silently 404s |
| 1180 | * every route when cold-started under bun — so the provider can pin the |
| 1181 | * child to `"node"`. When the requested runtime is not installed, the |
| 1182 | * engine falls back to its own runtime. Defaults to the engine's runtime. |
| 1183 | */ |
| 1184 | readonly runtime?: "node"; |
| 1185 | /** |
| 1186 | * Provider-specific options (rootDir, memo, framework config, ...). |
| 1187 | * Must be JSON-serializable AND JSON-stable: the descriptor persists |
| 1188 | * in state and participates in the metadata hash, so non-deterministic |
| 1189 | * values here cause perpetual redeploys. |
| 1190 | */ |
| 1191 | readonly options?: unknown; |
| 1192 | } |
| 1193 | |
| 1194 | export interface ViteOptions { |
| 1195 | /** |
| 1196 | * Framework-specific build metadata interpreted after Vite completes. |
| 1197 | * Set by `Website.Foldkit` to derive asset routing from its manifest. |
| 1198 | * @internal |
| 1199 | */ |
| 1200 | framework?: "foldkit"; |
| 1201 | |
| 1202 | /** |
| 1203 | * Overrides the module that becomes the deployed Worker entry, forwarded |
| 1204 | * to the Cloudflare Vite plugin's `main` option. Relative paths resolve |
| 1205 | * from the Vite root (`rootDir`). A package export |
| 1206 | * (`"my-package/worker"`) or a virtual module id (`"virtual:entry"`) |
| 1207 | * resolves through Vite. |
| 1208 | * |
| 1209 | * By default the entry environment's own entry (the server bundle the |
| 1210 | * framework produces) is deployed. Point `main` at a custom module when |
| 1211 | * the deployed Worker must export more than the framework's fetch |
| 1212 | * handler — e.g. Durable Object classes or additional handlers wrapping |
| 1213 | * the framework handler. |
| 1214 | * |
| 1215 | * @example |
| 1216 | * ```typescript |
| 1217 | * vite: { main: "worker/index.ts" } |
| 1218 | * ``` |
| 1219 | */ |
| 1220 | main?: string; |
| 1221 | /** |
| 1222 | * Root directory passed to Vite's `root` option. |
| 1223 | * Defaults to the current working directory (`process.cwd()`). |
| 1224 | */ |
| 1225 | rootDir?: string; |
| 1226 | /** |
| 1227 | * Controls which files are hashed to decide whether a rebuild is needed. |
| 1228 | * By default every non-gitignored file in `cwd` is hashed, plus the nearest |
| 1229 | * lockfile. Provide explicit globs to narrow the scope. |
| 1230 | * |
| 1231 | * @see {@link MemoOptions} |
| 1232 | */ |
| 1233 | memo?: MemoOptions & { |
| 1234 | /** |
| 1235 | * Configure additional workspaces to hash. |
| 1236 | * By default, auto-detects workspaces during Vite build, then hashes all |
| 1237 | * non-gitignored files in the workspace plus the nearest lockfile. |
| 1238 | * @default "auto" |
| 1239 | */ |
| 1240 | workspaces?: |
| 1241 | | "auto" |
| 1242 | | Array< |
| 1243 | MemoOptions & { |
| 1244 | /** |
| 1245 | * The working directory to hash, relative to the Vite root. |
| 1246 | */ |
| 1247 | cwd: string; |
| 1248 | } |
| 1249 | >; |
| 1250 | }; |
| 1251 | /** |
| 1252 | * Selects which Vite environments make up the deployed Worker, for |
| 1253 | * frameworks that build more than one (e.g. React Server Components). |
| 1254 | * |
| 1255 | * A single-environment SSR build needs no configuration. For a |
| 1256 | * multi-environment build, point `entry` at the environment that |
| 1257 | * produces the server entry chunk and list the remaining server-side |
| 1258 | * environments in `children` so their chunks are bundled alongside it. |
| 1259 | * The `client` environment is always treated as static assets. |
| 1260 | * |
| 1261 | * @example React Router / React Server Components |
| 1262 | * ```typescript |
| 1263 | * viteEnvironments: { entry: "rsc", children: ["ssr"] } |
| 1264 | * ``` |
| 1265 | * |
| 1266 | * @default { entry: "ssr", children: [] } |
| 1267 | */ |
| 1268 | viteEnvironments?: { |
| 1269 | entry?: string; |
| 1270 | children?: string[]; |
| 1271 | }; |
| 1272 | } |
| 1273 | |
| 1274 | // PERF: deliberately NOT `Bindings extends WorkerBindings`. The constraint |
| 1275 | // forced the checker to prove the generic `NormalizedBindings<...>` mapped |
| 1276 | // type assignable to the ~30-member `WorkerBindingResource` union at every |
| 1277 | // `Worker<...>` instantiation — a single 28s structural relation that was 45% |
| 1278 | // of the whole program's check time. Input is already constrained at the |
| 1279 | // call boundary (`Bindings extends WorkerBindingProps`), so this type |
| 1280 | // argument is only ever produced from validated shapes. |
| 1281 | export type Worker<Bindings = any> = Resource< |
| 1282 | WorkerTypeId, |
| 1283 | WorkerProps<Bindings>, |
| 1284 | { |
| 1285 | /** |
| 1286 | * The immutable ID Cloudflare assigns to this Worker's script — a hex |
| 1287 | * value like `c81a2d22c29840ed9d61681a3270dbff`, shown as the Worker ID |
| 1288 | * in the dashboard and the identifier Access `worker` destinations key |
| 1289 | * on. Stable across every update; changes only when the script is |
| 1290 | * replaced. For the script *name*, use {@link workerName}. A version |
| 1291 | * worker carries its parent script's ID. Under `alchemy dev` there is |
| 1292 | * no cloud script, so the local provider generates a `dev:`-prefixed |
| 1293 | * ID instead (switching between dev and deploy replaces the resource, |
| 1294 | * so the two identities never mix). |
| 1295 | */ |
| 1296 | workerId: string; |
| 1297 | /** The script name, e.g. `"api"` — the classic API's identifier. */ |
| 1298 | workerName: string; |
| 1299 | /** |
| 1300 | * The Workers for Platforms dispatch namespace this Worker was deployed |
| 1301 | * into, or `undefined` for a regular account-level Worker. |
| 1302 | */ |
| 1303 | namespace: string | undefined; |
| 1304 | logpush: boolean | undefined; |
| 1305 | /** |
| 1306 | * The most significant URL the Worker is reachable at — always |
| 1307 | * `urls[0]`, or `undefined` when the Worker is not reachable at any |
| 1308 | * URL (e.g. a dispatch-namespace user worker). Ranking: the canonical |
| 1309 | * custom domain, then aliases, then the stable `workers.dev` URL; a |
| 1310 | * version worker's `url` is its aliased preview URL; under |
| 1311 | * `alchemy dev` it is the local dev server's URL. |
| 1312 | */ |
| 1313 | url: string | undefined; |
| 1314 | /** |
| 1315 | * Every URL that serves this Worker, most significant first — |
| 1316 | * `[https://<domain.name>?, ...aliases, <workers.dev URL>?, |
| 1317 | * <version preview URLs>?]`, or the local dev server's |
| 1318 | * `[localhost, ...LAN]` URLs under `alchemy dev`. Redirect hostnames |
| 1319 | * never appear (they don't serve the Worker). Useful wholesale, e.g. |
| 1320 | * as a CORS allow-list. |
| 1321 | */ |
| 1322 | urls: string[]; |
| 1323 | /** |
| 1324 | * The Worker's resolved custom-domain configuration — canonical |
| 1325 | * `name`, `aliases`, and `redirects` as deployed — or `undefined` |
| 1326 | * when no custom domain is configured. |
| 1327 | */ |
| 1328 | domain: |
| 1329 | | { |
| 1330 | name: string; |
| 1331 | aliases: string[]; |
| 1332 | redirects: string[]; |
| 1333 | zone?: ZoneReference; |
| 1334 | previews?: boolean; |
| 1335 | } |
| 1336 | | undefined; |
| 1337 | tags: string[] | undefined; |
| 1338 | durableObjectNamespaces: Record<string, string>; |
| 1339 | accountId: string; |
| 1340 | /** |
| 1341 | * The zone routes attached to this Worker. `url` is the origin serving |
| 1342 | * the route's hostname — `https://<host>` when deployed, the local edge |
| 1343 | * listener under `alchemy dev` — and `undefined` for a wildcard host. |
| 1344 | */ |
| 1345 | routes: { id: string; pattern: string; zoneId: string; url?: string }[]; |
| 1346 | crons: string[]; |
| 1347 | /** |
| 1348 | * The tail consumers attached to this Worker's script — each entry the |
| 1349 | * consuming Worker's script name — or `undefined` when none are |
| 1350 | * attached. Local emulation (`RuntimeWorker.tails`) lowers this same |
| 1351 | * list into workerd tail-service designators. |
| 1352 | */ |
| 1353 | tailConsumers?: { service: string }[] | undefined; |
| 1354 | /** |
| 1355 | * The streaming tail consumers attached to this Worker's script — each |
| 1356 | * entry the consuming Worker's script name — or `undefined` when none |
| 1357 | * are attached. Recorded from the uploaded metadata: the script-settings |
| 1358 | * read endpoint does not expose `streaming_tail_consumers`, so this is |
| 1359 | * the deployed value, not an observed one. Local emulation |
| 1360 | * (`RuntimeWorker.streamingTails`) lowers this same list into workerd |
| 1361 | * streaming-tail service designators. |
| 1362 | */ |
| 1363 | streamingTailConsumers?: { service: string }[] | undefined; |
| 1364 | /** |
| 1365 | * The parent script name this Worker uploads versions to, when this |
| 1366 | * resource is a version worker (`version.parent` set). `undefined` for |
| 1367 | * a Worker that owns its own script — including one deploying with a |
| 1368 | * gradual rollout. This is the discriminator `read`/`delete` use to |
| 1369 | * avoid treating the parent's script as this resource's own. |
| 1370 | */ |
| 1371 | versionOf?: string | undefined; |
| 1372 | /** |
| 1373 | * The parent script name this Worker is a Preview of, when this |
| 1374 | * resource is a Preview Worker (`preview.of` set). `undefined` for |
| 1375 | * a Worker that owns its own script. Discriminator `read`/`delete` |
| 1376 | * use so they never treat the parent's script as this resource's own. |
| 1377 | */ |
| 1378 | previewOf?: string | undefined; |
| 1379 | /** |
| 1380 | * Cloudflare's immutable Preview id. Set when this resource is a |
| 1381 | * Preview Worker (`preview.of`). |
| 1382 | */ |
| 1383 | previewId?: string | undefined; |
| 1384 | /** |
| 1385 | * The Preview name as created — the user-provided `preview.name`, or |
| 1386 | * the auto-derived name from the stack stage. |
| 1387 | */ |
| 1388 | previewName?: string | undefined; |
| 1389 | /** |
| 1390 | * DNS-safe slug Cloudflare assigned to this Preview. Used in Preview |
| 1391 | * URLs (`<slug>-<worker>.<subdomain>.workers.dev` and |
| 1392 | * `<slug>.<domain>` when the parent has custom-domain Previews). |
| 1393 | */ |
| 1394 | previewSlug?: string | undefined; |
| 1395 | /** |
| 1396 | * Same-Worker Durable Object class names hosted on the last Preview |
| 1397 | * deploy — the baseline for the next Preview's class migrations. |
| 1398 | */ |
| 1399 | previewDoClasses?: string[] | undefined; |
| 1400 | /** |
| 1401 | * The id of the version uploaded by the most recent deploy. Set for |
| 1402 | * every Worker outside a dispatch namespace: a full deploy records the |
| 1403 | * version serving 100% of traffic, a gradual rollout |
| 1404 | * (`version.traffic` < 100) and a version worker (`version.parent`) |
| 1405 | * record the version they uploaded. |
| 1406 | */ |
| 1407 | versionId?: string | undefined; |
| 1408 | /** |
| 1409 | * The preview-URL alias attached to the uploaded version — the |
| 1410 | * user-provided `version.alias`, or the auto-derived stable alias for |
| 1411 | * a version worker. The aliased preview URL |
| 1412 | * (`<alias>-<name>.<subdomain>.workers.dev`) is stable across |
| 1413 | * deploys and is the version worker's primary `url`. |
| 1414 | */ |
| 1415 | versionAlias?: string | undefined; |
| 1416 | /** |
| 1417 | * The id of the deployment created by the most recent deploy. A full |
| 1418 | * deploy records the active deployment; a version with `traffic > 0` |
| 1419 | * records the deployment it created through the deployments API. |
| 1420 | * Preview-only versions (`traffic: 0`) and Workers in a dispatch |
| 1421 | * namespace have no deployment. |
| 1422 | */ |
| 1423 | deploymentId?: string | undefined; |
| 1424 | /** |
| 1425 | * The zone ids currently holding this resource's version-affinity |
| 1426 | * Transform Rules (`version.affinity`) — the cleanup list consulted |
| 1427 | * when affinity is removed or the resource is deleted. For a version |
| 1428 | * worker these are the *parent's* zones. `undefined` when no affinity |
| 1429 | * rules are deployed. |
| 1430 | */ |
| 1431 | affinityZoneIds?: string[] | undefined; |
| 1432 | /** |
| 1433 | * The sorted names of the `secret_text` and `secret_key` bindings this |
| 1434 | * Worker's deploys uploaded and have not yet deleted. Cloudflare keeps a |
| 1435 | * secret binding that a later upload omits, so a full deploy deletes the |
| 1436 | * names listed here that it no longer uploads. Secrets set outside |
| 1437 | * Alchemy are never listed, and never deleted. |
| 1438 | */ |
| 1439 | secretNames?: string[] | undefined; |
| 1440 | hash?: { |
| 1441 | assets: string | undefined; |
| 1442 | bundle: string | undefined; |
| 1443 | input: string | undefined; |
| 1444 | additionalWorkspaces: string[] | undefined; |
| 1445 | // Hash of the deploy-time metadata surface (compatibility, env, |
| 1446 | // bindings, asset config, limits, observability, ...) so metadata-only |
| 1447 | // edits trigger an update (#745). Optional: state written before this |
| 1448 | // field existed has no `metadata`, which reads as a one-time update on |
| 1449 | // the first diff after upgrading (the apply backfills it). |
| 1450 | metadata?: string | undefined; |
| 1451 | }; |
| 1452 | }, |
| 1453 | { |
| 1454 | bindings?: WorkerBinding[]; |
| 1455 | /** |
| 1456 | * Extra env vars merged into the Worker at reconcile. `Redacted` |
| 1457 | * values deploy as `secret_text`. Used by later resources (e.g. a |
| 1458 | * Stripe webhook signing secret) to attach env without the Worker |
| 1459 | * init depending on that resource. |
| 1460 | */ |
| 1461 | env?: Record<string, any>; |
| 1462 | /** |
| 1463 | * Workers Cache settings contributed by `yield* Cloudflare.cache()`. |
| 1464 | * Merged into the upload metadata's `cache_options`; an explicit |
| 1465 | * `WorkerProps.cache` takes precedence. |
| 1466 | */ |
| 1467 | cache?: WorkerCache; |
| 1468 | /** |
| 1469 | * Workers Observability traces settings contributed by |
| 1470 | * `Cloudflare.Telemetry()`. Deep-merged into upload metadata: bound |
| 1471 | * traces fill in when `WorkerProps.observability.traces` is omitted, |
| 1472 | * and never clobber the default logs config. An explicit |
| 1473 | * `observability.traces` object wins. |
| 1474 | */ |
| 1475 | observability?: Pick<WorkerObservability, "traces">; |
| 1476 | containers?: { |
| 1477 | className: string; |
| 1478 | /** Set when an async `Cloudflare.DurableObject(name, { containers })` binding contributed the row. */ |
| 1479 | attachedBy?: "binding"; |
| 1480 | /** Application name and prepared images for the native container API. */ |
| 1481 | name?: string; |
| 1482 | images?: Record<string, string>; |
| 1483 | /** Named image sources for local workerd. An empty map enables managed images. */ |
| 1484 | devImages?: Record<string, DevContainerImage>; |
| 1485 | dev: DevContainerImage | undefined; |
| 1486 | /** |
| 1487 | * Content hash of the image (bundle/Dockerfile/context). Part of the |
| 1488 | * local worker's restart config: `dev` only carries stable PATHS, so |
| 1489 | * without the hash an image content change would never restart the |
| 1490 | * instance and the running container would serve stale code. |
| 1491 | */ |
| 1492 | hash: string | undefined; |
| 1493 | }[]; |
| 1494 | crons?: string[]; |
| 1495 | /** |
| 1496 | * Durable Object classes a Domain model hosts, with the names they had in |
| 1497 | * earlier Domain versions, so a deploy carries their data over to this |
| 1498 | * version's names. See `Domain/Version.ts`. |
| 1499 | */ |
| 1500 | domainClasses?: DomainClass[]; |
| 1501 | hyperdrives?: Record<string, Required<DevOrigin>>; |
| 1502 | /** |
| 1503 | * Dev-only channel (like `hyperdrives`): binding name → opt-out of local |
| 1504 | * emulation in `alchemy dev` (the binding was piped through `Alchemy.remote()` |
| 1505 | * constructor). Contributed alongside the pure wire binding instead of |
| 1506 | * being embedded in it — wire descriptors stay exactly what Cloudflare |
| 1507 | * accepts. Records from multiple bind calls merge by key; the local |
| 1508 | * worker provider reads it when lowering `browser` / `images` / `stream` |
| 1509 | * / `send_email` bindings to their local or remote runtime hooks. The |
| 1510 | * live provider ignores it. |
| 1511 | */ |
| 1512 | devRemote?: Record<string, boolean>; |
| 1513 | }, |
| 1514 | Providers |
| 1515 | >; |
| 1516 | |
| 1517 | /** An external/async Worker declared without an Effect implementation. */ |
| 1518 | export type ExternalWorker<Bindings = {}> = Worker<Bindings> & { |
| 1519 | /** |
| 1520 | * The external Worker's declared `env`. Not available on persisted references |
| 1521 | * or Effect-native Worker construction results. |
| 1522 | * A Workflow binding is exposed as a {@link WorkflowBinding} whose |
| 1523 | * `workflowName` is an `Output` resolved in the same deploy, so a sibling |
| 1524 | * resource (e.g. a Queue subscription to the Workflow's events) can |
| 1525 | * consume the Workflow's physical name on its first deployment: |
| 1526 | * |
| 1527 | * ```typescript |
| 1528 | * source: { |
| 1529 | * type: "workflows.workflow", |
| 1530 | * workflowName: worker.env.MY_WORKFLOW.workflowName, |
| 1531 | * } |
| 1532 | * ``` |
| 1533 | */ |
| 1534 | readonly env: WorkerEnvBindings<Bindings>; |
| 1535 | }; |
| 1536 | |
| 1537 | /** The env key the resolved URL is injected under when `yield*`-ed. */ |
| 1538 | const SELF_URL_BINDING_NAME = "WORKER_URL"; |
| 1539 | |
| 1540 | /** |
| 1541 | * Effect-native accessor for the Worker's own URL. The value is injected as an |
| 1542 | * env binding that only exists at the *exec* phase on the deployed Worker, so |
| 1543 | * reading it is deferred behind an Effect that requires {@link RuntimeContext}. |
| 1544 | * Yield it inside a handler to obtain the URL string. |
| 1545 | */ |
| 1546 | export type URLAccessor = Effect.Effect<string, never, RuntimeContext>; |
| 1547 | |
| 1548 | /** |
| 1549 | * The type of {@link URL} (`Worker.URL`). |
| 1550 | * |
| 1551 | * It is a real `Effect` — `yield* Worker.URL` inside a Worker init attaches |
| 1552 | * the binding and resolves the deferred {@link URLAccessor} — but it also |
| 1553 | * carries the `~alchemy/Kind` marker statically, so when it is declared on a |
| 1554 | * Worker's `env` the binding machinery recognises it as a `self_url` binding |
| 1555 | * (`isSelfUrl`) instead of running it. |
| 1556 | * |
| 1557 | * Defined in this module (not its own file): the effect closes over the |
| 1558 | * `Worker` tag and `WorkerEnvironment`, and a separate module would form a |
| 1559 | * value cycle with Worker.ts that the deploy bundler's scope hoisting turns |
| 1560 | * into a startup crash. |
| 1561 | */ |
| 1562 | export interface URLEffect extends Effect.Effect<URLAccessor, never, WorkerEnvironment | Worker> { |
| 1563 | "~alchemy/Kind": "Cloudflare.Workers.URL"; |
| 1564 | } |
| 1565 | |
| 1566 | /** |
| 1567 | * A Worker's own public URL, injected as a binding on that same Worker. At |
| 1568 | * deploy time Alchemy resolves the URL the Worker will be served at (its first |
| 1569 | * custom domain if any, otherwise its `workers.dev` URL) and injects it as a |
| 1570 | * plain-text env binding, so the running Worker knows its own public address. |
| 1571 | * |
| 1572 | * Declare it on a Worker's `env` (it flows through `InferEnv` → `string`) or |
| 1573 | * `yield*` it inside an Effect-native Worker to attach the binding and obtain |
| 1574 | * a deferred {@link URLAccessor}. It is also exposed as |
| 1575 | * `Cloudflare.Worker.URL`. |
| 1576 | * |
| 1577 | * Because the URL is resolved *before* the bundle is built, a `VITE_`-prefixed |
| 1578 | * env key holding `Worker.URL` is inlined into the client bundle as |
| 1579 | * `import.meta.env.VITE_*` — the canonical way to give a Vite frontend its own |
| 1580 | * public URL. |
| 1581 | */ |
| 1582 | export const URL: URLEffect = Object.assign( |
| 1583 | Effect.gen(function* () { |
| 1584 | // Deploy-time only: register the binding on the host Worker. The provider |
| 1585 | // lowers the `self_url` sentinel into a plain-text binding holding the |
| 1586 | // resolved URL just before upload. |
| 1587 | if (!globalThis.__ALCHEMY_RUNTIME__) { |
| 1588 | yield* (yield* Worker).bind`${SELF_URL_BINDING_NAME}`({ |
| 1589 | bindings: [{ type: "self_url", name: SELF_URL_BINDING_NAME }], |
| 1590 | }); |
| 1591 | } |
| 1592 | // Captured at init; the deferred read only runs at exec phase (the |
| 1593 | // accessor is colored with RuntimeContext), where env is populated. |
| 1594 | const env = yield* WorkerEnvironment; |
| 1595 | return Effect.sync( |
| 1596 | () => (env as Record<string, string>)[SELF_URL_BINDING_NAME]!, |
| 1597 | ) as URLAccessor; |
| 1598 | }), |
| 1599 | { "~alchemy/Kind": "Cloudflare.Workers.URL" as const }, |
| 1600 | ); |
| 1601 | |
| 1602 | /** |
| 1603 | * Returns true when the value is the `Worker.URL` binding (keyed on the |
| 1604 | * static `~alchemy/Kind` marker — the value is a real Effect, so every |
| 1605 | * env-resolution site must check this before `Effect.isEffect`). |
| 1606 | */ |
| 1607 | export const isSelfUrl = (value: unknown): value is URLEffect => |
| 1608 | typeof value === "object" && |
| 1609 | value !== null && |
| 1610 | "~alchemy/Kind" in value && |
| 1611 | (value as URLEffect)["~alchemy/Kind"] === "Cloudflare.Workers.URL"; |
| 1612 | |
| 1613 | /** |
| 1614 | * A service binding that points at this Worker ITSELF. Declare it on `env` |
| 1615 | * to give the Worker a self-referencing service binding — the provider |
| 1616 | * lowers it into a `service` binding targeting the Worker's own physical |
| 1617 | * name at upload, and local dev serves it with the runtime's in-process |
| 1618 | * self service. |
| 1619 | * |
| 1620 | * `Self` targets the Worker's default export. To bind one of its named |
| 1621 | * `WorkerEntrypoint` classes instead, name it with |
| 1622 | * `Cloudflare.WorkerEntrypoint("McpEntrypoint")`. |
| 1623 | * |
| 1624 | * The canonical consumer is OpenNext's `WORKER_SELF_REFERENCE` (the ISR |
| 1625 | * revalidation queue re-fetches the worker through it): |
| 1626 | * |
| 1627 | * ```typescript |
| 1628 | * const site = yield* Cloudflare.Website.Nextjs("Site", { |
| 1629 | * env: { |
| 1630 | * WORKER_SELF_REFERENCE: Cloudflare.Workers.Self, |
| 1631 | * }, |
| 1632 | * }); |
| 1633 | * ``` |
| 1634 | */ |
| 1635 | export const Self = { |
| 1636 | "~alchemy/Kind": "Cloudflare.Workers.Self", |
| 1637 | } as const; |
| 1638 | export type Self = typeof Self; |
| 1639 | |
| 1640 | /** Returns true when the value is the {@link Self} marker. */ |
| 1641 | export const isSelf = (value: unknown): value is Self => |
| 1642 | typeof value === "object" && |
| 1643 | value !== null && |
| 1644 | "~alchemy/Kind" in value && |
| 1645 | (value as Self)["~alchemy/Kind"] === "Cloudflare.Workers.Self"; |
| 1646 | |
| 1647 | /** Options for {@link WorkerRef}. */ |
| 1648 | export interface WorkerRefOptions { |
| 1649 | /** Stage of the referenced Worker. Defaults to the current stage. */ |
| 1650 | stage?: string; |
| 1651 | /** Stack of the referenced Worker. Defaults to the current stack. */ |
| 1652 | stack?: string; |
| 1653 | } |
| 1654 | |
| 1655 | /** |
| 1656 | * `Cloudflare.Worker.ref` — by logical id, or by the Worker's declaration so |
| 1657 | * the reference keeps the declaration's type (`Worker & Rpc<...>`). |
| 1658 | */ |
| 1659 | export interface WorkerRef { |
| 1660 | <W extends Worker>( |
| 1661 | worker: Effect.Effect<W, any, any> & PlatformIdentity, |
| 1662 | options?: WorkerRefOptions, |
| 1663 | ): Effect.Effect<W>; |
| 1664 | (id: string, options?: WorkerRefOptions): Effect.Effect<Worker>; |
| 1665 | } |
| 1666 | |
| 1667 | /** |
| 1668 | * Let `ref` take a declaration in place of its logical id. Only the |
| 1669 | * declaration's `LogicalId` is read: it is never yielded, so the reference |
| 1670 | * adds no dependency on (and does not deploy) the referenced Worker. |
| 1671 | */ |
| 1672 | const withDeclarationRef = <P extends Pick<ResourceClass<Worker>, "ref">>(platform: P): P => { |
| 1673 | const ref = platform.ref; |
| 1674 | return Object.assign(platform, { |
| 1675 | ref: (worker: string | PlatformIdentity, options?: WorkerRefOptions) => |
| 1676 | ref(typeof worker === "string" ? worker : worker.LogicalId, options), |
| 1677 | }); |
| 1678 | }; |
| 1679 | |
| 1680 | /** |
| 1681 | * A Cloudflare Worker host with deploy-time binding support and runtime export |
| 1682 | * collection. |
| 1683 | * |
| 1684 | * A Worker follows a two-phase pattern. The outer `Effect.gen` runs at |
| 1685 | * deploy time to bind resources (KV, R2, Durable Objects, etc.). It returns |
| 1686 | * an object whose properties are the Worker's runtime handlers — `fetch` for |
| 1687 | * HTTP requests and any additional RPC methods. |
| 1688 | * |
| 1689 | * ```typescript |
| 1690 | * Effect.gen(function* () { |
| 1691 | * // Construction: bind resources (deploy time and cold start) |
| 1692 | * const kv = yield* Cloudflare.KV.ReadWriteNamespace(MyKV); |
| 1693 | * |
| 1694 | * return { |
| 1695 | * // Runtime: handlers, once per request |
| 1696 | * fetch: Effect.gen(function* () { |
| 1697 | * const value = yield* kv.get("key"); |
| 1698 | * return HttpServerResponse.text(value ?? "not found"); |
| 1699 | * }), |
| 1700 | * }; |
| 1701 | * }) |
| 1702 | * ``` |
| 1703 | * |
| 1704 | * There are three ways to define a Worker, from simplest to most |
| 1705 | * flexible. See the [Runtime](/infrastructure-as-effects/runtime) |
| 1706 | * page for the full explanation. |
| 1707 | * |
| 1708 | * - **Async** — plain `async fetch` handler, no Effect runtime in the bundle. |
| 1709 | * - **Effect** — Effect implementation passed directly, single file. |
| 1710 | * - **Layer** — class and `.make()` in a single file; Rolldown tree-shakes `.make()` from consumers. |
| 1711 | * ### Protect with Access |
| 1712 | * Put Cloudflare Access in front of the Worker with the `access` prop — |
| 1713 | * unauthenticated requests are redirected to your team's login page, and |
| 1714 | * handlers read the authenticated identity from `ctx.access` via |
| 1715 | * `Cloudflare.Access.Context`. See the |
| 1716 | * [Protect a Worker with Access](/cloudflare/security/access) guide. |
| 1717 | * |
| 1718 | * **Example:** Dedicated application — per-Worker policies |
| 1719 | * The `{ policies }` form declares an Access application owned by this |
| 1720 | * Worker (namespaced under it as `<Worker>/Access`), created, updated, |
| 1721 | * and deleted with it: |
| 1722 | * ```typescript |
| 1723 | * export default Cloudflare.Worker( |
| 1724 | * "Api", |
| 1725 | * { |
| 1726 | * main: import.meta.url, |
| 1727 | * access: { |
| 1728 | * policies: [ |
| 1729 | * { decision: "allow", include: [{ emailDomain: "example.com" }] }, |
| 1730 | * ], |
| 1731 | * }, |
| 1732 | * // simulate the authenticated state under `alchemy dev` |
| 1733 | * dev: { access: { aud: "dev", identity: { email: "dev@example.com" } } }, |
| 1734 | * }, |
| 1735 | * Effect.gen(function* () { |
| 1736 | * return { |
| 1737 | * fetch: Effect.gen(function* () { |
| 1738 | * const access = yield* Cloudflare.Access.Context; |
| 1739 | * const identity = yield* access!.getIdentity(); |
| 1740 | * return yield* HttpServerResponse.json({ email: identity?.email }); |
| 1741 | * }), |
| 1742 | * }; |
| 1743 | * }), |
| 1744 | * ); |
| 1745 | * ``` |
| 1746 | * |
| 1747 | * **Example:** Shared application — one policy set, many Workers |
| 1748 | * Pass a `Cloudflare.Access.Application` directly to enroll into it. |
| 1749 | * Access policies are application-wide: every enrolled Worker is gated |
| 1750 | * by the same policy set. |
| 1751 | * ```typescript |
| 1752 | * const TeamOnly = Cloudflare.Access.Application("TeamOnly", { |
| 1753 | * type: "self_hosted", |
| 1754 | * policies: [ |
| 1755 | * { decision: "allow", include: [{ emailDomain: "example.com" }] }, |
| 1756 | * ], |
| 1757 | * }); |
| 1758 | * |
| 1759 | * export default Cloudflare.Worker( |
| 1760 | * "Api", |
| 1761 | * { main: import.meta.url, access: TeamOnly }, |
| 1762 | * /* ... */ |
| 1763 | * ); |
| 1764 | * ``` |
| 1765 | * |
| 1766 | * ### Async Workers |
| 1767 | * You don't have to use Effect for your runtime code. If you create |
| 1768 | * a Worker resource with `main` pointing at a file but provide no |
| 1769 | * `Effect.gen` implementation, Alchemy bundles and deploys that file |
| 1770 | * as-is. Your handler is a plain `async fetch` — no Effect runtime |
| 1771 | * is included in the bundle. |
| 1772 | * |
| 1773 | * Use the `env` prop to declare which resources, `Config` values, |
| 1774 | * and literal env vars are available at runtime, and |
| 1775 | * `Cloudflare.InferEnv` to extract a fully typed `env` object from |
| 1776 | * them. |
| 1777 | * |
| 1778 | * See the [Workers guide](/cloudflare/compute/workers) |
| 1779 | * for a comprehensive walkthrough of all binding types (R2, D1, |
| 1780 | * Durable Objects, Assets, and more). |
| 1781 | * |
| 1782 | * **Example:** Defining an async Worker in your stack |
| 1783 | * ```typescript |
| 1784 | * // alchemy.run.ts |
| 1785 | * const db = yield* Cloudflare.D1.Database("DB"); |
| 1786 | * const bucket = yield* Cloudflare.R2.Bucket("Bucket"); |
| 1787 | * |
| 1788 | * export type WorkerEnv = Cloudflare.InferEnv<typeof Worker>; |
| 1789 | * |
| 1790 | * export const Worker = Cloudflare.Worker("Worker", { |
| 1791 | * main: "./src/worker.ts", |
| 1792 | * env: { db, bucket }, |
| 1793 | * }); |
| 1794 | * ``` |
| 1795 | * |
| 1796 | * **Example:** Writing the async handler |
| 1797 | * ```typescript |
| 1798 | * // src/worker.ts |
| 1799 | * import type { WorkerEnv } from "../alchemy.run.ts"; |
| 1800 | * |
| 1801 | * export default { |
| 1802 | * async fetch(request: Request, env: WorkerEnv) { |
| 1803 | * if (request.method === "GET") { |
| 1804 | * const object = await env.bucket.get("key"); |
| 1805 | * return new Response(object?.body ?? null); |
| 1806 | * } |
| 1807 | * return new Response("Not Found", { status: 404 }); |
| 1808 | * }, |
| 1809 | * }; |
| 1810 | * ``` |
| 1811 | * |
| 1812 | * **Example:** Binding a named entrypoint |
| 1813 | * |
| 1814 | * `env: { TARGET: worker }` targets the Worker's default entrypoint. |
| 1815 | * `Cloudflare.WorkerEntrypoint` binds one of its named |
| 1816 | * `WorkerEntrypoint` class exports instead; `InferEnv` types the entry |
| 1817 | * as a `Fetcher` stub whose RPC methods are called directly. |
| 1818 | * ```typescript |
| 1819 | * const caller = yield* Cloudflare.Worker("Caller", { |
| 1820 | * main: "./src/caller.ts", |
| 1821 | * env: { |
| 1822 | * API: Cloudflare.WorkerEntrypoint(target, "Api"), // env.API.greet("alice") |
| 1823 | * // one of this Worker's own entrypoints |
| 1824 | * MCP: Cloudflare.WorkerEntrypoint("McpEntrypoint"), |
| 1825 | * }, |
| 1826 | * }); |
| 1827 | * ``` |
| 1828 | * |
| 1829 | * **Example:** Entrypoint props |
| 1830 | * |
| 1831 | * The options form attaches properties the target entrypoint reads from |
| 1832 | * `this.ctx.props`. `Output` values resolve at deploy time. `alchemy dev` |
| 1833 | * delivers `props` to the local workerd; the deploy API's binding schema |
| 1834 | * does not carry the field yet, so `props` are dropped at upload while the |
| 1835 | * binding itself deploys correctly. |
| 1836 | * ```typescript |
| 1837 | * env: { |
| 1838 | * VENDOR: Cloudflare.WorkerEntrypoint(vendorWorker, { |
| 1839 | * entrypoint: "Vendor", |
| 1840 | * props: { baseUrl: site.url }, |
| 1841 | * }), |
| 1842 | * } |
| 1843 | * ``` |
| 1844 | * |
| 1845 | * ### Python Workers |
| 1846 | * Point `main` at a `.py` file to deploy a |
| 1847 | * [Python Worker](https://developers.cloudflare.com/workers/languages/python/) |
| 1848 | * (open beta). There is no bundling step — the entry and every sibling |
| 1849 | * `.py` module upload as-is and are interpreted by Pyodide, and the |
| 1850 | * `python_workers` compatibility flag is added automatically. Like async |
| 1851 | * Workers, Python Workers take no inline Effect implementation; declare |
| 1852 | * bindings with the `env` prop and read them from `self.env` in Python. |
| 1853 | * |
| 1854 | * Dependencies come from `pyproject.toml` next to the entry: Alchemy |
| 1855 | * vendors `[project.dependencies]` with [uv](https://docs.astral.sh/uv/) |
| 1856 | * against the Pyodide wheel index and uploads them under |
| 1857 | * `python_modules/`. If a `python_modules/` directory already exists |
| 1858 | * (e.g. produced by `pywrangler sync`), it is uploaded as-is and uv is |
| 1859 | * not invoked. |
| 1860 | * |
| 1861 | * See the [Python Workers guide](/cloudflare/compute/python-workers) |
| 1862 | * for the full walkthrough. |
| 1863 | * |
| 1864 | * **Example:** Defining a Python Worker in your stack |
| 1865 | * ```typescript |
| 1866 | * // alchemy.run.ts |
| 1867 | * const kv = yield* Cloudflare.KV.Namespace("Cache"); |
| 1868 | * |
| 1869 | * export const Worker = Cloudflare.Worker("Worker", { |
| 1870 | * main: "./src/worker.py", |
| 1871 | * env: { CACHE: kv }, |
| 1872 | * }); |
| 1873 | * ``` |
| 1874 | * |
| 1875 | * **Example:** Writing the Python handler |
| 1876 | * ```python |
| 1877 | * # src/worker.py |
| 1878 | * from workers import Response, WorkerEntrypoint |
| 1879 | * |
| 1880 | * class Default(WorkerEntrypoint): |
| 1881 | * async def fetch(self, request): |
| 1882 | * cached = await self.env.CACHE.get("greeting") |
| 1883 | * return Response(cached or "Hello from Python!") |
| 1884 | * ``` |
| 1885 | * |
| 1886 | * **Example:** Vendoring dependencies with pyproject.toml |
| 1887 | * ```toml |
| 1888 | * # src/pyproject.toml — vendored with uv on deploy |
| 1889 | * [project] |
| 1890 | * name = "my-worker" |
| 1891 | * version = "0.1.0" |
| 1892 | * requires-python = ">=3.13" |
| 1893 | * dependencies = ["humanize"] |
| 1894 | * ``` |
| 1895 | * |
| 1896 | * ### Effect Workers |
| 1897 | * Pass the Effect implementation as the third argument. This is the |
| 1898 | * simplest Effect-based approach — everything lives in one file. |
| 1899 | * Convenient for standalone Workers that don't need to be referenced |
| 1900 | * by other Workers. |
| 1901 | * |
| 1902 | * **Example:** Worker Effect |
| 1903 | * ```typescript |
| 1904 | * export default class MyWorker extends Cloudflare.Worker<MyWorker>()( |
| 1905 | * "MyWorker", |
| 1906 | * { main: import.meta.url }, |
| 1907 | * Effect.gen(function* () { |
| 1908 | * // Construction: bind resources |
| 1909 | * const kv = yield* Cloudflare.KV.ReadWriteNamespace(MyKV); |
| 1910 | * |
| 1911 | * return { |
| 1912 | * // Runtime: use them |
| 1913 | * fetch: Effect.gen(function* () { |
| 1914 | * const value = yield* kv.get("key"); |
| 1915 | * return HttpServerResponse.text(value ?? "not found"); |
| 1916 | * }), |
| 1917 | * }; |
| 1918 | * }), |
| 1919 | * ) {} |
| 1920 | * ``` |
| 1921 | * |
| 1922 | * ### Worker Layer |
| 1923 | * When two Workers need to reference each other (e.g. WorkerA calls |
| 1924 | * WorkerB and vice versa), or you simply want optimal tree-shaking, |
| 1925 | * define the Worker class separately from its `.make()` call. The |
| 1926 | * class is a lightweight identifier; `.make()` provides the runtime |
| 1927 | * implementation as an `export default`. Rolldown treats `.make()` |
| 1928 | * as pure, so any Worker that imports the class to bind it will not |
| 1929 | * pull in the `.make()` dependencies — the bundler tree-shakes |
| 1930 | * them away entirely. |
| 1931 | * |
| 1932 | * The class and `.make()` can live in the same file. This is the |
| 1933 | * same pattern used by `Container` and `DurableObject`, |
| 1934 | * and is recommended for any cross-Worker or cross-DO bindings. |
| 1935 | * |
| 1936 | * **Example:** Worker Layer (class + .make() in one file) |
| 1937 | * ```typescript |
| 1938 | * // src/WorkerB.ts — the tag carries the name + RPC shape; props live |
| 1939 | * // on `.make()`. |
| 1940 | * export class WorkerB extends Cloudflare.Worker< |
| 1941 | * WorkerB, |
| 1942 | * { greet: (name: string) => Effect.Effect<string> } |
| 1943 | * >()("WorkerB") {} |
| 1944 | * |
| 1945 | * export default WorkerB.make( |
| 1946 | * { main: import.meta.url }, |
| 1947 | * Effect.gen(function* () { |
| 1948 | * // Construction: bind resources |
| 1949 | * const kv = yield* Cloudflare.KV.ReadWriteNamespace(MyKV); |
| 1950 | * |
| 1951 | * return { |
| 1952 | * // Runtime: use them |
| 1953 | * greet: (name: string) => |
| 1954 | * Effect.gen(function* () { |
| 1955 | * yield* kv.put("last-greeted", name); |
| 1956 | * return `Hello ${name}`; |
| 1957 | * }), |
| 1958 | * }; |
| 1959 | * }), |
| 1960 | * ); |
| 1961 | * ``` |
| 1962 | * |
| 1963 | * **Example:** Binding a Worker Layer from another Worker |
| 1964 | * ```typescript |
| 1965 | * // src/WorkerA.ts — imports WorkerB; bundler tree-shakes .make() |
| 1966 | * import WorkerB from "./WorkerB.ts"; |
| 1967 | * |
| 1968 | * export default class WorkerA extends Cloudflare.Worker<WorkerA>()( |
| 1969 | * "WorkerA", |
| 1970 | * { main: import.meta.url }, |
| 1971 | * Effect.gen(function* () { |
| 1972 | * const b = yield* Cloudflare.Workers.bindWorker(WorkerB); |
| 1973 | * return { |
| 1974 | * fetch: Effect.gen(function* () { |
| 1975 | * return yield* b.greet("world"); |
| 1976 | * }), |
| 1977 | * }; |
| 1978 | * }), |
| 1979 | * ) {} |
| 1980 | * ``` |
| 1981 | * |
| 1982 | * **Example:** Binding a Worker to itself |
| 1983 | * |
| 1984 | * Declare the class before `.make()` so the implementation can reference it. |
| 1985 | * The self binding uses workerd's `ctx.exports` loopback, so nothing is |
| 1986 | * added to the Worker's deployed bindings. |
| 1987 | * ```typescript |
| 1988 | * export class Greeter extends Cloudflare.Worker< |
| 1989 | * Greeter, |
| 1990 | * { greet: (name: string) => Effect.Effect<string> } |
| 1991 | * >()("Greeter") {} |
| 1992 | * |
| 1993 | * export default Greeter.make( |
| 1994 | * { main: import.meta.url }, |
| 1995 | * Effect.gen(function* () { |
| 1996 | * const self = yield* Cloudflare.Workers.bindWorker(Greeter); |
| 1997 | * return { |
| 1998 | * greet: (name: string) => Effect.succeed(`Hello ${name}`), |
| 1999 | * fetch: Effect.gen(function* () { |
| 2000 | * return HttpServerResponse.text(yield* self.greet("world")); |
| 2001 | * }), |
| 2002 | * }; |
| 2003 | * }), |
| 2004 | * ); |
| 2005 | * ``` |
| 2006 | * |
| 2007 | * ### Configuration |
| 2008 | * The props object controls compatibility flags, static assets, and |
| 2009 | * build options. These are evaluated at deploy time. |
| 2010 | * |
| 2011 | * **Example:** Enabling Node.js compatibility |
| 2012 | * ```typescript |
| 2013 | * { |
| 2014 | * main: import.meta.url, |
| 2015 | * compatibility: { |
| 2016 | * flags: ["nodejs_compat"], |
| 2017 | * date: "2026-08-31", |
| 2018 | * }, |
| 2019 | * } |
| 2020 | * ``` |
| 2021 | * |
| 2022 | * **Example:** Serving static assets |
| 2023 | * ```typescript |
| 2024 | * { |
| 2025 | * main: import.meta.url, |
| 2026 | * assets: "./public", |
| 2027 | * } |
| 2028 | * ``` |
| 2029 | * |
| 2030 | * **Example:** Run the Worker before the asset layer |
| 2031 | * |
| 2032 | * A path that matches no asset already falls through to the Worker. |
| 2033 | * `runWorkerFirst` routes the listed paths (or, with `true`, every |
| 2034 | * request) through the Worker ahead of asset matching, for an asset |
| 2035 | * that would otherwise shadow a route or an SPA fallback that would |
| 2036 | * answer an API call. A `_headers` or `_redirects` file in the |
| 2037 | * directory is applied automatically and `.assetsignore` excludes |
| 2038 | * files from the upload. |
| 2039 | * ```typescript |
| 2040 | * { |
| 2041 | * main: import.meta.url, |
| 2042 | * assets: { |
| 2043 | * directory: "./public", |
| 2044 | * runWorkerFirst: ["/api/*", "/admin/*"], |
| 2045 | * }, |
| 2046 | * } |
| 2047 | * ``` |
| 2048 | * |
| 2049 | * **Example:** Assets-only Worker (static site) |
| 2050 | * Omit `main` and `script` entirely to deploy a static site: no Worker |
| 2051 | * code is uploaded — Cloudflare's asset layer serves every request and |
| 2052 | * applies `htmlHandling` / `notFoundHandling` (including SPA fallback) |
| 2053 | * itself, exactly like an assets-only `wrangler deploy`. |
| 2054 | * ```typescript |
| 2055 | * const site = yield* Cloudflare.Worker("Site", { |
| 2056 | * assets: { |
| 2057 | * directory: "./public", |
| 2058 | * htmlHandling: "drop-trailing-slash", |
| 2059 | * notFoundHandling: "404-page", |
| 2060 | * }, |
| 2061 | * domain: "static.example.com", |
| 2062 | * }); |
| 2063 | * ``` |
| 2064 | * |
| 2065 | * **Example:** Zone routes |
| 2066 | * ```typescript |
| 2067 | * { |
| 2068 | * main: import.meta.filename, |
| 2069 | * routes: [ |
| 2070 | * { pattern: "api.example.com/*", zoneName: "example.com" }, |
| 2071 | * { pattern: "example.com/api/*", zoneId: "<YOUR_ZONE_ID>" }, |
| 2072 | * ], |
| 2073 | * } |
| 2074 | * ``` |
| 2075 | * |
| 2076 | * **Example:** Federating one hostname across Workers |
| 2077 | * Routes take precedence over custom domains, so one Worker can own the |
| 2078 | * hostname while others claim paths under it — no gateway Worker in the |
| 2079 | * request path, and each Worker binds only what its paths need. `alchemy |
| 2080 | * dev` applies the same routing on the custom-domain Worker's local URL. |
| 2081 | * ```typescript |
| 2082 | * const home = yield* Cloudflare.Worker("Home", { |
| 2083 | * main: "./src/home.ts", |
| 2084 | * domain: "api.example.com", |
| 2085 | * }); |
| 2086 | * yield* Cloudflare.Worker("Products", { |
| 2087 | * main: "./src/products.ts", |
| 2088 | * routes: [{ pattern: "api.example.com/products*" }], |
| 2089 | * }); |
| 2090 | * yield* Cloudflare.Worker("Orders", { |
| 2091 | * main: "./src/orders.ts", |
| 2092 | * routes: [{ pattern: "api.example.com/orders*" }], |
| 2093 | * }); |
| 2094 | * // https://api.example.com/orders/1 runs Orders; /about runs Home. |
| 2095 | * return { url: home.url }; |
| 2096 | * ``` |
| 2097 | * |
| 2098 | * **Example:** Deploying a prebuilt Worker without bundling |
| 2099 | * When `main` already points at a complete, runtime-ready ESM bundle |
| 2100 | * produced by an external tool (e.g. OpenNext), set `bundle: false` to |
| 2101 | * upload it byte-for-byte. The entry's directory is walked recursively |
| 2102 | * and every file matching the module rules (by default `.js`, `.mjs`, |
| 2103 | * `.wasm`, `.txt`, `.html`, `.sql`, and `.bin`) is uploaded as an |
| 2104 | * additional module named by its path relative to that directory. |
| 2105 | * ```typescript |
| 2106 | * { |
| 2107 | * main: "./.open-next/worker.js", |
| 2108 | * bundle: false, |
| 2109 | * assets: "./.open-next/assets", |
| 2110 | * } |
| 2111 | * ``` |
| 2112 | * |
| 2113 | * **Example:** Running a custom workerd binary in dev |
| 2114 | * `dev.workerd` configures the local `workerd` process: `path` swaps |
| 2115 | * the binary from the `workerd` npm package (e.g. on NixOS, where it |
| 2116 | * can't start), `v8Flags` adds V8 flags and `env` adds environment |
| 2117 | * variables. `ALCHEMY_WORKERD_PATH` sets the binary for every workerd |
| 2118 | * process instead, including ones shared across Workers. |
| 2119 | * ```typescript |
| 2120 | * { |
| 2121 | * main: "./src/worker.ts", |
| 2122 | * dev: { |
| 2123 | * workerd: { |
| 2124 | * path: "workerd", |
| 2125 | * v8Flags: ["--max-old-space-size=4096"], |
| 2126 | * env: { TZ: "UTC" }, |
| 2127 | * }, |
| 2128 | * }, |
| 2129 | * } |
| 2130 | * ``` |
| 2131 | * |
| 2132 | * ### Bundling & Tree-shaking |
| 2133 | * `main` is bundled with rolldown at deploy time. Unused code is |
| 2134 | * tree-shaken. `effect`, alchemy, and `@distilled.cloud` are marked |
| 2135 | * pure so unused parts prune more aggressively. Your app is not |
| 2136 | * marked pure. |
| 2137 | * |
| 2138 | * **Example:** Mark additional packages as pure |
| 2139 | * Only list packages with no top-level side effects. |
| 2140 | * ```typescript |
| 2141 | * { |
| 2142 | * main: "./src/worker.ts", |
| 2143 | * build: { |
| 2144 | * pure: { packages: ["my-lib", "@my-scope/*"] }, |
| 2145 | * }, |
| 2146 | * } |
| 2147 | * ``` |
| 2148 | * |
| 2149 | * **Example:** Replace Node modules with Worker-compatible stubs |
| 2150 | * Use Rolldown's `build.input.resolve.alias` for module replacements. |
| 2151 | * Aliases apply to imports and static `require()` calls before Node |
| 2152 | * compatibility shims. Use absolute paths for file replacements. |
| 2153 | * Keep bundling enabled: `bundle: false` uploads files unchanged and |
| 2154 | * does not apply aliases. Alternatively, apply aliases in your external |
| 2155 | * build before uploading its output with `bundle: false`. |
| 2156 | * ```typescript |
| 2157 | * import * as Path from "effect/Path"; |
| 2158 | * |
| 2159 | * const path = yield* Path.Path; |
| 2160 | * const stub = yield* path.fromFileUrl( |
| 2161 | * new URL("./.mastra/output/module-stub.mjs", import.meta.url), |
| 2162 | * ); |
| 2163 | * const worker = yield* Cloudflare.Worker("Worker", { |
| 2164 | * main: "./.mastra/output/index.mjs", |
| 2165 | * compatibility: { |
| 2166 | * date: "2025-04-01", |
| 2167 | * flags: ["nodejs_compat", "nodejs_compat_populate_process_env"], |
| 2168 | * }, |
| 2169 | * build: { |
| 2170 | * input: { resolve: { alias: { module: stub, "node:module": stub } } }, |
| 2171 | * }, |
| 2172 | * }); |
| 2173 | * ``` |
| 2174 | * |
| 2175 | * **Example:** Turn it off |
| 2176 | * ```typescript |
| 2177 | * { |
| 2178 | * main: "./src/worker.ts", |
| 2179 | * build: { pure: false }, |
| 2180 | * } |
| 2181 | * ``` |
| 2182 | * |
| 2183 | * ### URLs & Domains |
| 2184 | * Every URL that serves the Worker is collected in `worker.urls`, most |
| 2185 | * significant first, and `worker.url` is always `urls[0]`. The ranking: |
| 2186 | * the canonical custom domain (`domain.name`), then aliases in declared |
| 2187 | * order, then the stable `workers.dev` URL, then version preview URLs. |
| 2188 | * Under `alchemy dev`, `urls` is the local dev server's |
| 2189 | * `[localhost, ...LAN]` addresses instead. Redirect hostnames never |
| 2190 | * appear in `urls` — they serve no content. |
| 2191 | * |
| 2192 | * The `workersDev` prop controls the `workers.dev` surface (`true` by |
| 2193 | * default = stable URL + version previews; `false` = neither; object form |
| 2194 | * toggles independently), and the `domain` prop attaches custom domains — |
| 2195 | * DNS records and edge certificates are managed automatically. |
| 2196 | * |
| 2197 | * **Example:** Custom domain with aliases and redirects |
| 2198 | * ```typescript |
| 2199 | * const worker = yield* Cloudflare.Worker("Api", { |
| 2200 | * main: "./src/api.ts", |
| 2201 | * domain: { |
| 2202 | * name: "example.com", |
| 2203 | * zoneId: "<YOUR_ZONE_ID>", |
| 2204 | * aliases: ["www.example.com"], |
| 2205 | * redirects: ["old.example.com"], // 301 → https://example.com |
| 2206 | * }, |
| 2207 | * }); |
| 2208 | * // worker.url === "https://example.com" |
| 2209 | * // worker.urls === ["https://example.com", "https://www.example.com", |
| 2210 | * // "https://<name>.<account>.workers.dev"] |
| 2211 | * ``` |
| 2212 | * |
| 2213 | * **Example:** workers.dev toggles |
| 2214 | * ```typescript |
| 2215 | * // No workers.dev URLs at all: |
| 2216 | * { main: "./src/api.ts", workersDev: false, domain: "api.example.com" } |
| 2217 | * |
| 2218 | * // Previews only — each deploy's version preview URL becomes worker.url: |
| 2219 | * { main: "./src/api.ts", workersDev: { enabled: false, previewsEnabled: true } } |
| 2220 | * ``` |
| 2221 | * |
| 2222 | * **Example:** All URLs as a CORS allow-list |
| 2223 | * ```typescript |
| 2224 | * const site = yield* Cloudflare.Worker("Site", { |
| 2225 | * main: "./src/site.ts", |
| 2226 | * domain: { name: "example.com", aliases: ["www.example.com"] }, |
| 2227 | * }); |
| 2228 | * const api = yield* Cloudflare.Worker("Api", { |
| 2229 | * main: "./src/api.ts", |
| 2230 | * env: { ALLOWED_ORIGINS: site.urls }, |
| 2231 | * }); |
| 2232 | * ``` |
| 2233 | * |
| 2234 | * **Example:** Route 53 domain through Cloudflare for SaaS |
| 2235 | * ```typescript |
| 2236 | * // Once per SaaS zone (a Cloudflare zone with Cloudflare for SaaS |
| 2237 | * // enabled): an originless proxied record as the fallback origin. |
| 2238 | * const origin = yield* Cloudflare.DNS.Record("SaasOrigin", { |
| 2239 | * zoneId: "<SAAS_ZONE_ID>", |
| 2240 | * name: "customers.my-saas.com", |
| 2241 | * type: "AAAA", |
| 2242 | * content: "100::", |
| 2243 | * proxied: true, |
| 2244 | * }); |
| 2245 | * const fallback = yield* Cloudflare.CustomHostname.FallbackOrigin( |
| 2246 | * "SaasFallback", |
| 2247 | * { zoneId: "<SAAS_ZONE_ID>", origin: origin.name }, |
| 2248 | * ); |
| 2249 | * |
| 2250 | * // app.example.com's DNS lives in Route 53: Route 53 gets the |
| 2251 | * // verification TXT records and a CNAME to the fallback origin, and the |
| 2252 | * // Worker serves `app.example.com/*` on the SaaS zone. |
| 2253 | * const worker = yield* Cloudflare.Worker("Api", { |
| 2254 | * main: "./src/api.ts", |
| 2255 | * domain: { |
| 2256 | * name: "app.example.com", |
| 2257 | * zoneId: "<SAAS_ZONE_ID>", |
| 2258 | * cnameTarget: fallback.origin, |
| 2259 | * dns: AWS.Route53.Adapter({ hostedZoneId: "Z1234567890" }), |
| 2260 | * }, |
| 2261 | * }); |
| 2262 | * ``` |
| 2263 | * |
| 2264 | * ### Worker Previews |
| 2265 | * The `preview` prop maps Cloudflare's |
| 2266 | * [Worker Previews](https://developers.cloudflare.com/workers/previews/) — |
| 2267 | * a named copy of a Worker with its own URL, variables, secrets, bindings, |
| 2268 | * and isolated same-Worker Durable Object state. Use it for branch and |
| 2269 | * pull-request testing. Distinct from {@link version}: a version is an |
| 2270 | * immutable upload onto the parent script (gradual rollouts, canaries); |
| 2271 | * a Preview does not take production traffic. |
| 2272 | * |
| 2273 | * A Preview Worker's `url` is its stable Preview URL |
| 2274 | * (`<name>-<parent>.<subdomain>.workers.dev`, or |
| 2275 | * `<name>.<domain>` when the parent has `domain.previews`). The name |
| 2276 | * defaults to the stack stage (override with `preview.name`). Destroying |
| 2277 | * the Preview Worker deletes the Preview; the parent is untouched. |
| 2278 | * |
| 2279 | * **Example:** PR preview of another stage's Worker |
| 2280 | * ```typescript |
| 2281 | * const parent = yield* Cloudflare.Worker.ref("Api", { stage: "prod" }); |
| 2282 | * const preview = yield* Cloudflare.Worker("Api", { |
| 2283 | * main: "./src/api.ts", |
| 2284 | * preview: { of: parent, message: `PR #${process.env.PR_NUMBER}` }, |
| 2285 | * }); |
| 2286 | * // preview.url -> https://<stage>-<name>.<subdomain>.workers.dev |
| 2287 | * ``` |
| 2288 | * |
| 2289 | * **Example:** Custom-domain Preview URLs |
| 2290 | * ```typescript |
| 2291 | * // On the production Worker: |
| 2292 | * yield* Cloudflare.Worker("Api", { |
| 2293 | * main: "./src/api.ts", |
| 2294 | * domain: { name: "app.example.com", previews: true }, |
| 2295 | * }); |
| 2296 | * // A Preview of that Worker is then at https://<preview-name>.app.example.com |
| 2297 | * ``` |
| 2298 | * |
| 2299 | * ### Versions & Gradual Deployments |
| 2300 | * The `version` prop maps Cloudflare's |
| 2301 | * [versions and gradual deployments](https://developers.cloudflare.com/workers/configuration/versions-and-deployments/) |
| 2302 | * onto Alchemy stages. A Worker with `version.parent` set uploads an |
| 2303 | * immutable *version* to the parent Worker's script instead of creating its |
| 2304 | * own — give it `traffic` to run it as a canary, or use `version.traffic` |
| 2305 | * on a normal Worker to roll out its own deploys gradually. For branch |
| 2306 | * and pull-request testing, use {@link preview} instead. |
| 2307 | * |
| 2308 | * A version worker's `url` is its *aliased* preview URL |
| 2309 | * (`<alias>-<name>.<subdomain>.workers.dev`) — the alias is derived from |
| 2310 | * the stack, stage, and logical id (override with `version.alias`), so the |
| 2311 | * URL is stable across deploys and always points at the latest uploaded |
| 2312 | * version. The per-version URL (`<version-prefix>-...`) is also returned |
| 2313 | * in `domains`. Because the aliased URL is known before the version |
| 2314 | * exists, `Worker.URL` works on version workers and resolves to it. |
| 2315 | * |
| 2316 | * A version carries code, static assets, bindings, and compatibility |
| 2317 | * settings. Script-level settings (routes, domains, crons, tags, |
| 2318 | * observability, …) belong to the parent and are rejected on version workers, |
| 2319 | * as are locally-hosted Durable Object or Workflow classes. Preview URLs |
| 2320 | * require the parent's workers.dev subdomain to be enabled (the default). |
| 2321 | * |
| 2322 | * **Example:** Upload a version without routing traffic |
| 2323 | * ```typescript |
| 2324 | * // Inspect this upload at its Version URL before a gradual rollout. |
| 2325 | * // For branch/PR testing, use `preview.of` instead. |
| 2326 | * yield* Cloudflare.Worker("MyWorker", { |
| 2327 | * main: "./src/worker.ts", |
| 2328 | * version: { traffic: 0, tag: process.env.GITHUB_SHA }, |
| 2329 | * }); |
| 2330 | * ``` |
| 2331 | * |
| 2332 | * **Example:** Canary: send 10% of the parent's traffic to a version |
| 2333 | * ```typescript |
| 2334 | * const parent = yield* Cloudflare.Worker.ref("MyWorker", { stage: "prod" }); |
| 2335 | * yield* Cloudflare.Worker("MyWorker", { |
| 2336 | * main: "./src/worker.ts", |
| 2337 | * version: { parent, traffic: 10 }, |
| 2338 | * }); |
| 2339 | * ``` |
| 2340 | * |
| 2341 | * **Example:** Gradual rollout of a Worker's own deploy |
| 2342 | * ```typescript |
| 2343 | * // The new version takes 25% of traffic; the previously-live version |
| 2344 | * // keeps 75%. Bump traffic (or remove the prop) and re-deploy to promote. |
| 2345 | * yield* Cloudflare.Worker("MyWorker", { |
| 2346 | * main: "./src/worker.ts", |
| 2347 | * version: { traffic: 25 }, |
| 2348 | * }); |
| 2349 | * ``` |
| 2350 | * |
| 2351 | * **Example:** Keep users on one version during the rollout |
| 2352 | * ```typescript |
| 2353 | * // Percentages route each request independently; affinity pins users by |
| 2354 | * // filling the Cloudflare-Workers-Version-Key header on zone traffic — |
| 2355 | * // here from the session cookie, falling back to the client IP. Requires |
| 2356 | * // a `domain` or `routes` (with `parent`, the parent's). |
| 2357 | * yield* Cloudflare.Worker("MyWorker", { |
| 2358 | * main: "./src/worker.ts", |
| 2359 | * domain: "api.example.com", |
| 2360 | * version: { |
| 2361 | * traffic: 25, |
| 2362 | * affinity: { cookie: "session_id", ip: true }, |
| 2363 | * }, |
| 2364 | * }); |
| 2365 | * ``` |
| 2366 | * |
| 2367 | * ### The Worker's own URL |
| 2368 | * `Worker.URL` injects the URL a Worker is served at as a binding on that |
| 2369 | * same Worker — the first custom `domain` if one is configured, otherwise |
| 2370 | * its `workers.dev` URL, always equal to the resource's `url` attribute. |
| 2371 | * Under `alchemy dev` it resolves to the local dev server's URL. |
| 2372 | * |
| 2373 | * **Example:** Read the Worker's own URL inside a handler |
| 2374 | * ```typescript |
| 2375 | * Cloudflare.Worker( |
| 2376 | * "Api", |
| 2377 | * { main: import.meta.url }, |
| 2378 | * Effect.gen(function* () { |
| 2379 | * // Attaches the binding and returns a deferred accessor. |
| 2380 | * const url = yield* Cloudflare.Worker.URL; |
| 2381 | * |
| 2382 | * return { |
| 2383 | * fetch: Effect.gen(function* () { |
| 2384 | * const publicUrl = yield* url; |
| 2385 | * return yield* HttpServerResponse.json({ url: publicUrl }); |
| 2386 | * }), |
| 2387 | * }; |
| 2388 | * }), |
| 2389 | * ); |
| 2390 | * ``` |
| 2391 | * |
| 2392 | * **Example:** Inject the URL into an async Worker's env |
| 2393 | * `InferEnv` types the entry as `string`. A `VITE_`-prefixed key on a |
| 2394 | * vite-built Worker is additionally inlined into the client bundle as |
| 2395 | * `import.meta.env.VITE_PUBLIC_URL` at build time. |
| 2396 | * ```typescript |
| 2397 | * export const Worker = Cloudflare.Worker("Worker", { |
| 2398 | * main: "./src/worker.ts", |
| 2399 | * env: { PUBLIC_URL: Cloudflare.Worker.URL }, |
| 2400 | * }); |
| 2401 | * |
| 2402 | * export type WorkerEnv = Cloudflare.InferEnv<typeof Worker>; |
| 2403 | * // { PUBLIC_URL: string } |
| 2404 | * ``` |
| 2405 | * |
| 2406 | * ### Observability |
| 2407 | * Cloudflare Workers Observability is on by default — `logs.enabled` and |
| 2408 | * `logs.invocationLogs` are turned on if you don't pass an `observability` |
| 2409 | * prop. Pass the prop yourself to tune sampling, enable persistence, or |
| 2410 | * turn on the new `traces` channel (the same toggle the dashboard's |
| 2411 | * Observability tab writes). |
| 2412 | * |
| 2413 | * Effect-native Workers should prefer `Cloudflare.Telemetry()` over |
| 2414 | * setting `observability.traces` by hand: providing the Layer enables |
| 2415 | * traces on this Worker and mirrors `Effect.withSpan` into the Cloudflare |
| 2416 | * waterfall. Pin `compatibility: { date: "2026-08-25" }` (or later) until |
| 2417 | * the global default date is raised past 2026-07-28. |
| 2418 | * |
| 2419 | * Field names match the Cloudflare API (camelCased): `headSamplingRate`, |
| 2420 | * `invocationLogs`, etc. |
| 2421 | * |
| 2422 | * **Example:** Enabling logs and traces |
| 2423 | * ```typescript |
| 2424 | * { |
| 2425 | * main: import.meta.url, |
| 2426 | * observability: { |
| 2427 | * enabled: true, |
| 2428 | * headSamplingRate: 1, |
| 2429 | * logs: { |
| 2430 | * enabled: true, |
| 2431 | * invocationLogs: true, |
| 2432 | * headSamplingRate: 1, |
| 2433 | * persist: true, |
| 2434 | * }, |
| 2435 | * traces: { |
| 2436 | * enabled: true, |
| 2437 | * headSamplingRate: 1, |
| 2438 | * persist: true, |
| 2439 | * }, |
| 2440 | * }, |
| 2441 | * } |
| 2442 | * ``` |
| 2443 | * |
| 2444 | * **Example:** Enabling Workers Issues |
| 2445 | * ```typescript |
| 2446 | * const worker = yield* Cloudflare.Worker("Api", { |
| 2447 | * main: "./src/worker.ts", |
| 2448 | * observability: { |
| 2449 | * issues: { enabled: true }, |
| 2450 | * }, |
| 2451 | * }); |
| 2452 | * ``` |
| 2453 | * |
| 2454 | * Workers Issues groups recurring failures in the Cloudflare dashboard. |
| 2455 | * Alchemy includes the flag in upload metadata and reconciles it through |
| 2456 | * script settings after a full deployment so it survives redeploys. Set |
| 2457 | * `issues.enabled` to `false` or remove `issues` to disable detection. |
| 2458 | * Configure logs and traces alongside `issues` when you need those channels. |
| 2459 | * Version-only uploads and gradual rollouts retain the parent's settings. |
| 2460 | * |
| 2461 | * ### Tail Workers |
| 2462 | * A [Tail Worker](https://developers.cloudflare.com/workers/observability/logs/tail-workers/) |
| 2463 | * receives execution traces (console logs, exceptions, event metadata) from |
| 2464 | * other Workers. List it in a producer's `tailConsumers` and export a |
| 2465 | * `tail()` handler from the consumer; Cloudflare delivers each invocation's |
| 2466 | * trace events to every listed consumer after the invocation completes. |
| 2467 | * |
| 2468 | * **Example:** Sending a Worker's traces to a Tail Worker |
| 2469 | * ```typescript |
| 2470 | * const tailWorker = yield* Cloudflare.Worker("TailWorker", { |
| 2471 | * // exports: export default { async tail(events, env, ctx) { ... } } |
| 2472 | * main: "./src/tail.ts", |
| 2473 | * }); |
| 2474 | * |
| 2475 | * const api = yield* Cloudflare.Worker("Api", { |
| 2476 | * main: "./src/api.ts", |
| 2477 | * tailConsumers: [tailWorker], |
| 2478 | * }); |
| 2479 | * ``` |
| 2480 | * |
| 2481 | * A *streaming* Tail Worker receives the same invocation's events live, |
| 2482 | * while the producer is still executing: list it in |
| 2483 | * `streamingTailConsumers` and export a `tailStream()` handler that is |
| 2484 | * invoked with the invocation's `onset` event and returns a handler for |
| 2485 | * every subsequent event of the session, ending with the terminal |
| 2486 | * `outcome`. |
| 2487 | * |
| 2488 | * **Example:** Streaming a Worker's events to a streaming Tail Worker |
| 2489 | * ```typescript |
| 2490 | * const streamTailWorker = yield* Cloudflare.Worker("StreamTailWorker", { |
| 2491 | * // exports: export default { |
| 2492 | * // tailStream(onset, env, ctx) { |
| 2493 | * // return (event) => { ... }; // log, spanOpen, ..., outcome |
| 2494 | * // }, |
| 2495 | * // } |
| 2496 | * main: "./src/stream-tail.ts", |
| 2497 | * }); |
| 2498 | * |
| 2499 | * const api = yield* Cloudflare.Worker("Api", { |
| 2500 | * main: "./src/api.ts", |
| 2501 | * streamingTailConsumers: [streamTailWorker], |
| 2502 | * }); |
| 2503 | * ``` |
| 2504 | * |
| 2505 | * ### Workers Cache |
| 2506 | * Workers Cache puts a regionally tiered cache in front of the Worker — |
| 2507 | * cache hits are served from the edge without invoking the Worker (and |
| 2508 | * without billing CPU time). In an Effect-native Worker, enable it by |
| 2509 | * yielding `Cloudflare.cache()` in the Construction phase, which also returns the |
| 2510 | * runtime purge client; async Workers use the `cache` prop instead. Control |
| 2511 | * what gets cached from your handlers via standard response headers: |
| 2512 | * `Cache-Control` (including `stale-while-revalidate`), `Cache-Tag` for |
| 2513 | * tag-based purging, and `Vary` for content negotiation. |
| 2514 | * |
| 2515 | * The cache is scoped to a single Worker version by default, so every |
| 2516 | * deploy starts cold. Set `crossVersionCache: true` to share cached |
| 2517 | * responses across versions. |
| 2518 | * |
| 2519 | * **Example:** Enabling and purging the cache in an Effect Worker |
| 2520 | * ```typescript |
| 2521 | * Effect.gen(function* () { |
| 2522 | * // Construction: enable Workers Cache on this Worker |
| 2523 | * const { purge } = yield* Cloudflare.cache({ crossVersionCache: true }); |
| 2524 | * |
| 2525 | * return { |
| 2526 | * fetch: Effect.gen(function* () { |
| 2527 | * const request = yield* HttpServerRequest; |
| 2528 | * if (request.url.startsWith("/invalidate")) { |
| 2529 | * yield* purge({ tags: ["products"] }); |
| 2530 | * return HttpServerResponse.text("purged"); |
| 2531 | * } |
| 2532 | * return HttpServerResponse.text("hello", { |
| 2533 | * headers: { |
| 2534 | * "Cache-Control": "public, max-age=300, stale-while-revalidate=3600", |
| 2535 | * "Cache-Tag": "products,product:123", |
| 2536 | * }, |
| 2537 | * }); |
| 2538 | * }), |
| 2539 | * }; |
| 2540 | * }) |
| 2541 | * ``` |
| 2542 | * |
| 2543 | * **Example:** Enabling Workers Cache on an async Worker |
| 2544 | * ```typescript |
| 2545 | * { |
| 2546 | * main: "./src/worker.ts", |
| 2547 | * cache: { |
| 2548 | * enabled: true, |
| 2549 | * crossVersionCache: true, |
| 2550 | * }, |
| 2551 | * } |
| 2552 | * ``` |
| 2553 | * |
| 2554 | * **Example:** Caching one entrypoint behind an uncached gateway |
| 2555 | * ```typescript |
| 2556 | * // alchemy.run.ts |
| 2557 | * const api = yield* Cloudflare.Worker("Api", { |
| 2558 | * main: "./src/worker.ts", |
| 2559 | * entrypoints: { |
| 2560 | * default: { cache: { enabled: false } }, |
| 2561 | * Public: { cache: { enabled: true } }, |
| 2562 | * }, |
| 2563 | * }); |
| 2564 | * ``` |
| 2565 | * |
| 2566 | * ```typescript |
| 2567 | * // src/worker.ts |
| 2568 | * import { WorkerEntrypoint } from "cloudflare:workers"; |
| 2569 | * |
| 2570 | * export class Public extends WorkerEntrypoint { |
| 2571 | * async fetch() { |
| 2572 | * return new Response("hello", { |
| 2573 | * headers: { "Cache-Control": "public, max-age=300" }, |
| 2574 | * }); |
| 2575 | * } |
| 2576 | * } |
| 2577 | * |
| 2578 | * export default { |
| 2579 | * // the gateway runs on every request, then forwards to the cached entrypoint |
| 2580 | * async fetch(request: Request, env: unknown, ctx: ExecutionContext) { |
| 2581 | * if (!request.headers.get("authorization")) { |
| 2582 | * return new Response("unauthorized", { status: 401 }); |
| 2583 | * } |
| 2584 | * return ctx.exports.Public.fetch(request); |
| 2585 | * }, |
| 2586 | * }; |
| 2587 | * ``` |
| 2588 | * |
| 2589 | * ### Background Work & Scopes |
| 2590 | * Each incoming event (fetch, RPC call, scheduled run) gets its own Effect |
| 2591 | * `Scope`. When the handler finishes, the bridge closes that scope and |
| 2592 | * registers the close promise with workerd's `ctx.waitUntil` — so |
| 2593 | * finalizers added with `Effect.addFinalizer` inside a handler run *after* |
| 2594 | * the response is sent, without blocking it, and the Worker stays alive |
| 2595 | * until they settle. Streaming responses transfer the scope to the stream, |
| 2596 | * so those finalizers run when the stream completes instead. |
| 2597 | * |
| 2598 | * For ad-hoc background work, `Cloudflare.waitUntil(effect)` forks an |
| 2599 | * Effect with the caller's full context and keeps the invocation alive |
| 2600 | * until it settles. It is `RuntimeContext`-colored, so it can only run |
| 2601 | * inside a handler. |
| 2602 | * |
| 2603 | * The constructor is evaluated once per isolate: the bridge builds the |
| 2604 | * Worker's layer stack on the first event and every later event reuses the |
| 2605 | * built services. Resolve services, bind resources, build handlers there — |
| 2606 | * one-shot I/O that caches a plain value (e.g. fetching a secret for a |
| 2607 | * client) is fine, but nothing disposable: the build scope is never closed |
| 2608 | * (workerd has no isolate-teardown hook), so a finalizer added in the |
| 2609 | * constructor never runs, and I/O-backed objects (sockets, response bodies) are |
| 2610 | * pinned to the request that created them. Anything that needs cleanup |
| 2611 | * belongs in a handler, where `Effect.addFinalizer` attaches to the |
| 2612 | * per-event scope. |
| 2613 | * |
| 2614 | * **Example:** Post-response cleanup with a scope finalizer |
| 2615 | * ```typescript |
| 2616 | * return { |
| 2617 | * fetch: Effect.gen(function* () { |
| 2618 | * // runs after this response is sent, kept alive by waitUntil |
| 2619 | * yield* Effect.addFinalizer(() => flushMetrics().pipe(Effect.ignore)); |
| 2620 | * return HttpServerResponse.text("ok"); |
| 2621 | * }), |
| 2622 | * }; |
| 2623 | * ``` |
| 2624 | * |
| 2625 | * **Example:** Background work with waitUntil |
| 2626 | * ```typescript |
| 2627 | * return { |
| 2628 | * fetch: Effect.gen(function* () { |
| 2629 | * // respond now; the audit write completes in the background |
| 2630 | * yield* Cloudflare.waitUntil(writeAuditLog(event)); |
| 2631 | * return HttpServerResponse.text("accepted", { status: 202 }); |
| 2632 | * }), |
| 2633 | * }; |
| 2634 | * ``` |
| 2635 | * |
| 2636 | * ### Self Entrypoints & ctx.props |
| 2637 | * `WorkerExecutionContext.props` reads the `ctx.props` the caller attached |
| 2638 | * to its service binding or stub — an empty object for an external request. |
| 2639 | * `ctx.exports.default({ props })` mints a stub to this Worker's own handlers |
| 2640 | * that delivers those props (`ctx.exports.Name(...)` for a named entrypoint), |
| 2641 | * as workerd's `ctx.exports` does; a Durable Object mints the same stub from |
| 2642 | * `DurableObjectState.exports`. The |
| 2643 | * stub is a `Cloudflare.Fetcher`, so it plugs into APIs that route traffic to |
| 2644 | * a Worker entrypoint, and its `raw` is the native `Fetcher`. |
| 2645 | * |
| 2646 | * **Example:** Read ctx.props in a handler |
| 2647 | * ```typescript |
| 2648 | * // Construction |
| 2649 | * const ctx = yield* Cloudflare.WorkerExecutionContext; |
| 2650 | * |
| 2651 | * return { |
| 2652 | * fetch: Effect.gen(function* () { |
| 2653 | * const { tenant } = yield* ctx.props; |
| 2654 | * return HttpServerResponse.text(`tenant: ${String(tenant ?? "none")}`); |
| 2655 | * }), |
| 2656 | * }; |
| 2657 | * ``` |
| 2658 | * |
| 2659 | * **Example:** Route a container's egress into this Worker with props |
| 2660 | * ```typescript |
| 2661 | * export default class Agent extends Cloudflare.DurableObject<Agent>()( |
| 2662 | * "Agents", |
| 2663 | * Effect.gen(function* () { |
| 2664 | * const ctx = yield* Cloudflare.DurableObjectState; |
| 2665 | * const sandbox = yield* Sandbox; |
| 2666 | * |
| 2667 | * return Effect.gen(function* () { |
| 2668 | * return { |
| 2669 | * run: (tenant: string) => |
| 2670 | * Effect.gen(function* () { |
| 2671 | * yield* sandbox.start(); |
| 2672 | * // the Worker's fetch handler sees ctx.props = { tenant } |
| 2673 | * const egress = yield* ctx.exports.default({ props: { tenant } }); |
| 2674 | * yield* sandbox.interceptOutboundHttps("api.example.com", egress); |
| 2675 | * }), |
| 2676 | * }; |
| 2677 | * }); |
| 2678 | * }), |
| 2679 | * ) {} |
| 2680 | * ``` |
| 2681 | * |
| 2682 | * ### Cross-Stack References |
| 2683 | * `Cloudflare.Worker.ref` references a Worker that another stack or stage |
| 2684 | * deploys. Pass the Worker's declaration instead of its logical id to keep |
| 2685 | * its type, so a service binding to it stays typed. Only the declaration's |
| 2686 | * logical id is read; the referencing stack does not deploy it. |
| 2687 | * |
| 2688 | * **Example:** Bind a Worker owned by another stack |
| 2689 | * ```typescript |
| 2690 | * // Construction |
| 2691 | * const greeter = yield* Cloudflare.Workers.bindWorker( |
| 2692 | * Cloudflare.Worker.ref(Greeter, { stack: "Greeter" }), |
| 2693 | * ); |
| 2694 | * |
| 2695 | * return { |
| 2696 | * fetch: Effect.gen(function* () { |
| 2697 | * return HttpServerResponse.text(yield* greeter.greet("world")); |
| 2698 | * }), |
| 2699 | * }; |
| 2700 | * ``` |
| 2701 | * |
| 2702 | * ### R2 Bucket |
| 2703 | * Bind an R2 bucket in the Construction phase with `Cloudflare.R2.ReadWriteBucket`. |
| 2704 | * The returned handle exposes `get`, `put`, `delete`, and `list` |
| 2705 | * methods you can call in your runtime handlers. |
| 2706 | * |
| 2707 | * **Example:** Binding and using R2 |
| 2708 | * ```typescript |
| 2709 | * // Construction |
| 2710 | * const bucket = yield* Cloudflare.R2.ReadWriteBucket(MyBucket); |
| 2711 | * |
| 2712 | * return { |
| 2713 | * fetch: Effect.gen(function* () { |
| 2714 | * const request = yield* HttpServerRequest; |
| 2715 | * const key = request.url.split("/").pop()!; |
| 2716 | * |
| 2717 | * if (request.method === "GET") { |
| 2718 | * const object = yield* bucket.get(key); |
| 2719 | * return object |
| 2720 | * ? HttpServerResponse.text(yield* object.text()) |
| 2721 | * : HttpServerResponse.empty({ status: 404 }); |
| 2722 | * } |
| 2723 | * |
| 2724 | * yield* bucket.put(key, request.stream); |
| 2725 | * return HttpServerResponse.empty({ status: 201 }); |
| 2726 | * }), |
| 2727 | * }; |
| 2728 | * ``` |
| 2729 | * |
| 2730 | * ### KV Namespace |
| 2731 | * Bind a KV namespace with `Cloudflare.KV.ReadWriteNamespace`. KV provides |
| 2732 | * eventually-consistent, low-latency key-value reads replicated |
| 2733 | * globally across Cloudflare's edge. |
| 2734 | * |
| 2735 | * **Example:** Binding and using KV |
| 2736 | * ```typescript |
| 2737 | * // Construction |
| 2738 | * const kv = yield* Cloudflare.KV.ReadWriteNamespace(MyKV); |
| 2739 | * |
| 2740 | * return { |
| 2741 | * fetch: Effect.gen(function* () { |
| 2742 | * const value = yield* kv.get("my-key"); |
| 2743 | * return HttpServerResponse.text(value ?? "not found"); |
| 2744 | * }), |
| 2745 | * }; |
| 2746 | * ``` |
| 2747 | * |
| 2748 | * ### D1 Database |
| 2749 | * Bind a D1 database with `Cloudflare.D1.QueryDatabase`. D1 is a |
| 2750 | * serverless SQLite database — use `prepare` to build parameterized |
| 2751 | * queries and `all`, `first`, or `run` to execute them. |
| 2752 | * |
| 2753 | * **Example:** Binding and querying D1 |
| 2754 | * ```typescript |
| 2755 | * // Construction |
| 2756 | * const db = yield* Cloudflare.D1.QueryDatabase(MyDatabase); |
| 2757 | * |
| 2758 | * return { |
| 2759 | * fetch: Effect.gen(function* () { |
| 2760 | * const results = yield* db |
| 2761 | * .prepare("SELECT * FROM users WHERE id = ?") |
| 2762 | * .bind(userId) |
| 2763 | * .all(); |
| 2764 | * return yield* HttpServerResponse.json(results); |
| 2765 | * }), |
| 2766 | * }; |
| 2767 | * ``` |
| 2768 | * |
| 2769 | * ### Durable Objects |
| 2770 | * Yield a `DurableObject` class in the Construction phase to get a |
| 2771 | * namespace handle. Call `getByName` or `getById` to get a typed RPC |
| 2772 | * stub, then call its methods from your runtime handlers. |
| 2773 | * |
| 2774 | * **Example:** Using a Durable Object |
| 2775 | * ```typescript |
| 2776 | * // Construction |
| 2777 | * const counters = yield* Counter; |
| 2778 | * |
| 2779 | * return { |
| 2780 | * fetch: Effect.gen(function* () { |
| 2781 | * const counter = counters.getByName("user-123"); |
| 2782 | * const value = yield* counter.increment(); |
| 2783 | * return HttpServerResponse.text(String(value)); |
| 2784 | * }), |
| 2785 | * }; |
| 2786 | * ``` |
| 2787 | * |
| 2788 | * By default a deploy lets an active Durable Object keep running its |
| 2789 | * current code for up to 5 minutes while it waits to hibernate. |
| 2790 | * `codeUpdateStrategy` changes how long, or applies the new code at once. |
| 2791 | * See [Code updates](/cloudflare/compute/code-updates). |
| 2792 | * |
| 2793 | * **Example:** Shorter deferral for Durable Object code updates |
| 2794 | * ```typescript |
| 2795 | * { |
| 2796 | * main: import.meta.url, |
| 2797 | * codeUpdateStrategy: { mode: "deferred", maxDelay: "1 minute" }, |
| 2798 | * } |
| 2799 | * ``` |
| 2800 | * |
| 2801 | * **Example:** Apply Durable Object code updates immediately |
| 2802 | * ```typescript |
| 2803 | * { |
| 2804 | * main: import.meta.url, |
| 2805 | * codeUpdateStrategy: { mode: "immediate" }, |
| 2806 | * } |
| 2807 | * ``` |
| 2808 | * |
| 2809 | * ### Containers |
| 2810 | * Containers run long-lived processes alongside Durable Objects. |
| 2811 | * `yield* Sandbox` binds the container to the DO and returns its handle |
| 2812 | * without starting it. Call `start()` (a no-op once running) before using |
| 2813 | * its typed methods or `getTcpPort`. |
| 2814 | * |
| 2815 | * **Example:** Running a Container from a Durable Object |
| 2816 | * ```typescript |
| 2817 | * export default class Agent extends Cloudflare.DurableObject<Agent>()( |
| 2818 | * "Agents", |
| 2819 | * Effect.gen(function* () { |
| 2820 | * const sandbox = yield* Sandbox; |
| 2821 | * |
| 2822 | * return Effect.gen(function* () { |
| 2823 | * const start = sandbox.start({ enableInternet: true }); |
| 2824 | * return { |
| 2825 | * shell: (cmd: string) => start.pipe(Effect.andThen(sandbox.shell(cmd))), |
| 2826 | * health: () => |
| 2827 | * Effect.gen(function* () { |
| 2828 | * yield* start; |
| 2829 | * const { fetch } = yield* sandbox.getTcpPort(3000); |
| 2830 | * const res = yield* fetch( |
| 2831 | * HttpClientRequest.get("http://container/health"), |
| 2832 | * ); |
| 2833 | * return yield* res.text; |
| 2834 | * }), |
| 2835 | * }; |
| 2836 | * }); |
| 2837 | * }), |
| 2838 | * ) {} |
| 2839 | * ``` |
| 2840 | * |
| 2841 | * ### Dynamic Workers |
| 2842 | * `WorkerLoader` lets you spin up ephemeral Workers at runtime |
| 2843 | * from inline JavaScript modules. This is useful for sandboxing |
| 2844 | * user-provided code or running untrusted scripts in isolation. |
| 2845 | * |
| 2846 | * **Example:** Loading a dynamic Worker |
| 2847 | * ```typescript |
| 2848 | * // Construction |
| 2849 | * const loader = yield* Cloudflare.WorkerLoader("Loader"); |
| 2850 | * |
| 2851 | * return { |
| 2852 | * fetch: Effect.gen(function* () { |
| 2853 | * const worker = yield* loader.load({ |
| 2854 | * compatibilityDate: "2026-08-31", |
| 2855 | * mainModule: "worker.js", |
| 2856 | * modules: { |
| 2857 | * "worker.js": `export default { |
| 2858 | * async fetch(req) { return new Response("sandboxed"); } |
| 2859 | * }`, |
| 2860 | * }, |
| 2861 | * }); |
| 2862 | * |
| 2863 | * const res = yield* worker.fetch( |
| 2864 | * HttpClientRequest.get("https://worker/"), |
| 2865 | * ); |
| 2866 | * return HttpServerResponse.fromClientResponse(res); |
| 2867 | * }), |
| 2868 | * }; |
| 2869 | * ``` |
| 2870 | * |
| 2871 | * @resource |
| 2872 | * @product Workers |
| 2873 | * @category Workers & Compute |
| 2874 | */ |
| 2875 | export const Worker: ResourceClassLike<Worker> & { |
| 2876 | /** |
| 2877 | * Reference a deployed Worker — in the current stack/stage by default, or |
| 2878 | * in another via `options`. Pass the Worker's declaration instead of its |
| 2879 | * logical id to keep its type, including its RPC methods, for service |
| 2880 | * bindings from another stack. |
| 2881 | */ |
| 2882 | ref: WorkerRef; |
| 2883 | } & Effect.Effect<Worker & WorkerRuntimeContext & RuntimeContext, never, Worker> & { |
| 2884 | <Self, Shape extends WorkerShape, Deps = never>(): { |
| 2885 | <const Id extends string>( |
| 2886 | id: Id, |
| 2887 | ): Effect.Effect< |
| 2888 | Worker & Rpc<Self> & Dependencies<Deps>, |
| 2889 | never, |
| 2890 | Self | Extract<Deps, Container.Application<any>> | Providers |
| 2891 | > & |
| 2892 | Named<Id> & |
| 2893 | PlatformIdentity<Id> & { |
| 2894 | new (_: never): MakeShape<Shape, WorkerShape> & Named<Id> & Tag<WorkerTypeId>; |
| 2895 | of(shape: Shape & WorkerShape): MakeShape<Shape, WorkerShape>; |
| 2896 | make<PropsReq = never, InitReq = never>( |
| 2897 | props: |
| 2898 | | InputProps<WorkerProps> |
| 2899 | | Effect.Effect<InputProps<WorkerProps>, ConfigError, PropsReq>, |
| 2900 | impl: Effect.Effect<Shape, ConfigError, InitReq>, |
| 2901 | ): Layer.Layer< |
| 2902 | Self, |
| 2903 | never, |
| 2904 | | Extract<Deps, Container.Application<any>> |
| 2905 | | Providers |
| 2906 | | Exclude<PropsReq | InitReq, Self | WorkerServices | Tag<WorkerTypeId>> |
| 2907 | >; |
| 2908 | }; |
| 2909 | }; |
| 2910 | <Self>(): { |
| 2911 | < |
| 2912 | const Id extends string, |
| 2913 | Shape extends WorkerShape, |
| 2914 | Req extends WorkerServices | Container.Application<any> | PlatformServices | Tag, |
| 2915 | PropsReq = never, |
| 2916 | >( |
| 2917 | id: Id, |
| 2918 | props: |
| 2919 | | InputProps<WorkerProps> |
| 2920 | | Effect.Effect<InputProps<WorkerProps>, ConfigError, PropsReq>, |
| 2921 | impl: Effect.Effect<Shape, ConfigError, Req>, |
| 2922 | ): Effect.Effect< |
| 2923 | Worker & Rpc<Self>, |
| 2924 | never, |
| 2925 | Extract<Req, Container.Application<any>> | Providers | PropsReq |
| 2926 | > & |
| 2927 | Named<Id> & |
| 2928 | PlatformIdentity<Id> & { |
| 2929 | new (): MakeShape<Shape, WorkerShape> & Named<Id> & Tag<WorkerTypeId>; |
| 2930 | }; |
| 2931 | /** |
| 2932 | * Class form without an implementation — an external Worker (a plain |
| 2933 | * bundled `main`, a raw `script`, or an assets-only Worker with no |
| 2934 | * script at all): |
| 2935 | * |
| 2936 | * ```typescript |
| 2937 | * export class Site extends Cloudflare.Worker<Site>()("Site", { |
| 2938 | * assets: { directory: "./public" }, |
| 2939 | * }) {} |
| 2940 | * ``` |
| 2941 | */ |
| 2942 | < |
| 2943 | const Id extends string, |
| 2944 | const Bindings extends WorkerBindingProps = {}, |
| 2945 | const Assets extends WorkerAssetsConfig | undefined = undefined, |
| 2946 | Req = never, |
| 2947 | >( |
| 2948 | id: Id, |
| 2949 | props: |
| 2950 | | InputProps<WorkerProps<Bindings, Assets>> |
| 2951 | | Effect.Effect<InputProps<WorkerProps<Bindings, Assets>>, ConfigError, Req>, |
| 2952 | ): Effect.Effect< |
| 2953 | ExternalWorker<NormalizedBindings<Bindings, Assets>> & Rpc<{}>, |
| 2954 | never, |
| 2955 | Req | Providers |
| 2956 | > & |
| 2957 | Named<Id> & |
| 2958 | PlatformIdentity<Id> & { |
| 2959 | new (): Named<Id> & |
| 2960 | Tag<WorkerTypeId> & { |
| 2961 | /** @internal phantom */ |
| 2962 | readonly "~alchemy/WorkerEnv": NormalizedBindings<Bindings, Assets>; |
| 2963 | }; |
| 2964 | }; |
| 2965 | }; |
| 2966 | < |
| 2967 | const Bindings extends WorkerBindingProps = {}, |
| 2968 | const Assets extends WorkerAssetsConfig | undefined = undefined, |
| 2969 | Req = never, |
| 2970 | const Id extends string = string, |
| 2971 | >( |
| 2972 | id: Id, |
| 2973 | props: |
| 2974 | | InputProps<WorkerProps<Bindings, Assets>> |
| 2975 | | Effect.Effect<InputProps<WorkerProps<Bindings, Assets>>, ConfigError, Req>, |
| 2976 | ): Effect.Effect< |
| 2977 | ExternalWorker<{ |
| 2978 | [binding in keyof NormalizedBindings<Bindings, Assets>]: NormalizedBindings< |
| 2979 | Bindings, |
| 2980 | Assets |
| 2981 | >[binding]; |
| 2982 | }> & |
| 2983 | Rpc<{}>, |
| 2984 | never, |
| 2985 | Req | Providers |
| 2986 | > & |
| 2987 | PlatformIdentity<Id>; |
| 2988 | < |
| 2989 | const Id extends string, |
| 2990 | Shape extends WorkerShape, |
| 2991 | Req extends WorkerServices | Container.Application<any> | PlatformServices, |
| 2992 | >( |
| 2993 | id: Id, |
| 2994 | props: InputProps<WorkerProps> | Effect.Effect<InputProps<WorkerProps>, ConfigError>, |
| 2995 | impl: Effect.Effect<Shape, ConfigError, Req>, |
| 2996 | ): Effect.Effect< |
| 2997 | Worker & Rpc<Shape>, |
| 2998 | never, |
| 2999 | Extract<Req, Container.Application<any>> | Providers |
| 3000 | > & |
| 3001 | Named<Id> & |
| 3002 | PlatformIdentity<Id>; |
| 3003 | /** |
| 3004 | * The Worker's own public URL, injected as a binding on that same Worker. |
| 3005 | * Declare it on `env` (`env: { VITE_PUBLIC_URL: Worker.URL }`) or |
| 3006 | * `yield*` it inside an Effect-native Worker to obtain a deferred |
| 3007 | * accessor. See {@link URLEffect}. |
| 3008 | */ |
| 3009 | readonly URL: URLEffect; |
| 3010 | } = withDeclarationRef( |
| 3011 | Platform( |
| 3012 | WorkerTypeId, |
| 3013 | { |
| 3014 | // WorkerAsyncBindings imports isWorker; defer access until module initialization completes. |
| 3015 | // `props` is `undefined` for a bare tag whose `.make` Layer has not built yet. |
| 3016 | onCreate: (resource, props) => bindWorkerAsyncBindings(resource as Worker, props ?? {}), |
| 3017 | createRuntimeContext: (id) => makeWorkerRuntimeContext(id), |
| 3018 | // Normalize `main` relative to the cwd, then let `domain.dns` naming a |
| 3019 | // non-Cloudflare DNS host compose Cloudflare for SaaS custom hostnames + |
| 3020 | // records and rewrite `domain` into routes. |
| 3021 | transformProps: (id, props) => |
| 3022 | transformWorkerDomainProps( |
| 3023 | id, |
| 3024 | globalThis.__ALCHEMY_RUNTIME__ || typeof props?.main !== "string" |
| 3025 | ? props |
| 3026 | : { ...props, main: relativeWorkerMain(props.main, process.cwd()) }, |
| 3027 | ), |
| 3028 | }, |
| 3029 | { URL }, |
| 3030 | ), |
| 3031 | ); |
| 3032 | |
| 3033 | /** |
| 3034 | * `main` as a path relative to `cwd` when it points inside `cwd`. State keeps |
| 3035 | * the Worker's props and `alchemy drift` rebuilds the bundle from them, so an |
| 3036 | * absolute `main` (such as `import.meta.url`) fails once the checkout that |
| 3037 | * deployed it moves or is removed. Paths outside `cwd` are kept as given. |
| 3038 | * |
| 3039 | * @internal exported for unit testing. |
| 3040 | */ |
| 3041 | export const relativeWorkerMain = (main: string, cwd: string): string => { |
| 3042 | const file = main.startsWith("file:") |
| 3043 | ? decodeURIComponent(new globalThis.URL(main).pathname) |
| 3044 | : main; |
| 3045 | return path.isAbsolute(file) && isPathWithin(cwd, file, cwd) ? path.relative(cwd, file) : main; |
| 3046 | }; |