sailfork / t3code-github / .repos/ alchemy-effect/ packages/ cloudflare/ src/ Workers/ Worker.ts

import * as workers from "@distilled.cloud/cloudflare/workers";
import { type MemoOptions } from "alchemy/Command/Memo";
import type { Dependencies } from "alchemy/Dependencies";
import type { DnsConfig } from "alchemy/DNS/Adapter";
import type { InputProps } from "alchemy/Input";
import type { Named, Tag } from "alchemy/Named";
import type * as Output from "alchemy/Output";
import {
  Platform,
  type Main,
  type MainRpc,
  type MakeShape,
  type PlatformIdentity,
  type PlatformProps,
  type PlatformServices,
} from "alchemy/Platform";
import {
  isResourceOfType,
  Resource,
  type ResourceClass,
  type ResourceClassLike,
} from "alchemy/Resource";
import type { Rpc } from "alchemy/Rpc";
import type { RuntimeContext } from "alchemy/RuntimeContext";
import type { Self as SelfService } from "alchemy/Self";
import { isPathWithin } from "alchemy/Util/isPathWithin";
import type { WebhookHost } from "alchemy/WebhookHost";
import type { ConfigError } from "effect/Config";
import type * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import type * as Layer from "effect/Layer";
import * as Redacted from "effect/Redacted";
import path from "pathe";
import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
import type { Container } from "../Containers/Container.ts";
import type { DevContainerImage } from "../Containers/ContainerApplication.ts";
import type { DomainClass } from "../Domain/Version.ts";
import type { DevOrigin } from "../Hyperdrive/Connection.ts";
import type { Providers } from "../Providers.ts";
import type { DispatchNamespace } from "../WorkersForPlatforms/DispatchNamespace.ts";
import type { WorkflowBinding, WorkflowLike } from "../Workflows/Workflow.ts";
import type { Reference as ZoneReference } from "../Zone/lookup.ts";
import { type Assets, type AssetsConfig, type AssetsProps } from "./Assets.ts";
import { Request } from "./Request.ts";
import type { ModuleRule } from "./Sources/Prebuilt.ts";
import type { WorkerBuildOptions } from "./Sources/Rolldown.ts";
import type { WorkerAccessConfig, WorkerAccessIdentity } from "./WorkerAccess.ts";
import { bindWorkerAsyncBindings } from "./WorkerAsyncBindings.ts";
import type { WorkerBinding, WorkerBindingResource } from "./WorkerBinding.ts";
import { transformWorkerDomainProps } from "./WorkerDomainDns.ts";
import { WorkerEnvironment, WorkerTypeId } from "./WorkerRuntime.ts";
import {
  makeWorkerRuntimeContext,
  type WorkerExport,
  type WorkerRuntimeContext,
} from "./WorkerRuntimeContext.ts";

export * from "./WorkerRuntime.ts";
export { WorkerDomainDnsError } from "./WorkerDomainDns.ts";

export const isWorker = <T>(value: T): value is T & Worker => isResourceOfType(value, WorkerTypeId);

/**
 * Assets configuration that includes a pre-computed hash.
 * When hash is provided, it's used directly for diffing instead of computing from directory contents.
 * This is useful when integrating with Build resources that produce a deterministic hash.
 */
export interface AssetsWithHash extends AssetsProps {
  /**
   * Pre-computed hash of the assets. When provided, this hash is used for diffing
   * to determine if the worker needs to be redeployed.
   */
  hash: string;
}

export interface WorkerObservability extends Exclude<
  workers.PutScriptRequest["metadata"]["observability"],
  undefined
> {}

export interface WorkerLimits extends Exclude<
  workers.PutScriptRequest["metadata"]["limits"],
  undefined
> {}

export interface WorkerCache extends Exclude<
  workers.PutScriptRequest["metadata"]["cacheOptions"],
  undefined
> {}

/**
 * Per-entrypoint settings for one of a Worker's exports, keyed in
 * {@link WorkerProps.entrypoints} by export name.
 */
export interface WorkerEntrypointSettings {
  /**
   * Workers Cache override for this entrypoint. `enabled` replaces the
   * Worker-wide `cache.enabled` for calls into this entrypoint only;
   * `crossVersionCache` stays Worker-wide.
   */
  cache?: {
    /** Whether Workers Cache is checked before invoking this entrypoint. */
    enabled: boolean;
  };
}

export type WorkerPlacement = Exclude<workers.PutScriptRequest["metadata"]["placement"], undefined>;

/**
 * How a deploy rolls new code out to the Worker's running Durable Objects.
 *
 * - `{ mode: "deferred" }` — an active object keeps running its current code
 *   while it waits to hibernate, for up to `maxDelay`, so in-flight work can
 *   finish. Hibernation API WebSockets stay connected when the object picks
 *   up the new code after hibernating.
 * - `{ mode: "immediate" }` — every object resets onto the new code as soon
 *   as the deploy lands.
 *
 * Deferral is best effort: an object can still reset before `maxDelay`
 * elapses, e.g. during a Cloudflare runtime update.
 */
export type WorkerCodeUpdateStrategy =
  | { mode: "immediate" }
  | {
      mode: "deferred";
      /**
       * The longest an active Durable Object may keep running old code before
       * it is forced onto the new code — e.g. `"1 minute"`, `"30 seconds"`, or
       * a `Duration`. Between 0 and 24 hours, millisecond precision.
       * @default "5 minutes"
       */
      maxDelay?: Duration.Input;
    };

export type WorkerServices =
  | Worker
  | WebhookHost
  | Request
  | WorkerEnvironment
  | CloudflareEnvironment
  | Container.Application<any>
  | SelfService;

export type WorkerShape<Req = never> = Main<WorkerServices | Req> & MainRpc<WorkerServices | Req>;

export type WorkerEnv = Record<
  string,
  | string
  | number
  | boolean
  | null
  | readonly unknown[]
  | { readonly [key: string]: unknown }
  | Redacted.Redacted<string>
>;

export type WorkerBindingProps = {
  [bindingName in string]: WorkerBindingResource | Effect.Effect<WorkerBindingResource, any, any>;
};

export type NormalizedBindings<
  Bindings extends WorkerBindingProps = {},
  AssetsConfig extends WorkerAssetsConfig | undefined = undefined,
> = {
  // Containers are declarations and Outputs stay deferred at declaration time.
  [B in keyof Bindings]: Bindings[B] extends Container.Decl.Any | Output.Output<any, any>
    ? Bindings[B]
    : Bindings[B] extends Effect.Effect<infer T extends WorkerBindingResource, any, any>
      ? T
      : Extract<Bindings[B], WorkerBindingResource>;
} & (undefined extends AssetsConfig ? {} : { ASSETS: Assets });

/**
 * An external Worker's declared `env` as exposed on its declaration
 * (`worker.env`): every entry is the binding value as declared (with
 * Effect-valued entries resolved), except a Workflow binding, which surfaces
 * as a {@link WorkflowBinding} carrying the Workflow's physical name as an
 * `Output` of the current deploy.
 */
export type WorkerEnvBindings<Bindings> = {
  readonly [B in keyof Bindings]: Bindings[B] extends WorkflowLike<infer Params>
    ? WorkflowBinding<Params>
    : Bindings[B];
};

export type WorkerAssetsConfig =
  | string
  | (AssetsConfig & { directory?: never })
  | AssetsProps
  | AssetsWithHash;

/**
 * Fine-grained control over the Worker's `workers.dev` surface. The two
 * toggles are independent on the Cloudflare API.
 */
