Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion packages/alchemy/src/Cloudflare/Workers/InferEnv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,10 @@ export type GetBindingType<T> =
// generic Effect unwrap: a Container declaration is itself an Effect.
T extends Container.Decl<any, any, any, any, infer DOShape>
? DurableObjectNamespace<DOShape & Rpc.DurableObjectBranded>
: T extends Effect.Effect<infer A, infer _E, infer _R>
: // `Worker.URL` (an Effect resolving to a deferred string accessor) needs
// no case of its own: the generic Effect unwrap below reduces it to
// `string` via the fallthrough.
T extends Effect.Effect<infer A, infer _E, infer _R>
? GetBindingType<A>
: T extends FlagshipNs.App
? Flagship
Expand Down
59 changes: 49 additions & 10 deletions packages/alchemy/src/Cloudflare/Workers/LocalWorkerProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ import type { WorkerAssetsConfig, WorkerProps } from "../Workers/Worker.ts";
import { readAssetsConfigFiles } from "./Assets.ts";
import { getCompatibility } from "./Compatibility.ts";
import { isPythonMain, watchPythonWorkerBundle } from "./PythonWorkerBundle.ts";
import { Worker } from "./Worker.ts";
import { isSelfUrl, Worker } from "./Worker.ts";
import { getCronBindings } from "./WorkerAsyncBindings.ts";
import type { WorkerBinding } from "./WorkerBinding.ts";
import { WorkerBundle, type WorkerBundleOptions } from "./WorkerBundle.ts";
Expand All @@ -79,6 +79,14 @@ type WorkerPropsWithDev = Omit<WorkerProps, "dev"> & {
dev: Extract<WorkerProps["dev"], { mode?: "worker" }>;
};

/**
* The normalized dev-server options a proxy is started with (`props.dev`
* with the default port applied). Named independently of `WorkerConfig` so
* `maybeStartProxy` — which `buildConfig` now calls to resolve `Worker.URL`
* — doesn't form a type cycle through `WorkerConfig["dev"]`.
*/
type DevServerOptions = WorkerPropsWithDev["dev"] & { port: number };