export interface WorkersDevConfig {
  /**
   * Serve the Worker at its stable `workers.dev` URL
   * (`https://<worker-name>.<account-subdomain>.workers.dev`).
   * @default true
   */
  enabled?: boolean;
  /**
   * Enable version preview URLs — a distinct
   * `https://<version-prefix>-<worker-name>.<account-subdomain>.workers.dev`
   * URL per uploaded version, plus stable aliased preview URLs
   * (`https://<alias>-...`) for versions uploaded with an alias.
   *
   * When previews are enabled but {@link enabled} is `false`, the current
   * version's preview URL becomes the Worker's primary `url` output.
   * @default true
   */
  previewsEnabled?: boolean;
}

/**
 * The Worker's custom-domain configuration: one canonical hostname, plus
 * optional aliases that also serve the Worker and redirect hostnames that
 * 301 to the canonical name.
 */
export interface WorkerDomainConfig {
  /**
   * The canonical hostname (e.g. `"example.com"`). Attached to the Worker
   * as a Cloudflare custom domain — DNS record and edge certificate are
   * managed automatically. The Cloudflare zone is inferred from the
   * hostname unless {@link zoneId}, {@link zone}, or {@link zoneName} is
   * set. The zone must already exist in the account.
   *
   * When set, `https://<name>` is the Worker's primary `url` output.
   */
  name: string;
  /**
   * Additional hostnames that serve the Worker (e.g. `"www.example.com"`,
   * `"api.example.com"`). Each is attached as its own custom domain.
   * Order matters: aliases follow `name` in the `urls` output.
   */
  aliases?: string[];
  /**
   * Hostnames that permanently redirect (HTTP 301, path and query
   * preserved) to {@link name} — e.g. `"old.example.com"`. Each is
   * attached as a custom domain (for DNS + TLS) with a redirect rule in
   * the zone's `http_request_dynamic_redirect` phase, which runs before
   * the Worker — redirected requests never invoke it. Redirect hostnames
   * serve no content, so they appear in the `domain` output but never in
   * `urls`.
   */
  redirects?: string[];
  /**
   * Cloudflare zone ID for every hostname in this config. Equivalent to
   * Wrangler's `zone_id`. Wins over {@link zone} / {@link zoneName}.
   * When omitted, each hostname's zone is looked up by name
   * (`GET /zones?name=`), not by listing the account's first page of zones.
   */
  zoneId?: string;
  /**
   * Cloudflare zone name, e.g. `"example.com"`. Equivalent to Wrangler's
   * `zone_name`.
   */
  zoneName?: string;
  /**
   * Zone reference — a zone ID, zone name, or `{ zoneId, name? }` object.
   * Alternative to {@link zoneId} / {@link zoneName}.
   */
  zone?: ZoneReference;
  /**
   * Opt into custom-domain Worker Previews (private beta). When `true`,
   * Previews of this Worker are served at `<preview-name>.<name>` (and a
   * pinned `<deployment-id>-<preview-name>.<name>` per deploy). Cloudflare
   * provisions a wildcard DNS record and certificate. Equivalent to
   * Wrangler's `previews_enabled` on a custom-domain route.
   *
   * Unset, the field is not sent to Cloudflare — existing custom-domain
   * attaches are unchanged. This is a **parent** setting: enable it on
   * the production Worker, not on the Preview Worker. A dedicated Preview
   * hostname (`previews.example.com`) avoids colliding with existing
   * subdomains.
   *
   * @default false
   */
  previews?: boolean;
  /**
   * The DNS host that publishes this domain's records. Omit it (or pass
   * `Cloudflare.DNS.Adapter()`) for hostnames in a Cloudflare zone of the
   * account: they attach as native custom domains, exactly as without
   * `dns`.
   *
   * Any other adapter (`AWS.Route53.Adapter()`, `Hetzner.DNS.Adapter()`)
   * serves the hostnames through
   * [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/start/advanced-settings/worker-as-origin/):
   * {@link name} and each alias become a
   * `Cloudflare.CustomHostname.CustomHostname` on the SaaS zone
   * ({@link zoneId} / {@link zone} / {@link zoneName}, required), the
   * DNS host publishes their ownership and certificate-validation TXT
   * records plus a `CNAME` to {@link cnameTarget}, and the Worker gets a
   * `<hostname>/*` route on the SaaS zone instead of a custom domain.
   * {@link redirects} and {@link previews} are not supported on this path,
   * and the Worker's `url` stays its `workers.dev` URL. Declare the SaaS
   * zone's `Cloudflare.CustomHostname.FallbackOrigin` once yourself —
   * several Workers can share one SaaS zone.
   *
   * See [DNS Adapters](/infrastructure-as-code/dns-adapters).
   */
  dns?: DnsConfig;
  /**
   * Hostname in the SaaS zone that custom hostnames CNAME to, typically
   * the zone's fallback origin (`FallbackOrigin`'s `origin`). Required
   * when {@link dns} names a DNS host other than Cloudflare; unused
   * otherwise.
   */
  cnameTarget?: string;
}

export interface WorkerRouteConfig {
  /**
   * URL pattern to match incoming requests against, e.g.
   * `"subdomain.example.com/*"` or `"example.com/api/*"`.
   */
  pattern: string;
  /**
   * Cloudflare zone ID. Equivalent to Wrangler's `zone_id`.
   */
  zoneId?: string;
  /**
   * Cloudflare zone name, e.g. `"example.com"`. Equivalent to Wrangler's
   * `zone_name`.
   */
  zoneName?: string;
  /**
   * Zone reference — a zone ID, zone name, or `{ zoneId, name? }` object.
   * Alternative to `zoneId` / `zoneName`.
   */
  zone?: ZoneReference;
}

/**
 * Version-affinity configuration — keeps each user on one version for the
 * duration of a gradual rollout.
 *
 * Percentages route each request independently, so one user can bounce
 * between versions mid-rollout. Cloudflare pins a request to a version
 * deterministically when it carries a `Cloudflare-Workers-Version-Key`
 * header: the key is hashed and assigned a version from the current
 * percentages, so equal keys always land on the same version, and pinned
 * users only move forward as percentages rise.
 *
 * Setting `affinity` provisions that header as infrastructure: a `rewrite`
 * Transform Rule in the `http_request_late_transform` phase of every zone
 * the Worker serves on (custom domains and zone routes), scoped to the
 * Worker's hostnames, filling the header from the configured source. The
 * rule is updated in place as the config changes and removed when
 * `affinity` is removed or the Worker is destroyed; other rules in the
 * zone's shared entrypoint are left untouched.
 *
 * Exactly one of {@link cookie}, {@link header}, or {@link key} may be
 * set; {@link ip} combines with `cookie`/`header` as a fallback or stands
 * alone as the sole source.
 *
 * Transform Rules only see **zone traffic** — the Worker must have a
 * `domain` or `routes` (or, with `version.parent`, the parent must).
 * A workers.dev-only Worker fails the deploy with
 * `WorkerVersionConfigError`; on the bare workers.dev URL clients must
 * send the header themselves.
 */
export interface WorkerVersionAffinity {
  /**
   * Pin by the value of this request cookie (e.g. a session id). Requests
   * without the cookie fall back to {@link ip} when set, otherwise they
   * route independently by percentage.
   */
  cookie?: string;
  /**
   * Pin by the value of this request header (e.g. a tenant or user id
   * your edge already stamps, or a stable auth claim forwarded as a
   * header). Requests without the header fall back to {@link ip} when
   * set, otherwise they route independently by percentage.
   */
  header?: string;
  /**
   * Pin by client IP. On its own (`{ ip: true }`) every request is keyed
   * by `ip.src`; combined with {@link cookie} or {@link header} it is the
   * fallback for requests missing the primary source (e.g. sticky by
   * session cookie, falling back to sticky IP before the cookie is set).
   */
  ip?: boolean;
  /**
   * Escape hatch: a raw [Rules-language](https://developers.cloudflare.com/ruleset-engine/rules-language/)
   * expression that computes the version key — e.g. a JWT claim via API
   * Shield's `http.request.jwt.claims`, or any composite of request
   * fields. Applied to every request on the Worker's hostnames; cannot be
   * combined with the other sources.
   */
  key?: string;
}

/**
 * Versioning configuration for a Worker deploy — controls Worker
 * [versions and gradual deployments](https://developers.cloudflare.com/workers/configuration/versions-and-deployments/).
 *
 * Two modes, selected by {@link parent}:
 *
 * - **Version worker** (`parent` set): instead of creating its own script,
 *   this Worker uploads an immutable *version* to the referenced parent
 *   Worker's script. With `traffic: 0` (the default) the parent's live
 *   deployment is untouched and the version is reachable only at its
 *   preview URL (`<version-prefix>-<name>.<subdomain>.workers.dev`) —
 *   the PR-preview use case. With `traffic > 0` the version becomes a
 *   canary taking that percentage of the parent's traffic.
 * - **Gradual rollout** (`parent` omitted): when this Worker deploys
 *   itself, the newly uploaded version receives {@link traffic} percent
 *   and the currently-live version keeps the remainder, instead of the
 *   default 100% cutover.
 *
 * A gradual rollout carries only what a version can: code, static assets,
 * bindings, compatibility settings, and cache configuration. A deploy that
 * creates, renames, deletes or moves Durable Object classes must go out at
 * 100% (class lifecycle changes cannot ride a rollout), and script-level settings
 * (tags, observability, limits, placement, logpush) keep their live
 * values until the next full deploy.
 */
export interface WorkerVersionOptions {
  /**
   * The Worker that owns the script this version is uploaded to. Accepts a
   * Worker reference — typically `yield* Cloudflare.Worker.ref(id, { stage,
   * stack })` for a Worker deployed in another stage/stack, or a
   * locally-declared Worker — or a literal script name as an escape hatch.
   *
   * When set, this resource does not create a script of its own: it
   * uploads a version (code + static assets + bindings + compatibility
   * settings) to the parent's script. Script-level settings apply immediately
   * to *all* versions of the parent, so they cannot be set on a version worker —
   * `name`, `namespace`, `crons`, `domain`, `routes`, `tags`,
   * `logpush`, `observability`, `placement`, `limits`, and `subdomain` are
   * rejected, as are locally-hosted Durable Object or Workflow classes
   * (their migrations would mutate the parent).
   *
   * Changing the parent replaces the resource (a version belongs to
   * exactly one script).
   */
  parent?: string | Worker;
  /**
   * Percentage of traffic (0–100) the newly uploaded version receives; the
   * currently-live version keeps the remainder. Cloudflare deployments
   * split between at most two versions, so one canary can be active per
   * script at a time.
   *
   * With {@link parent} set, defaults to `0`: the version is
   * preview-URL-only and the parent's live deployment is untouched.
   * Without `parent`, defaults to `100` (today's full cutover); `0` means
   * "upload the version without deploying it" (the equivalent of
   * `wrangler versions upload`).
   *
   * Percentages replace the previous deployment, they never add. Each
   * versioned deploy splits its new version against the *stable* version —
   * the majority holder of the current deployment — so deploying at 10 and
   * then at 20 yields the second version at 20% against the stable version
   * at 80%, with the earlier 10% version dropped from routing entirely
   * (still uploaded, but unreachable even via a version-override header).
   * With unchanged code that replacement is exactly a ramp; with changed
   * code it swaps canaries. The first deploy of a script always goes to
   * 100%, since there is no previous version to split with.
   *
   * Note that a subsequent full deploy of the parent (or of this Worker
   * itself, at the default 100) resets traffic to 100% of its own new
   * version.
   */
  traffic?: number;
  /**
   * Preview-URL alias for the uploaded version. Aliased preview URLs
   * (`<alias>-<name>.<subdomain>.workers.dev`) are stable — each upload
   * with the same alias re-points the URL at the new version — which is
   * what makes them useful as shareable PR-preview links and lets
   * `Worker.URL` resolve before the version exists.
   *
   * For a version worker ({@link parent} set) an alias is derived
   * automatically from the stack, stage, and logical id, so every version
   * worker gets a stable preview URL out of the box; set this to override
   * it. Must start with a lowercase letter, contain only lowercase
   * letters, digits, and dashes, and `<alias>-<worker-name>` must fit in
   * 63 characters (a DNS label).
   */
  alias?: string;
  /**
   * Keep each user on one version for the duration of the rollout by
   * pinning them to a stable request property — a session cookie, a
   * header, the client IP, or a raw Rules-language expression:
   *
   * ```typescript
   * version: {
   *   traffic: 10,
   *   // sticky by session cookie, falling back to sticky IP
   *   affinity: { cookie: "session_id", ip: true },
   * }
   * ```
   *
   * Provisions a Transform Rule that fills the
   * `Cloudflare-Workers-Version-Key` header on the zones the Worker
   * serves on — the Worker (or, with {@link parent}, the parent) must
   * have a `domain` or `routes`. With `parent` set, the rule lands on the
   * parent's zones, pinning users across the canary split. See
   * {@link WorkerVersionAffinity}.
   */
  affinity?: WorkerVersionAffinity;
  /**
   * Human-readable annotation attached to the uploaded version, shown in
   * the Cloudflare dashboard and `wrangler versions list`.
   */
  message?: string;
  /**
   * Machine-readable tag annotation attached to the uploaded version
   * (e.g. a git commit SHA or PR number).
   */
  tag?: string;
}

/**
 * Worker Preview configuration — uploads this Worker as a first-class
 * [Preview](https://developers.cloudflare.com/workers/previews/) of
 * another Worker's script instead of creating a script of its own.
 *
 * Distinct from {@link WorkerVersionOptions}: a version is an immutable
 * upload onto the parent script (gradual rollouts, canaries, Version
 * URLs). A Preview is a named copy with its own variables, secrets,
 * bindings, and isolated same-Worker Durable Object / Container state.
 * Cloudflare recommends Previews for branch and pull-request testing.
 *
 * Mutually exclusive with {@link WorkerVersionOptions.parent}.
 */
export interface WorkerPreviewOptions {
  /**
   * The Worker this Preview belongs to. Accepts a Worker reference —
   * typically `yield* Cloudflare.Worker.ref(id, { stage, stack })` for
   * a Worker deployed in another stage/stack, or a locally-declared
   * Worker — or a literal script name as an escape hatch.
   *
   * When set, this resource does not create a script of its own: it
   * creates (or updates) a Preview of the parent's script and deploys
   * this Worker's code, assets, and bindings to it. Script-level
   * settings that belong to the parent — `name`, `namespace`, `crons`,
   * `domain`, `routes`, `workersDev`, `access` — cannot be set on a
   * Preview Worker. Locally-hosted Durable Object and Workflow classes
   * *are* allowed: each Preview gets its own isolated namespace.
   *
   * Changing the parent replaces the resource (a Preview belongs to
   * exactly one script).
   */
  of: string | Worker;
  /**
   * Preview name. Defaults to a DNS-safe form of the stack stage
   * (`pr-123`, `feat-login`). Appears in Preview URLs:
   * `https://<name>-<worker>.<subdomain>.workers.dev` and, when the
   * parent has {@link WorkerDomainConfig.previews} enabled,
   * `https://<name>.<domain>`.
   *
   * Must start with a lowercase letter, contain only lowercase letters,
   * digits, and dashes, and `<name>-<worker-name>` must fit in 63
   * characters (a DNS label).
   */
  name?: string;
  /**
   * Human-readable annotation attached to the Preview deployment,
   * shown in the Cloudflare dashboard.
   */
  message?: string;
  /**
   * Machine-readable tag annotation attached to the Preview deployment
   * (e.g. a git commit SHA or PR number).
   */
  tag?: string;
}