export class WorkerValidationError extends Schema.TaggedErrorClass<WorkerValidationError>()(
"WorkerValidationError",
{
Expand All @@ -102,7 +110,7 @@ export const LocalWorkerProvider = () =>
const proxyInstances = new Map<
string,
{
serverOptions: WorkerConfig["dev"];
serverOptions: DevServerOptions;
instance: WorkerProxy.WorkerProxyInstance;
scope: Scope.Closeable;
}
Expand Down Expand Up @@ -134,7 +142,7 @@ export const LocalWorkerProvider = () =>

const startProxy = Effect.fn(function* (
id: string,
serverOptions: WorkerConfig["dev"],
serverOptions: DevServerOptions,
) {
const scope = yield* Scope.fork(rootScope);
const instance = yield* workerProxy
Expand All @@ -154,7 +162,7 @@ export const LocalWorkerProvider = () =>

const maybeStartProxy = Effect.fn(function* (
id: string,
serverOptions: WorkerConfig["dev"],
serverOptions: DevServerOptions,
) {
const existing = proxyInstances.get(id);
if (existing) {
Expand Down Expand Up @@ -392,12 +400,31 @@ export const LocalWorkerProvider = () =>
const { accountId } = yield* yield* CloudflareEnvironment;
const name = yield* createWorkerName(id, props.name);
const compatibility = getCompatibility(props);
const dev: DevServerOptions = {
...props.dev,
// This is the default. Vite and cloudflare-runtime will retry if unavailable, unless `strictPort` is true.
port: props.dev?.port ?? 1337,
};
// `Worker.URL` locally resolves to the worker's dev-proxy URL — the
// proxy is stable per worker id (the same instance `runWorker` /
// `runVite` attach to below), so the URL is known before workerd
// starts. Trailing slash stripped to match the cloud value's shape.
const needsSelfUrl =
bindings.some((b) =>
(b.data.bindings ?? []).some((item) => item.type === "self_url"),
) || Object.values(props.env ?? {}).some(isSelfUrl);
const selfUrl = needsSelfUrl
? (yield* maybeStartProxy(id, dev)).url.toString().replace(/\/$/, "")
: undefined;
const workerBindings: BindingHook<BindingServices>[] = [
Text.local("ALCHEMY_PHASE", "runtime"),
Text.local("ALCHEMY_STACK_NAME", stack.name),
Text.local("ALCHEMY_STAGE", stack.stage),
Text.local("ALCHEMY_CLOUDFLARE_ACCOUNT_ID", accountId),
...Object.entries(props.env ?? {}).map(([key, value]) => {
if (isSelfUrl(value)) {
return Text.local(key, selfUrl!);
}
const unredacted = Redacted.isRedacted(value)
? Redacted.value(value)
: value;
Expand All @@ -416,6 +443,12 @@ export const LocalWorkerProvider = () =>
const containers: Record<string, ContainerImage> = {};
for (const { data } of bindings) {
for (const binding of data.bindings ?? []) {
if (binding.type === "self_url") {
// Lowered here rather than in `toRuntimeBinding` — only this
// scope knows the worker's own dev-proxy URL.
workerBindings.push(Text.local(binding.name, selfUrl!));
continue;
}
if (
binding.type === "durable_object_namespace" &&
// The `durableObjectNamespaces` property is only used to declare DOs in this worker.
Expand Down Expand Up @@ -499,7 +532,17 @@ export const LocalWorkerProvider = () =>
viteMain: props.vite?.main,
viteEnvironments: props.vite?.viteEnvironments,
hyperdrives,
env: props.env,
// Substitute `Worker.URL` sentinels so the Vite dev server inlines
// the local URL into VITE_*-prefixed define entries.
env:
props.env && selfUrl !== undefined
? Object.fromEntries(
Object.entries(props.env).map(([key, value]) => [
key,
isSelfUrl(value) ? selfUrl : value,
]),
)
: props.env,
bundleOptions: {
id,
main: props.main!,
Expand All @@ -511,11 +554,7 @@ export const LocalWorkerProvider = () =>
extraOptions: props.build,
} satisfies WorkerBundleOptions,
assets: props.assets,
dev: {
...props.dev,
// This is the default. Vite and cloudflare-runtime will retry if unavailable, unless `strictPort` is true.
port: props.dev?.port ?? 1337,
},
dev,
};
});

Expand Down
154 changes: 142 additions & 12 deletions packages/alchemy/src/Cloudflare/Workers/Worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -681,6 +681,86 @@ export type Worker<Bindings extends WorkerBindings = any> = Resource<
Providers
>;

/** The env key the resolved URL is injected under when `yield*`-ed. */
const SELF_URL_BINDING_NAME = "WORKER_URL";

/**
* Effect-native accessor for the Worker's own URL. The value is injected as an
* env binding that only exists at the *exec* phase on the deployed Worker, so
* reading it is deferred behind an Effect that requires {@link RuntimeContext}.
* Yield it inside a handler to obtain the URL string.
*/
export type URLAccessor = Effect.Effect<string, never, RuntimeContext>;

/**
* The type of {@link URL} (`Worker.URL`).
*
* It is a real `Effect` — `yield* Worker.URL` inside a Worker init attaches
* the binding and resolves the deferred {@link URLAccessor} — but it also
* carries the `~alchemy/Kind` marker statically, so when it is declared on a
* Worker's `env` the binding machinery recognises it as a `self_url` binding
* (`isSelfUrl`) instead of running it.
*
* Defined in this module (not its own file): the effect closes over the
* `Worker` tag and `WorkerEnvironment`, and a separate module would form a
* value cycle with Worker.ts that the deploy bundler's scope hoisting turns
* into a startup crash.
*/
export interface URLEffect extends Effect.Effect<
URLAccessor,
never,
WorkerEnvironment | Worker
> {
"~alchemy/Kind": "Cloudflare.Workers.URL";
}

/**
* A Worker's own public URL, injected as a binding on that same Worker. At
* deploy time Alchemy resolves the URL the Worker will be served at (its first
* custom domain if any, otherwise its `workers.dev` URL) and injects it as a
* plain-text env binding, so the running Worker knows its own public address.
*
* Declare it on a Worker's `env` (it flows through `InferEnv` → `string`) or
* `yield*` it inside an Effect-native Worker to attach the binding and obtain
* a deferred {@link URLAccessor}. It is also exposed as
* `Cloudflare.Worker.URL`.
*
* Because the URL is resolved *before* the bundle is built, a `VITE_`-prefixed
* env key holding `Worker.URL` is inlined into the client bundle as
* `import.meta.env.VITE_*` — the canonical way to give a Vite frontend its own
* public URL.
*/
export const URL: URLEffect = Object.assign(
Effect.gen(function* () {
// Deploy-time only: register the binding on the host Worker. The provider
// lowers the `self_url` sentinel into a plain-text binding holding the
// resolved URL just before upload.
if (!globalThis.__ALCHEMY_RUNTIME__) {
yield* (yield* Worker).bind`${SELF_URL_BINDING_NAME}`({
bindings: [{ type: "self_url", name: SELF_URL_BINDING_NAME }],
});
}
// Captured at init; the deferred read only runs at exec phase (the
// accessor is colored with RuntimeContext), where env is populated.
const env = yield* WorkerEnvironment;
return Effect.sync(
() => (env as Record<string, string>)[SELF_URL_BINDING_NAME]!,
) as URLAccessor;
}),
{ "~alchemy/Kind": "Cloudflare.Workers.URL" as const },
);

/**
* Returns true when the value is the `Worker.URL` binding (keyed on the
* static `~alchemy/Kind` marker — the value is a real Effect, so every
* env-resolution site must check this before `Effect.isEffect`).
*/
export const isSelfUrl = (value: unknown): value is URLEffect =>
typeof value === "object" &&
value !== null &&
"~alchemy/Kind" in value &&
(value as URLEffect)["~alchemy/Kind"] === "Cloudflare.Workers.URL";

/**
* A Cloudflare Worker host with deploy-time binding support and runtime export
* collection.
Expand Down Expand Up @@ -947,6 +1027,45 @@ export type Worker<Bindings extends WorkerBindings = any> = Resource<
* }
* ```
*
* @section The Worker's own URL
* `Worker.URL` injects the URL a Worker is served at as a binding on that
* same Worker — the first custom `domain` if one is configured, otherwise
* its `workers.dev` URL, always equal to the resource's `url` attribute.
* Under `alchemy dev` it resolves to the local dev server's URL.
*
* @example Read the Worker's own URL inside a handler
* ```typescript
* Cloudflare.Worker(
* "Api",
* { main: import.meta.url },
* Effect.gen(function* () {
* // Attaches the binding and returns a deferred accessor.
* const url = yield* Cloudflare.Worker.URL;
*
* return {
* fetch: Effect.gen(function* () {
* const publicUrl = yield* url;
* return Response.json({ url: publicUrl });
* }),
* };
* }).pipe(Effect.provide(Cloudflare.Workers.URLBinding)),
* );
* ```
*
* @example Inject the URL into an async Worker's env
* `InferEnv` types the entry as `string`. A `VITE_`-prefixed key on a
* vite-built Worker is additionally inlined into the client bundle as
* `import.meta.env.VITE_PUBLIC_URL` at build time.
* ```typescript
* export const Worker = Cloudflare.Worker("Worker", {
* main: "./src/worker.ts",
* env: { PUBLIC_URL: Cloudflare.Worker.URL },
* });
*
* export type WorkerEnv = Cloudflare.InferEnv<typeof Worker>;
* // { PUBLIC_URL: string }
* ```
*
* @section Observability
* Cloudflare Workers Observability is on by default — `logs.enabled` and
* `logs.invocationLogs` are turned on if you don't pass an `observability`
Expand Down Expand Up @@ -1324,15 +1443,26 @@ export const Worker: ResourceClassLike<Worker> &
Extract<Req, Container.Application<any>> | Providers
> &
Named<Id>;
} = Platform(WorkerTypeId, {
// Both hooks are wrapped in arrows so the imported references are resolved
// at call time rather than at module-load time. Worker.ts forms import
// cycles with both WorkerAsyncBindings.ts (which imports `isWorker` here)
// and WorkerRuntimeContext.ts (which imports `WorkerTypeId`/`WorkerEnvironment`
// here). Reading either binding eagerly here hits TDZ when Bun loads the
// package from node_modules in a different module-init order than the local
// workspace.
onCreate: (resource, props) =>
bindWorkerAsyncBindings(resource as Worker, props),
createRuntimeContext: (id) => makeWorkerRuntimeContext(id),
});
/**
* The Worker's own public URL, injected as a binding on that same Worker.
* Declare it on `env` (`env: { VITE_PUBLIC_URL: Worker.URL }`) or
* `yield*` it inside an Effect-native Worker to obtain a deferred
* accessor. See {@link URLEffect}.
*/
readonly URL: URLEffect;
} = Platform(
WorkerTypeId,
{
// Both hooks are wrapped in arrows so the imported references are resolved
// at call time rather than at module-load time. Worker.ts forms import
// cycles with both WorkerAsyncBindings.ts (which imports `isWorker` here)
// and WorkerRuntimeContext.ts (which imports `WorkerTypeId`/`WorkerEnvironment`
// here). Reading either binding eagerly here hits TDZ when Bun loads the
// package from node_modules in a different module-init order than the local
// workspace.
onCreate: (resource, props) =>
bindWorkerAsyncBindings(resource as Worker, props),
createRuntimeContext: (id) => makeWorkerRuntimeContext(id),
},
{ URL },
);
14 changes: 13 additions & 1 deletion packages/alchemy/src/Cloudflare/Workers/WorkerAsyncBindings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,12 @@ import {
import { isRateLimit } from "./RateLimit.ts";
import { isVersionMetadata } from "./VersionMetadata.ts";
import type { WorkerBindingProps } from "./Worker.ts";
import { isWorker, type Worker, type WorkerProps } from "./Worker.ts";
import {
isSelfUrl,
isWorker,
type Worker,
type WorkerProps,
} from "./Worker.ts";
import type { WorkerBinding, WorkerBindingResource } from "./WorkerBinding.ts";
import { isWorkerLoader } from "./WorkerLoader.ts";

Expand Down Expand Up @@ -375,6 +380,13 @@ const toBinding = (
type: "version_metadata",
name: bindingName,
};
} else if (isSelfUrl(binding)) {
// The Worker's own URL. The provider lowers this sentinel into a
// `plain_text` binding holding the resolved URL just before upload.
return {
type: "self_url",
name: bindingName,
};
} else if (isWorkerLoader(binding)) {
return {
type: "worker_loader",
Expand Down
23 changes: 22 additions & 1 deletion packages/alchemy/src/Cloudflare/Workers/WorkerBinding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import type { DispatchNamespace } from "../WorkersForPlatforms/DispatchNamespace
import type { WorkflowLike } from "../Workflows/Workflow.ts";
import type { AIBinding } from "./AIBinding.ts";
import type { Assets } from "./Assets.ts";
import type { URLEffect } from "./Worker.ts";
import type { BrowserBinding } from "./BrowserBinding.ts";
import type { DurableObjectLike } from "./DurableObject.ts";
import type { RateLimitBinding } from "./RateLimitBinding.ts";
Expand Down Expand Up @@ -53,9 +54,27 @@ export type DurableObjectNamespaceWorkerBinding = Extract<
transferredFrom?: string | string[];
};

/**
* Alchemy-only binding: the host Worker's own public URL (`Worker.URL`). The
* provider resolves the URL the Worker will be served at (first custom domain,
* else its `workers.dev` URL) and lowers this into a `plain_text` binding
* before the script upload — Cloudflare never sees this type.
*/
export interface SelfUrlWorkerBinding {
type: "self_url";
name: string;
}

/**
* The wire-shape binding union the Cloudflare API accepts — {@link WorkerBinding}
* minus the alchemy-only members that must be lowered before upload.
*/
export type WireWorkerBinding = Exclude<WorkerBinding, SelfUrlWorkerBinding>;

export type WorkerBinding =
| Exclude<DistilledWorkerBinding, { type: "durable_object_namespace" }>
| DurableObjectNamespaceWorkerBinding;
| DurableObjectNamespaceWorkerBinding
| SelfUrlWorkerBinding;

export type WorkerSettingsBinding = Exclude<
workers.GetScriptScriptAndVersionSettingResponse["bindings"],
Expand Down Expand Up @@ -90,6 +109,8 @@ export type WorkerBindingResource =
| Worker
| WorkerLoader
| VersionMetadataBinding
// The Worker's own URL (`Worker.URL`).
| URLEffect
| DispatchNamespace
| DurableObjectLike<any>
| WorkflowLike<any>
Expand Down
Loading
Loading