export interface WorkerProps<
  // PERF: unconstrained for the same reason as `Worker<Bindings>` above —
  // the `extends WorkerBindingProps` proof is expensive for generic mapped
  // types and the call-site overloads already constrain user input.
  Bindings = any,
  Assets extends WorkerAssetsConfig | undefined = WorkerAssetsConfig | undefined,
> extends PlatformProps {
  /**
   * Worker name override. If omitted, Alchemy derives a deterministic physical
   * name from the stack, stage, and logical ID.
   */
  name?: string;
  /**
   * Deploy this Worker into a Workers for Platforms dispatch namespace as a
   * "user worker" — a customer Worker that a platform Worker dispatches to at
   * runtime via a dynamic-dispatch binding — instead of as a regular
   * account-level Worker.
   *
   * Accepts the namespace name or a {@link DispatchNamespace} resource. The
   * Worker's put/read/delete switch from the account-level
   * `/workers/scripts` endpoints to the dispatch-namespace
   * `/workers/dispatch/namespaces/:namespace/scripts` endpoints.
   *
   * User workers are not directly routable: they have no `workers.dev`
   * subdomain, custom domains, or cron triggers, so {@link url},
   * {@link domain}, and {@link crons} are ignored when this is set. Changing
   * the namespace (or moving a Worker in or out of one) replaces the Worker,
   * since an account-level script and a dispatch-namespace script are
   * distinct cloud resources.
   *
   * @see https://developers.cloudflare.com/cloudflare-for-platforms/workers-for-platforms/
   */
  namespace?: string | DispatchNamespace;
  /**
   * Worker versions & gradual deployments. Set `version.parent` to upload
   * this Worker as a canary *version* of another Worker's script
   * instead of creating its own; set `version.traffic` below 100 to
   * gradually roll out a deploy of this Worker's own script. For branch
   * and pull-request testing, use {@link preview} instead. See
   * {@link WorkerVersionOptions}.
   */
  version?: WorkerVersionOptions;
  /**
   * Opt into Cloudflare's [Worker Previews](https://developers.cloudflare.com/workers/previews/)
   * (private beta). Unset, this Worker deploys as a normal script and none
   * of the Preview APIs are called. Set `preview.of` to upload this Worker
   * as a Preview of another Worker's script instead: own URL, bindings,
   * and isolated Durable Object state; the parent's live deployment is
   * untouched. Mutually exclusive with {@link version.parent}. See
   * {@link WorkerPreviewOptions}.
   */
  preview?: WorkerPreviewOptions;
  /**
   * Controls the Worker's `workers.dev` surface.
   *
   * - `true` (the default) — serve the Worker at its stable `workers.dev`
   *   URL and enable version preview URLs.
   * - `false` — no `workers.dev` URLs at all.
   * - An object — toggle the stable URL and version previews independently,
   *   e.g. `{ enabled: false, previewsEnabled: true }` keeps the stable URL
   *   off while each deployed version stays reachable at its preview URL.
   *
   * @default true
   */
  workersDev?: boolean | WorkersDevConfig;
  /**
   * Protect this Worker with Cloudflare Access. Two forms:
   *
   * **Dedicated** — `{ policies, ... }` declares an Access application
   * owned by this Worker (namespaced under it as `<Worker>/Access`),
   * created, updated, and deleted with it:
   * ```ts
   * access: {
   *   policies: [
   *     { decision: "allow", include: [{ emailDomain: "example.com" }] },
   *   ],
   * }
   * ```
   *
   * **Shared** — pass a `Cloudflare.Access.Application` directly to enroll
   * into it. Access policies are application-wide: every enrolled Worker
   * is gated by the same policy set:
   * ```ts
   * access: TeamOnly
   * ```
   *
   * Either way the Worker's `worker` destination — and a `preview_worker`
   * destination unless `previews: false` (dedicated form) — is pushed onto
   * the application, covering custom domains, routes, the `workers.dev`
   * URL, and version preview URLs. Removing the prop (or deleting the
   * Worker) un-enrolls it.
   *
   * At runtime, read the authenticated identity from `ctx.access` via
   * `Cloudflare.Access.Context`; under `alchemy dev`, simulate it with
   * `dev: { access: ... }`. Also accepted by every `Cloudflare.Website.*`
   * framework. See the
   * [Protect a Worker with Access](/cloudflare/security/access) guide.
   */
  access?: WorkerAccessConfig;
  /**
   * Static assets to serve. Can be:
   * - A string path to the assets directory
   * - An AssetsProps object with directory and config
   * - An object with path and hash (e.g., from a Build resource)
   *
   * Plans hash the directory contents, so an unchanged tree converges to a
   * noop. Supplying a precomputed `hash` (e.g. from a Build resource) makes
   * that hash authoritative instead — the directory is not read during
   * planning at all.
   *
   * Requests are served assets-first by default: a request matching a file
   * never invokes the Worker. `runWorkerFirst` inverts that — `true` routes
   * every request through the Worker ahead of the asset layer (serve files
   * yourself via the `ASSETS` binding), and a glob array (e.g. `["/api/*"]`)
   * routes only matching paths worker-first. The same routing applies under
   * `alchemy dev`.
   *
   * When neither {@link main} nor {@link script} is provided, the Worker is
   * deployed **assets-only**: no script is uploaded at all and Cloudflare's
   * asset layer serves every request, applying `htmlHandling` /
   * `notFoundHandling` (including single-page-application fallback) itself.
   */
  assets?: Assets;
  /** @internal used by Cloudflare.Website.Vite resource */
  vite?: ViteOptions;
  /**
   * An external source provider for this Worker — a package that builds
   * the assets and server bundle (and serves local dev) in place of the
   * built-in bundling pipeline. Used by framework integrations
   * (Next/OpenNext, Astro, SvelteKit, Waku); most users configure it
   * through the framework's `Website.*` wrapper rather than directly.
   *
   * The named package must be installed in your project — it is loaded
   * with a dynamic `import()` and its default export must satisfy the
   * `WorkerSourceModule` contract (`{ make(options) }`).
   *
   * Mutually exclusive with {@link script}, {@link vite}, and
   * {@link main} — a source is self-contained; a provider that needs a
   * custom entry takes it in its own `options`.
   */
  source?: WorkerSourceDescriptor;
  logpush?: boolean;
  /**
   * Cloudflare Workers Observability settings. Controls Workers Logs
   * (`logs`) and Workers Traces (`traces`), each with their own
   * `enabled`, `headSamplingRate`, and `persist` toggles.
   *
   * If omitted, defaults to `{ enabled: true, logs: { enabled: true,
   * invocationLogs: true } }`. Traces are off by default — opt in via
   * `traces: { enabled: true, ... }`.
   *
   * Set `issues: { enabled: true }` to enable Workers Issues error detection
   * across full deployments. Setting it to `false` or omitting `issues`
   * disables Issues on the next full deployment. Version-only uploads and
   * gradual rollouts keep the parent's live observability settings.
   */
  observability?: WorkerObservability;
  /**
   * Workers Cache settings. When `enabled` is `true`, Cloudflare checks a
   * regionally tiered cache in front of the Worker on every HTTP request —
   * cache hits are served from the edge without invoking the Worker at all.
   * The Worker controls what gets cached via standard response headers
   * (`Cache-Control`, `Cache-Tag`, `Vary`), including
   * `stale-while-revalidate`.
   *
   * Set `crossVersionCache: true` to share cached responses across Worker
   * versions (by default the cache is scoped to a single version, so every
   * deploy starts cold).
   *
   * If omitted, Workers Cache is disabled — unless the Worker's init phase
   * enables it via `yield* Cloudflare.cache()`, which is the preferred way
   * for Effect-native Workers (and also returns the runtime purge client).
   * When both are set, this prop takes precedence.
   *
   * @see https://blog.cloudflare.com/workers-cache/
   */
  cache?: WorkerCache;
  /**
   * Per-entrypoint settings, keyed by export name: `default` for the
   * default export, or the class name of a named `WorkerEntrypoint`.
   * Entrypoints you leave out inherit the Worker-wide settings.
   *
   * Today the only setting is `cache`: a per-entrypoint `cache.enabled`
   * overrides the Worker-wide {@link cache} for that entrypoint. Workers
   * Cache only applies to `fetch()` invocations (including loopback calls
   * through `ctx.exports`); custom RPC methods always bypass it.
   *
   * Names must not collide with Durable Object classes hosted by this
   * Worker.
   *
   * Previews upload their own settings, and the versions of a gradual
   * rollout may differ. `alchemy dev` does not emulate Workers Cache:
   * locally, every entrypoint runs on every request.
   */
  entrypoints?: Record<string, WorkerEntrypointSettings>;
  tags?: string[];
  /**
   * Path to the Worker's entry module. Bundled with rolldown before
   * upload. Mutually exclusive with {@link script} — provide at most one.
   * Omit both (with {@link assets} set) to deploy an assets-only Worker.
   *
   * A `.py` entry deploys a Python Worker instead: no bundling runs — the
   * entry plus every sibling `.py` file upload as Python modules, the
   * `python_workers` compatibility flag is added, and dependencies from
   * `pyproject.toml` (or a prebuilt `python_modules/` directory) are
   * vendored alongside. See the Python Workers section above.
   */
  main?: string;
  /**
   * Raw module source for the Worker. When provided, bundling is bypassed
   * entirely and this string is uploaded as a single ESM module
   * (`main.js`). Useful for tiny inline workers (tests, fixtures,
   * one-offs) and any case where you've already produced the final
   * bundle elsewhere. Mutually exclusive with {@link main}.
   */
  script?: string;
  compatibility?: {
    date?: string;
    /**
     * Cloudflare runtime compatibility flags.
     *
     * For external Workers with `bundle: false`, an explicitly provided array
     * is used exactly as declared, including `[]`. Omit this field to apply
     * Alchemy's defaults.
     *
     * For all other Workers, supplied flags extend Alchemy's defaults:
     * - `new_module_registry` is added unless `legacy_module_registry` is set.
     * - `nodejs_compat` is added for dates before `2026-08-04` unless
     *   `no_nodejs_compat` is set. External Workers also require a date on or
     *   after `2024-09-23` for this default.
     * - Effect Workers get `handle_cross_request_promise_resolution` for dates
     *   before `2024-10-14`; explicitly disabling it is rejected.
     * - Python Workers get `python_workers` instead of the JavaScript defaults.
     *
     * Duplicate flags are removed when defaults are applied.
     *
     * Add `enable_request_signal` to interrupt an Effect `fetch` handler when
     * the client disconnects: the handler's finalizers run as an interruption
     * and the Worker stays alive until they finish. Without the flag,
     * Cloudflare cancels the request and its finalizers never run. `alchemy
     * dev` does not report client disconnects.
     */
    flags?: (
      | "nodejs_compat"
      | "nodejs_compat_v2"
      | "no_nodejs_compat"
      | "nodejs_als"
      | "new_module_registry"
      | "legacy_module_registry"
      | "handle_cross_request_promise_resolution"
      | "no_handle_cross_request_promise_resolution"
      | "python_workers"
      | (string & {})
    )[];
  };
  limits?: WorkerLimits;
  placement?: WorkerPlacement;
  /**
   * How each deploy rolls new code out to this Worker's running Durable
   * Objects. Cloudflare defers updates by default: an active object keeps
   * running its current code for up to 5 minutes while it waits to
   * hibernate. Use `{ mode: "immediate" }` when an object must run the new
   * code right after the deploy (during an incident, or when a test drives
   * it straight away), or set a different `maxDelay`.
   *
   * Applies per deploy, not as a stored setting: changing only this prop
   * does not redeploy the Worker; the next deploy uses it. See
   * {@link WorkerCodeUpdateStrategy}.
   *
   * @default { mode: "deferred", maxDelay: "5 minutes" }
   */
  codeUpdateStrategy?: WorkerCodeUpdateStrategy;
  /**
   * Tracks Durable Object and Workflow exports and captured SQL migrations
   * for Effect-native Workers only.
   * Populated automatically from bindings; do not set manually.
   * @internal
   */
  exports?: Record<string, WorkerExport>;
  /**
   * Environment variables and native Cloudflare Bindings to bind to
   * the Worker. Accepts:
   *
   * - Resource references (R2 bucket, KV namespace, D1 database,
   *   another Worker, Durable Object, etc.) — emitted as the
   *   corresponding native binding.
   * - `effect/Config` values (`Config.Redacted`, `Config.String`,
   *   `Config.Number`, …) — resolved at deploy time and bound as
   *   `secret_text` on Cloudflare regardless of the `Config`
   *   constructor used. See
   *   [Secrets & env](/cloudflare/security/secrets-env).
   * - Literal values — routed by shape: `Redacted<string>` →
   *   `secret_text`, `string` → `plain_text`, anything else → `json`.
   * - `Output` values that resolve to a plain env value (e.g.
   *   `Alchemy.makeRandom`) — classified at deploy time by their
   *   resolved value using the literal rules above. Whole-resource
   *   Outputs (`Output.of(bucket)`) are rejected at deploy time; bind
   *   the resource itself instead.
   *
   * In Effect-native Workers you can alternatively `yield*` a
   * `Config` in the Init phase to register the binding implicitly;
   * `env` is the only option for async (non-Effect) Workers.
   *
   * Alchemy also binds its runtime variables to every Worker:
   * `ALCHEMY_PHASE`, `ALCHEMY_WORKER_NAME`, `ALCHEMY_STACK_NAME`,
   * `ALCHEMY_STAGE` and `ALCHEMY_CLOUDFLARE_ACCOUNT_ID`. They appear in
   * `env` and, when `process.env` is populated, in `process.env`.
   */
  env?: Bindings;
  /**
   * Cron expressions that trigger the Worker's scheduled handler.
   *
   * This is how async (non-Effect) Workers configure Cron Triggers — the
   * entry module exports its own `scheduled` handler and this prop attaches
   * the schedules at deploy time. Effect-native Workers usually skip this
   * prop and call `Cloudflare.Workers.cron(expression, handler)` in the Init
   * phase instead, which attaches the expression and registers the runtime
   * listener in one step.
   *
   * Pass an empty array to remove all Cron Triggers.
   */
  crons?: string[];
  /**
   * Tail Workers that consume this Worker's execution traces. Each entry is
   * another {@link Worker} (or a literal script name) that exports a `tail()`
   * handler; after each invocation of this Worker, Cloudflare delivers the
   * invocation's trace events (console logs, exceptions, event metadata) to
   * every listed consumer.
   *
   * Pass the consumer Worker resource directly — Alchemy resolves it to its
   * deployed script name and deploys the consumer before this Worker — or a
   * plain script name string for a tail Worker managed outside this stack.
   *
   * Changing the list is an in-place update. Omitting the prop (or passing
   * `[]`) deploys this Worker with no tail consumers attached.
   *
   * @see https://developers.cloudflare.com/workers/observability/logs/tail-workers/
   */
  tailConsumers?: (string | Worker)[];
  /**
   * Streaming Tail Workers that consume this Worker's execution events as
   * they happen. Each entry is another {@link Worker} (or a literal script
   * name) that exports a `tailStream()` handler; Cloudflare invokes it with
   * the invocation's `onset` event *while this Worker is still executing*,
   * and the returned handler receives every subsequent event of the session
   * (`log`, `spanOpen`, ...) ending with the terminal `outcome`.
   *
   * This differs from {@link tailConsumers}: a plain tail consumer's `tail()`
   * handler receives the completed `TraceItem`s only after the producer's
   * invocation finishes, while a streaming tail consumer observes events
   * live, per-session, during execution.
   *
   * Pass the consumer Worker resource directly — Alchemy resolves it to its
   * deployed script name and deploys the consumer before this Worker — or a
   * plain script name string for a streaming tail Worker managed outside
   * this stack.
   *
   * Changing the list is an in-place update. Omitting the prop (or passing
   * `[]`) deploys this Worker with no streaming tail consumers attached.
   *
   * Streaming tail workers are experimental on Cloudflare's cloud: the
   * configuration deploys, but production does not yet deliver events —
   * Cloudflare rejects the `streaming_tail_worker` compatibility flag as
   * "experimental and cannot yet be used in Workers deployed to
   * Cloudflare", so a deployed consumer cannot enable its `tailStream()`
   * handler. Under `alchemy dev`, local delivery is fully emulated.
   *
   * @see https://developers.cloudflare.com/workers/observability/logs/tail-workers/
   */
  streamingTailConsumers?: (string | Worker)[];
  /**
   * The Worker's custom domain: one canonical hostname, plus optional
   * `aliases` that also serve the Worker and `redirects` that 301 to the
   * canonical name. A bare string is shorthand for `{ name }`. Pin the
   * zone with `zoneId` / `zone` / `zoneName` (same as {@link routes});
   * otherwise each hostname is looked up by name. The zone must already
   * exist in the account.
   *
   * When set, `https://<name>` becomes the Worker's primary `url` output,
   * ranking above the `workers.dev` URL. See {@link WorkerDomainConfig}.
   *
   * Omitting the prop leaves custom domains unmanaged — attachments made
   * outside Alchemy are preserved. Pass `null` to explicitly detach every
   * custom domain (and remove their redirect rules).
   */
  domain?: string | WorkerDomainConfig | null;
  /**
   * Zone routes that map URL patterns to this Worker. Equivalent to Wrangler's
   * `routes` array — provide `zoneName` or `zoneId` (or `zone`) alongside each
   * `pattern`. When the zone is omitted, it is inferred from the pattern's
   * hostname.
   *
   * `alchemy dev` emulates zone routing locally: a Worker whose custom
   * {@link domain} matches a route's hostname serves the routes on its own
   * dev URL, and each route's `url` attribute is a local listener for its
   * hostname.
   */
  routes?: WorkerRouteConfig[];
  /**
   * Extra bundler options applied on top of the standard rolldown
   * input/output options used to build this Worker. Includes the generic
   * bundle extras (pure-annotation packages, bundle analyzer) plus
   * `input` and `output` overrides. Input plugins run before Alchemy's
   * plugins; `input.resolve.alias` takes precedence over Node compatibility
   * shims. The entry remains {@link main}. Ignored when {@link bundle} is
   * `false`. See {@link WorkerBuildOptions}.
   */
  build?: WorkerBuildOptions;
  /**
   * Whether to bundle {@link main} with rolldown before upload.
   *
   * Set to `false` when `main` already points at a complete,
   * runtime-ready ESM Worker produced by an external tool (OpenNext,
   * a separate rolldown/esbuild pipeline, etc.). The entry and every
   * file around it matching {@link rules} are uploaded byte-for-byte —
   * no bundling, no minification, no transformation. Module names are
   * the files' POSIX paths relative to the entry's directory, matching
   * Wrangler's `no_bundle` contract.
   *
   * Re-bundling such artifacts is unsafe: dynamic `import()` calls the
   * upstream tool relies on can be rewritten in ways that break runtime
   * behavior.
   *
   * Durable Object and Workflow classes must be exported by the prebuilt
   * entry itself — {@link exports} is not applied when `bundle` is
   * `false`.
   *
   * @default true
   */
  bundle?: boolean;
  /**
   * Module rules selecting files uploaded as their own Worker modules,
   * mirroring Wrangler's `rules`. Globs match POSIX-style paths relative to
   * the directory containing {@link main}, and `**\/` matches any depth.
   * Each rule's `type` decides how a file is imported: `Text` as a `string`,
   * `Data` as an `ArrayBuffer`, `CompiledWasm` as a `WebAssembly.Module`.
   * Without one, the extension decides (`.wasm` CompiledWasm,
   * `.txt`/`.html`/`.sql` Text), and other files are Data. When rules
   * overlap, the first match decides.
   *
   * When Alchemy bundles {@link main}, rules add to the built-in ones
   * (`.wasm`, `.bin`, `.txt`, `.html`, `.sql`) and are checked first: an
   * imported file that matches is uploaded as a module instead of bundled.
   * JavaScript, TypeScript and JSON are always bundled, and imports inside
   * nested `?worker` modules don't use rules. For files outside the entry's
   * directory, globs may start with `../` or be absolute. `!` globs exclude
   * across your rules; an excluded `.txt` or `.wasm` still matches the
   * built-in rules.
   *
   * When {@link bundle} is `false`, every file in the entry's directory that
   * matches is uploaded, and the rules replace {@link defaultModuleRules}.
   *
   * Rules don't apply to an inline {@link script}, a {@link source}
   * provider or a Python {@link main}.
   *
   * ```ts
   * // worker.ts
   * import font from "./font.ttf"; // ArrayBuffer
   * import readme from "./README.md"; // string
   *
   * // alchemy.run.ts
   * rules: [{ globs: ["**\/*.ttf"] }, { type: "Text", globs: ["**\/*.md"] }]
   *
   * // modules.d.ts, so TypeScript knows the imports
   * declare module "*.ttf" { const data: ArrayBuffer; export default data; }
   * declare module "*.md" { const text: string; export default text; }
   * ```
   *
   * @default none when bundling; {@link defaultModuleRules} with `bundle: false`
   */
  rules?: ModuleRule[];
  /**
   * Options for the local dev server that runs this Worker under `alchemy dev`.
   * Each Worker is served on its own port.
   *
   * Use `{ mode: "external" }` to skip starting a local Worker entirely —
   * useful when an external dev server (e.g. one spawned via `Command.Dev`)
   * is serving the content this Worker would otherwise host.
   */
  dev?:
    | {
        /**
         * Run this Worker in `workerd` locally (the default).
         * @default "worker"
         */
        mode?: "worker";
        /**
         * Host the local dev server binds to.
         * @default "localhost"
         */
        host?: string;
        /**
         * Port the local dev server listens on. If the port is unavailable,
         * the next free port is used unless {@link strictPort} is `true`.
         * @default 1337
         */
        port?: number;
        /**
         * When `true`, fail instead of falling back to another port if
         * {@link port} is already in use.
         * @default false
         */
        strictPort?: boolean;
        /**
         * Whether the local runtime's Cache API simulator
         * (`caches.default` / `caches.open()`) stores responses. Set
         * `false` to make every cache operation a no-op — matching
         * production behaviour on `workers.dev` subdomains, where the
         * Cache API silently does nothing.
         * @default true
         */
        cache?: boolean;
        /**
         * Override the `request.cf` blob served to this Worker locally.
         * Defaults to a static placeholder (Miniflare's Austin/DFW blob);
         * pass e.g. `{ colo: "LHR", country: "GB" }` to simulate a
         * different edge location.
         */
        cf?: Record<string, unknown>;
        /**
         * Stub the authenticated Access state in local dev. In production,
         * `ctx.access` is populated by Cloudflare's edge after a request
         * passes the Access login wall — locally there is no edge and no
         * login, so without this stub `ctx.access` is always `undefined`
         * and identity-dependent code paths can't run. When set, every
         * request served by `alchemy dev` behaves as if this one user had
         * logged in: `ctx.access` carries the given audience and
         * `getIdentity()` resolves the given identity. Omit to simulate
         * unauthenticated requests. Inert on deploy — the deployed Worker
         * always gets the real edge-populated `ctx.access`.
         */
        access?: {
          /**
           * Simulated Access application audience (AUD) tag.
           * @default "dev"
           */
          aud?: string;
          /**
           * Simulated identity returned by `ctx.access.getIdentity()`,
           * e.g. `{ email: "dev@example.com" }`.
           */
          identity?: WorkerAccessIdentity;
        };
        /**
         * Overrides for the `workerd` process that runs this Worker
         * locally. Inert on deploy.
         */
        workerd?: {
          /**
           * Path to the workerd binary to run instead of the one from the
           * `workerd` npm package. Use it where the npm binary can't
           * start, e.g. NixOS. Set `ALCHEMY_WORKERD_PATH` instead to
           * change the binary for every workerd process alchemy starts.
           */
          path?: string;
          /**
           * Extra V8 flags, e.g. `["--max-old-space-size=4096"]` to raise
           * the heap limit. Applied after `ALCHEMY_WORKERD_V8_FLAGS`, so
           * they win when both set the same flag.
           */
          v8Flags?: string[];
          /** Extra environment variables for the workerd process. */
          env?: Record<string, string>;
        };
      }
    | {
        /**
         * Don't start a local Worker; an external dev server is running instead.
         */
        mode: "external";
        /**
         * URL the external dev server is reachable at, if applicable.
         * This will be returned as the `url` attribute of the Worker resource.
         */
        url?: string;
      };
}

/**
 * A serializable reference to an external Worker source provider.
 * Persists in state (`olds`) and crosses the local-provider RPC
 * boundary, so it must stay plain JSON data — the implementation is
 * resolved by dynamically importing {@link provider}.
 */
export interface WorkerSourceDescriptor {
  /**
   * Module specifier resolved with `import()`, e.g.
   * `"@alchemy.run/cloudflare-next"`. The module's default export must
   * satisfy the `WorkerSourceModule` contract.
   */
  readonly provider: string;
  /**
   * How the source serves local development. Server-mode sources run in an
   * isolated child process; bundle-mode sources stream rebuilds back to the
   * local Worker host.
   */
  readonly devMode: "server" | "bundle";
  /**
   * The framework project root. Server-mode dev children are spawned with
   * this directory as their working directory — some framework dev servers
   * (e.g. `next dev`, which 404s every route when `process.cwd()` differs
   * from its `dir`) require cwd to be the project root. Relative paths
   * resolve against the engine's working directory. Defaults to the
   * engine's working directory.
   */
  readonly rootDir?: string;
  /**
   * The JS runtime the server-mode dev child must run under. Some framework
   * dev servers are runtime-sensitive — `next dev` (Turbopack) silently 404s
   * every route when cold-started under bun — so the provider can pin the
   * child to `"node"`. When the requested runtime is not installed, the
   * engine falls back to its own runtime. Defaults to the engine's runtime.
   */
  readonly runtime?: "node";
  /**
   * Provider-specific options (rootDir, memo, framework config, ...).
   * Must be JSON-serializable AND JSON-stable: the descriptor persists
   * in state and participates in the metadata hash, so non-deterministic
   * values here cause perpetual redeploys.
   */
  readonly options?: unknown;
}

export interface ViteOptions {
  /**
   * Framework-specific build metadata interpreted after Vite completes.
   * Set by `Website.Foldkit` to derive asset routing from its manifest.
   * @internal
   */
  framework?: "foldkit";

  /**
   * Overrides the module that becomes the deployed Worker entry, forwarded
   * to the Cloudflare Vite plugin's `main` option. Relative paths resolve
   * from the Vite root (`rootDir`). A package export
   * (`"my-package/worker"`) or a virtual module id (`"virtual:entry"`)
   * resolves through Vite.
   *
   * By default the entry environment's own entry (the server bundle the
   * framework produces) is deployed. Point `main` at a custom module when
   * the deployed Worker must export more than the framework's fetch
   * handler — e.g. Durable Object classes or additional handlers wrapping
   * the framework handler.
   *
   * @example
   * ```typescript
   * vite: { main: "worker/index.ts" }
   * ```
   */
  main?: string;
  /**
   * Root directory passed to Vite's `root` option.
   * Defaults to the current working directory (`process.cwd()`).
   */
  rootDir?: string;
  /**
   * Controls which files are hashed to decide whether a rebuild is needed.
   * By default every non-gitignored file in `cwd` is hashed, plus the nearest
   * lockfile. Provide explicit globs to narrow the scope.
   *
   * @see {@link MemoOptions}
   */
  memo?: MemoOptions & {
    /**
     * Configure additional workspaces to hash.
     * By default, auto-detects workspaces during Vite build, then hashes all
     * non-gitignored files in the workspace plus the nearest lockfile.
     * @default "auto"
     */
    workspaces?:
      | "auto"
      | Array<
          MemoOptions & {
            /**
             * The working directory to hash, relative to the Vite root.
             */
            cwd: string;
          }
        >;
  };
  /**
   * Selects which Vite environments make up the deployed Worker, for
   * frameworks that build more than one (e.g. React Server Components).
   *
   * A single-environment SSR build needs no configuration. For a
   * multi-environment build, point `entry` at the environment that
   * produces the server entry chunk and list the remaining server-side
   * environments in `children` so their chunks are bundled alongside it.
   * The `client` environment is always treated as static assets.
   *
   * @example React Router / React Server Components
   * ```typescript
   * viteEnvironments: { entry: "rsc", children: ["ssr"] }
   * ```
   *
   * @default { entry: "ssr", children: [] }
   */
  viteEnvironments?: {
    entry?: string;
    children?: string[];
  };
}

// PERF: deliberately NOT `Bindings extends WorkerBindings`. The constraint
// forced the checker to prove the generic `NormalizedBindings<...>` mapped
// type assignable to the ~30-member `WorkerBindingResource` union at every
// `Worker<...>` instantiation — a single 28s structural relation that was 45%
// of the whole program's check time. Input is already constrained at the
// call boundary (`Bindings extends WorkerBindingProps`), so this type
// argument is only ever produced from validated shapes.
export type Worker<Bindings = any> = Resource<
  WorkerTypeId,
  WorkerProps<Bindings>,
  {
    /**
     * The immutable ID Cloudflare assigns to this Worker's script — a hex
     * value like `c81a2d22c29840ed9d61681a3270dbff`, shown as the Worker ID
     * in the dashboard and the identifier Access `worker` destinations key
     * on. Stable across every update; changes only when the script is
     * replaced. For the script *name*, use {@link workerName}. A version
     * worker carries its parent script's ID. Under `alchemy dev` there is
     * no cloud script, so the local provider generates a `dev:`-prefixed
     * ID instead (switching between dev and deploy replaces the resource,
     * so the two identities never mix).
     */
    workerId: string;
    /** The script name, e.g. `"api"` — the classic API's identifier. */
    workerName: string;
    /**
     * The Workers for Platforms dispatch namespace this Worker was deployed
     * into, or `undefined` for a regular account-level Worker.
     */
    namespace: string | undefined;
    logpush: boolean | undefined;
    /**
     * The most significant URL the Worker is reachable at — always
     * `urls[0]`, or `undefined` when the Worker is not reachable at any
     * URL (e.g. a dispatch-namespace user worker). Ranking: the canonical
     * custom domain, then aliases, then the stable `workers.dev` URL; a
     * version worker's `url` is its aliased preview URL; under
     * `alchemy dev` it is the local dev server's URL.
     */
    url: string | undefined;
    /**
     * Every URL that serves this Worker, most significant first —
     * `[https://<domain.name>?, ...aliases, <workers.dev URL>?,
     * <version preview URLs>?]`, or the local dev server's
     * `[localhost, ...LAN]` URLs under `alchemy dev`. Redirect hostnames
     * never appear (they don't serve the Worker). Useful wholesale, e.g.
     * as a CORS allow-list.
     */
    urls: string[];
    /**
     * The Worker's resolved custom-domain configuration — canonical
     * `name`, `aliases`, and `redirects` as deployed — or `undefined`
     * when no custom domain is configured.
     */
    domain:
      | {
          name: string;
          aliases: string[];
          redirects: string[];
          zone?: ZoneReference;
          previews?: boolean;
        }
      | undefined;
    tags: string[] | undefined;
    durableObjectNamespaces: Record<string, string>;
    accountId: string;
    /**
     * The zone routes attached to this Worker. `url` is the origin serving
     * the route's hostname — `https://<host>` when deployed, the local edge
     * listener under `alchemy dev` — and `undefined` for a wildcard host.
     */
    routes: { id: string; pattern: string; zoneId: string; url?: string }[];
    crons: string[];
    /**
     * The tail consumers attached to this Worker's script — each entry the
     * consuming Worker's script name — or `undefined` when none are
     * attached. Local emulation (`RuntimeWorker.tails`) lowers this same
     * list into workerd tail-service designators.
     */
    tailConsumers?: { service: string }[] | undefined;
    /**
     * The streaming tail consumers attached to this Worker's script — each
     * entry the consuming Worker's script name — or `undefined` when none
     * are attached. Recorded from the uploaded metadata: the script-settings
     * read endpoint does not expose `streaming_tail_consumers`, so this is
     * the deployed value, not an observed one. Local emulation
     * (`RuntimeWorker.streamingTails`) lowers this same list into workerd
     * streaming-tail service designators.
     */
    streamingTailConsumers?: { service: string }[] | undefined;
    /**
     * The parent script name this Worker uploads versions to, when this
     * resource is a version worker (`version.parent` set). `undefined` for
     * a Worker that owns its own script — including one deploying with a
     * gradual rollout. This is the discriminator `read`/`delete` use to
     * avoid treating the parent's script as this resource's own.
     */
    versionOf?: string | undefined;
    /**
     * The parent script name this Worker is a Preview of, when this
     * resource is a Preview Worker (`preview.of` set). `undefined` for
     * a Worker that owns its own script. Discriminator `read`/`delete`
     * use so they never treat the parent's script as this resource's own.
     */
    previewOf?: string | undefined;
    /**
     * Cloudflare's immutable Preview id. Set when this resource is a
     * Preview Worker (`preview.of`).
     */
    previewId?: string | undefined;
    /**
     * The Preview name as created — the user-provided `preview.name`, or
     * the auto-derived name from the stack stage.
     */
    previewName?: string | undefined;
    /**
     * DNS-safe slug Cloudflare assigned to this Preview. Used in Preview
     * URLs (`<slug>-<worker>.<subdomain>.workers.dev` and
     * `<slug>.<domain>` when the parent has custom-domain Previews).
     */
    previewSlug?: string | undefined;
    /**
     * Same-Worker Durable Object class names hosted on the last Preview
     * deploy — the baseline for the next Preview's class migrations.
     */
    previewDoClasses?: string[] | undefined;
    /**
     * The id of the version uploaded by the most recent deploy. Set for
     * every Worker outside a dispatch namespace: a full deploy records the
     * version serving 100% of traffic, a gradual rollout
     * (`version.traffic` < 100) and a version worker (`version.parent`)
     * record the version they uploaded.
     */
    versionId?: string | undefined;
    /**
     * The preview-URL alias attached to the uploaded version — the
     * user-provided `version.alias`, or the auto-derived stable alias for
     * a version worker. The aliased preview URL
     * (`<alias>-<name>.<subdomain>.workers.dev`) is stable across
     * deploys and is the version worker's primary `url`.
     */
    versionAlias?: string | undefined;
    /**
     * The id of the deployment created by the most recent deploy. A full
     * deploy records the active deployment; a version with `traffic > 0`
     * records the deployment it created through the deployments API.
     * Preview-only versions (`traffic: 0`) and Workers in a dispatch
     * namespace have no deployment.
     */
    deploymentId?: string | undefined;
    /**
     * The zone ids currently holding this resource's version-affinity
     * Transform Rules (`version.affinity`) — the cleanup list consulted
     * when affinity is removed or the resource is deleted. For a version
     * worker these are the *parent's* zones. `undefined` when no affinity
     * rules are deployed.
     */
    affinityZoneIds?: string[] | undefined;
    /**
     * The sorted names of the `secret_text` and `secret_key` bindings this
     * Worker's deploys uploaded and have not yet deleted. Cloudflare keeps a
     * secret binding that a later upload omits, so a full deploy deletes the
     * names listed here that it no longer uploads. Secrets set outside
     * Alchemy are never listed, and never deleted.
     */
    secretNames?: string[] | undefined;
    hash?: {
      assets: string | undefined;
      bundle: string | undefined;
      input: string | undefined;
      additionalWorkspaces: string[] | undefined;
      // Hash of the deploy-time metadata surface (compatibility, env,
      // bindings, asset config, limits, observability, ...) so metadata-only
      // edits trigger an update (#745). Optional: state written before this
      // field existed has no `metadata`, which reads as a one-time update on
      // the first diff after upgrading (the apply backfills it).
      metadata?: string | undefined;
    };
  },
  {
    bindings?: WorkerBinding[];
    /**
     * Extra env vars merged into the Worker at reconcile. `Redacted`
     * values deploy as `secret_text`. Used by later resources (e.g. a
     * Stripe webhook signing secret) to attach env without the Worker
     * init depending on that resource.
     */
    env?: Record<string, any>;
    /**
     * Workers Cache settings contributed by `yield* Cloudflare.cache()`.
     * Merged into the upload metadata's `cache_options`; an explicit
     * `WorkerProps.cache` takes precedence.
     */
    cache?: WorkerCache;
    /**
     * Workers Observability traces settings contributed by
     * `Cloudflare.Telemetry()`. Deep-merged into upload metadata: bound
     * traces fill in when `WorkerProps.observability.traces` is omitted,
     * and never clobber the default logs config. An explicit
     * `observability.traces` object wins.
     */
    observability?: Pick<WorkerObservability, "traces">;
    containers?: {
      className: string;
      /** Set when an async `Cloudflare.DurableObject(name, { containers })` binding contributed the row. */
      attachedBy?: "binding";
      /** Application name and prepared images for the native container API. */
      name?: string;
      images?: Record<string, string>;
      /** Named image sources for local workerd. An empty map enables managed images. */
      devImages?: Record<string, DevContainerImage>;
      dev: DevContainerImage | undefined;
      /**
       * Content hash of the image (bundle/Dockerfile/context). Part of the
       * local worker's restart config: `dev` only carries stable PATHS, so
       * without the hash an image content change would never restart the
       * instance and the running container would serve stale code.
       */
      hash: string | undefined;
    }[];
    crons?: string[];
    /**
     * Durable Object classes a Domain model hosts, with the names they had in
     * earlier Domain versions, so a deploy carries their data over to this
     * version's names. See `Domain/Version.ts`.
     */
    domainClasses?: DomainClass[];
    hyperdrives?: Record<string, Required<DevOrigin>>;
    /**
     * Dev-only channel (like `hyperdrives`): binding name → opt-out of local
     * emulation in `alchemy dev` (the binding was piped through `Alchemy.remote()`
     * constructor). Contributed alongside the pure wire binding instead of
     * being embedded in it — wire descriptors stay exactly what Cloudflare
     * accepts. Records from multiple bind calls merge by key; the local
     * worker provider reads it when lowering `browser` / `images` / `stream`
     * / `send_email` bindings to their local or remote runtime hooks. The
     * live provider ignores it.
     */
    devRemote?: Record<string, boolean>;
  },
  Providers
>;

/** An external/async Worker declared without an Effect implementation. */
export type ExternalWorker<Bindings = {}> = Worker<Bindings> & {
  /**
   * The external Worker's declared `env`. Not available on persisted references
   * or Effect-native Worker construction results.