The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as Cloudflare from "@alchemy.run/cloudflare"; |
| 2 | import * as Bridge from "@alchemy.run/cloudflare/Bridge"; |
| 3 | import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment"; |
| 4 | import { CloudflareEnvironment as RuntimeCloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironmentService"; |
| 5 | import { |
| 6 | makeEffectVirtualEntry, |
| 7 | WorkerBundle, |
| 8 | } from "@alchemy.run/cloudflare/Workers/Sources/Rolldown"; |
| 9 | import * as WorkerRuntime from "@alchemy.run/cloudflare/Workers/WorkerRuntime"; |
| 10 | import * as WorkflowRuntime from "@alchemy.run/cloudflare/Workflows/WorkflowRuntime"; |
| 11 | import { describe, expect, layer } from "@alchemy.run/test"; |
| 12 | import * as Test from "@alchemy.run/test/Alchemy"; |
| 13 | import * as NodeServices from "@effect/platform-node/NodeServices"; |
| 14 | import { virtualEntryPlugin } from "alchemy/Bundle/Bundle"; |
| 15 | import { Stack } from "alchemy/Stack"; |
| 16 | import { StackContext } from "alchemy/StackContext"; |
| 17 | import * as Telemetry from "alchemy/Telemetry"; |
| 18 | import * as TelemetryRuntime from "alchemy/TelemetryRuntime"; |
| 19 | import * as Effect from "effect/Effect"; |
| 20 | import * as HttpClientRequest from "effect/http/HttpClientRequest"; |
| 21 | import * as Path from "effect/Path"; |
| 22 | import { requestWorker } from "../Utils/WorkerRequest.ts"; |
| 23 | import RuntimeEntryWorker from "./fixtures/runtime-entry/worker.ts"; |
| 24 | |
| 25 | const plannerSources = [ |
| 26 | "alchemy/src/Auth/", |
| 27 | "alchemy/src/Bundle/", |
| 28 | "alchemy/src/Local/", |
| 29 | "alchemy/src/Resource.ts", |
| 30 | "alchemy/src/Stack.ts", |
| 31 | "alchemy/src/Telemetry.ts", |
| 32 | "cloudflare/src/CloudflareEnvironment.ts", |
| 33 | "cloudflare/src/D1/LocalD1Gateway.ts", |
| 34 | "cloudflare/src/Local", |
| 35 | "cloudflare/src/SecretsStore/LocalSecretsStoreGateway.ts", |
| 36 | "cloudflare/src/Workers/Worker.ts", |
| 37 | "cloudflare/src/Workflows/Workflow.ts", |
| 38 | "cloudflare/src/Containers/ContainerBundle.ts", |
| 39 | "cloudflare/src/Website/Vite.ts", |
| 40 | "cloudflare/src/Workers/LocalWorkerProvider.ts", |
| 41 | "cloudflare/src/Workers/Sources/", |
| 42 | "cloudflare/src/Workers/ViteChild", |
| 43 | "cloudflare/src/Workers/WorkerProvider.ts", |
| 44 | ]; |
| 45 | |
| 46 | // Paths are relative to `packages/`. |
| 47 | const sourceRoots = ["alchemy/src", "cloudflare/src"]; |
| 48 | |
| 49 | const toolchainPackages = ["esbuild", "rolldown", "vite", "workerd"]; |
| 50 | |
| 51 | const packageOf = (id: string) => { |
| 52 | const segments = id.split(/[\\/]node_modules[\\/]/); |
| 53 | if (segments.length < 2) return undefined; |
| 54 | const rest = segments[segments.length - 1]!.split(/[\\/]/); |
| 55 | return rest[0]!.startsWith("@") ? `${rest[0]}/${rest[1]}` : rest[0]; |
| 56 | }; |
| 57 | |
| 58 | const bundleWorkerEntry = Effect.fn(function* (entry: string, generated = false) { |
| 59 | const path = yield* Path.Path; |
| 60 | const packagesDir = yield* path.fromFileUrl(new URL("../../../../", import.meta.url)); |
| 61 | const { default: cloudflare } = yield* Effect.promise( |
| 62 | () => import("@alchemy.run/cloudflare-runtime/rolldown"), |
| 63 | ); |
| 64 | const { rolldown } = yield* Effect.promise(() => import("rolldown")); |
| 65 | const virtualEntry = yield* virtualEntryPlugin; |
| 66 | const graph = new Map<string, { isEntry: boolean; importedIds: readonly string[] }>(); |
| 67 | return yield* Effect.acquireUseRelease( |
| 68 | Effect.promise(() => |
| 69 | rolldown({ |
| 70 | input: path.join(packagesDir, entry), |
| 71 | // The generated entry's bare imports resolve from the cwd, and only |
| 72 | // the package that owns the fixtures depends on the providers. |
| 73 | cwd: path.join(packagesDir, "integration-tests"), |
| 74 | external: [ |
| 75 | "lightningcss", |
| 76 | "fsevents", |
| 77 | // Isolate dependencies added by the generator from the application's imports. |
| 78 | ...(generated ? [path.join(packagesDir, entry)] : []), |
| 79 | ], |
| 80 | plugins: [ |
| 81 | cloudflare({ compatibilityDate: "2025-04-01", compatibilityFlags: ["nodejs_compat"] }), |
| 82 | generated |
| 83 | ? virtualEntry(makeEffectVirtualEntry({}, { name: "runtime-entry", stage: "test" })) |
| 84 | : undefined, |
| 85 | { |
| 86 | name: "collect-modules", |
| 87 | moduleParsed(info) { |
| 88 | graph.set(info.id, { |
| 89 | isEntry: info.isEntry, |
| 90 | importedIds: [...info.importedIds, ...info.dynamicallyImportedIds], |
| 91 | }); |
| 92 | }, |
| 93 | }, |
| 94 | ], |
| 95 | checks: { unresolvedImport: false, ineffectiveDynamicImport: false }, |
| 96 | logLevel: "silent", |
| 97 | }), |
| 98 | ), |
| 99 | (bundle) => |
| 100 | Effect.gen(function* () { |
| 101 | const { output } = yield* Effect.promise(() => bundle.generate({ format: "esm" })); |
| 102 | const chunks = new Map( |
| 103 | output |
| 104 | .filter((item) => item.type === "chunk") |
| 105 | .map((chunk) => [chunk.fileName, chunk] as const), |
| 106 | ); |
| 107 | const entryChunk = [...chunks.values()].find((chunk) => chunk.isEntry)!; |
| 108 | // Dynamic imports must not conceal deployment dependencies either. |
| 109 | const reachableChunks = new Set<string>(); |
| 110 | const chunkQueue = [entryChunk.fileName]; |
| 111 | for (let f = chunkQueue.shift(); f !== undefined; f = chunkQueue.shift()) { |
| 112 | if (reachableChunks.has(f) || !chunks.has(f)) continue; |
| 113 | reachableChunks.add(f); |
| 114 | chunkQueue.push(...chunks.get(f)!.imports, ...chunks.get(f)!.dynamicImports); |
| 115 | } |
| 116 | const code = [...reachableChunks].map((f) => chunks.get(f)!.code).join("\n"); |
| 117 | const modules = new Set<string>(); |
| 118 | const queue = [...graph].filter(([, m]) => m.isEntry).map(([id]) => id); |
| 119 | for (let id = queue.shift(); id !== undefined; id = queue.shift()) { |
| 120 | if (modules.has(id)) continue; |
| 121 | modules.add(id); |
| 122 | queue.push(...(graph.get(id)?.importedIds ?? [])); |
| 123 | } |
| 124 | const sources = [...modules] |
| 125 | .filter((id) => sourceRoots.some((root) => id.startsWith(path.join(packagesDir, root)))) |
| 126 | .map((id) => path.relative(packagesDir, id).replaceAll("\\", "/")); |
| 127 | const packages = new Set([...modules].map(packageOf).filter((name) => name !== undefined)); |
| 128 | return { code, exports: entryChunk.exports, sources, packages }; |
| 129 | }), |
| 130 | (bundle) => Effect.promise(() => bundle.close()), |
| 131 | ); |
| 132 | }); |
| 133 | |
| 134 | /** |
| 135 | * Bundle a fixture with `WorkerBundle` and return the modules rendered into |
| 136 | * the files the build ships. The collector's `generateBundle` runs before the |
| 137 | * built-in `unreachableChunksPlugin`, so it also sees chunks that are pruned |
| 138 | * afterwards; only chunks in the returned output count. |
| 139 | */ |
| 140 | const renderShippedModules = Effect.fn(function* ( |
| 141 | fixture: string, |
| 142 | entry: { kind: "external" } | { kind: "effect"; exports: {} }, |
| 143 | ) { |
| 144 | const path = yield* Path.Path; |
| 145 | const packagesDir = yield* path.fromFileUrl(new URL("../../../../", import.meta.url)); |
| 146 | const chunks = new Map<string, string[]>(); |
| 147 | const output = yield* (yield* WorkerBundle).build({ |
| 148 | id: "runtime-entry", |
| 149 | main: path.join( |
| 150 | packagesDir, |
| 151 | "integration-tests/test/Cloudflare/Workers/fixtures/runtime-entry", |
| 152 | fixture, |
| 153 | ), |
| 154 | compatibility: { date: "2025-04-01", flags: ["nodejs_compat"] }, |
| 155 | entry, |
| 156 | stack: { name: "runtime-entry", stage: "test" }, |
| 157 | extraOptions: { |
| 158 | input: { |
| 159 | plugins: { |
| 160 | name: "collect-rendered-modules", |
| 161 | generateBundle: (_options, bundle) => { |
| 162 | for (const chunk of Object.values(bundle)) { |
| 163 | if (chunk.type !== "chunk") continue; |
| 164 | chunks.set( |
| 165 | chunk.fileName, |
| 166 | Object.entries(chunk.modules) |
| 167 | .filter(([, module]) => module.renderedLength > 0) |
| 168 | .map(([id]) => path.relative(packagesDir, id).replaceAll("\\", "/")), |
| 169 | ); |
| 170 | } |
| 171 | }, |
| 172 | }, |
| 173 | }, |
| 174 | }, |
| 175 | }); |
| 176 | return output.files.flatMap((file) => chunks.get(file.path) ?? []); |
| 177 | }); |
| 178 | |
| 179 | const isPlannerSource = (source: string) => |
| 180 | plannerSources.some((prefix) => source.startsWith(prefix)); |
| 181 | |
| 182 | layer(NodeServices.layer)("@alchemy.run/cloudflare/Bridge (runtime-only entry)", (it) => { |
| 183 | it.effect( |
| 184 | "exports the bridge factories the generated Worker entry imports", |
| 185 | () => |
| 186 | Effect.gen(function* () { |
| 187 | const { exports } = yield* bundleWorkerEntry("cloudflare/src/Bridge.ts"); |
| 188 | expect(exports).toEqual( |
| 189 | expect.arrayContaining([ |
| 190 | "makeWorkerBridge", |
| 191 | "makeDurableObjectBridge", |
| 192 | "makeWorkflowBridge", |
| 193 | "fromCloudflareFetcher", |
| 194 | "toRpcAsync", |
| 195 | ]), |
| 196 | ); |
| 197 | }), |
| 198 | { tags: ["unit", "provider:cloudflare", "provider:cloudflare:worker", "local"] }, |
| 199 | ); |
| 200 | |
| 201 | it.effect( |
| 202 | "keeps planner tooling out of /Bridge's dependency graph", |
| 203 | () => |
| 204 | Effect.gen(function* () { |
| 205 | const { code, sources, packages } = yield* bundleWorkerEntry("cloudflare/src/Bridge.ts"); |
| 206 | expect(sources.filter(isPlannerSource)).toEqual([]); |
| 207 | expect(toolchainPackages.filter((name) => packages.has(name))).toEqual([]); |
| 208 | expect(code).not.toContain("require.resolve"); |
| 209 | }), |
| 210 | { tags: ["unit", "provider:cloudflare", "provider:cloudflare:worker", "local"] }, |
| 211 | ); |
| 212 | |
| 213 | it.effect( |
| 214 | "keeps planner tooling out of imports added by the generated wrapper", |
| 215 | () => |
| 216 | Effect.gen(function* () { |
| 217 | const { code, sources, packages, exports } = yield* bundleWorkerEntry( |
| 218 | "integration-tests/test/Cloudflare/Workers/fixtures/runtime-entry/worker.ts", |
| 219 | true, |
| 220 | ); |
| 221 | expect(exports).toContain("default"); |
| 222 | expect(sources).toContain("cloudflare/src/Bridge.ts"); |
| 223 | expect(sources.filter(isPlannerSource)).toEqual([]); |
| 224 | expect(toolchainPackages.filter((name) => packages.has(name))).toEqual([]); |
| 225 | expect(code).not.toContain("require.resolve"); |
| 226 | }), |
| 227 | { tags: ["unit", "provider:cloudflare", "provider:cloudflare:worker", "local"] }, |
| 228 | ); |
| 229 | |
| 230 | it.effect( |
| 231 | "keeps the stack builder and auth store out of a bundled Worker", |
| 232 | () => |
| 233 | Effect.gen(function* () { |
| 234 | const rendered = yield* renderShippedModules("worker.ts", { kind: "external" }); |
| 235 | expect(rendered).toContain("alchemy/src/Resource.ts"); |
| 236 | expect(rendered.filter((id) => /^alchemy\/src\/(Stack\.ts$|Auth\/)/.test(id))).toEqual([]); |
| 237 | }), |
| 238 | { tags: ["unit", "provider:cloudflare", "provider:cloudflare:worker", "local"] }, |
| 239 | ); |
| 240 | |
| 241 | for (const fixture of ["barrel-worker.ts", "bindings-worker.ts"]) { |
| 242 | it.effect( |
| 243 | `keeps the Cloudflare API client out of a bundled Worker (${fixture})`, |
| 244 | () => |
| 245 | Effect.gen(function* () { |
| 246 | const rendered = yield* renderShippedModules(fixture, { kind: "effect", exports: {} }); |
| 247 | expect(rendered).toContain("cloudflare/src/Workers/WorkerBridge.ts"); |
| 248 | // Deploy-only provider helpers (e.g. `findQueueByName`) reach the |
| 249 | // distilled clients. `purePlugin` prunes them behind async bindings; |
| 250 | // the runtime defines alone suffice for the hello-world (#2371). |
| 251 | expect( |
| 252 | rendered.filter((id) => /@distilled\.cloud|submodules\/distilled\//.test(id)), |
| 253 | ).toEqual([]); |
| 254 | }), |
| 255 | { tags: ["unit", "provider:cloudflare", "provider:cloudflare:worker", "local"] }, |
| 256 | ); |
| 257 | } |
| 258 | |
| 259 | it.effect( |
| 260 | "the @alchemy.run/cloudflare namespace does pull that tooling", |
| 261 | () => |
| 262 | Effect.gen(function* () { |
| 263 | const { code, sources, packages } = yield* bundleWorkerEntry("cloudflare/src/index.ts"); |
| 264 | expect(sources).toContain("cloudflare/src/Workers/Sources/Rolldown.ts"); |
| 265 | expect(packages.has("workerd")).toBe(true); |
| 266 | expect(code).toContain("require.resolve"); |
| 267 | }), |
| 268 | { tags: ["unit", "provider:cloudflare", "provider:cloudflare:worker", "local"] }, |
| 269 | ); |
| 270 | |
| 271 | it.effect( |
| 272 | "detects local tooling behind a dynamic import", |
| 273 | () => |
| 274 | Effect.gen(function* () { |
| 275 | const { code, sources, packages } = yield* bundleWorkerEntry( |
| 276 | "integration-tests/test/Cloudflare/Workers/fixtures/runtime-entry/dynamic-tooling.ts", |
| 277 | ); |
| 278 | expect(sources.filter(isPlannerSource)).toContain("cloudflare/src/LocalRuntime.ts"); |
| 279 | expect(packages.has("workerd")).toBe(true); |
| 280 | expect(code).toContain("require.resolve"); |
| 281 | }), |
| 282 | { tags: ["unit", "provider:cloudflare", "provider:cloudflare:worker", "local"] }, |
| 283 | ); |
| 284 | |
| 285 | it.effect( |
| 286 | "preserves the public runtime service identities", |
| 287 | () => |
| 288 | Effect.sync(() => { |
| 289 | expect(Cloudflare.WorkerEnvironment).toBe(WorkerRuntime.WorkerEnvironment); |
| 290 | expect(Cloudflare.WorkerExecutionContext).toBe(WorkerRuntime.WorkerExecutionContext); |
| 291 | expect(Cloudflare.Workflows.WorkflowEvent).toBe(WorkflowRuntime.WorkflowEvent); |
| 292 | expect(Cloudflare.Workflows.WorkflowStep).toBe(WorkflowRuntime.WorkflowStep); |
| 293 | expect(Cloudflare.Workflows.WorkflowStepContext).toBe(WorkflowRuntime.WorkflowStepContext); |
| 294 | expect(CloudflareEnvironment).toBe(RuntimeCloudflareEnvironment); |
| 295 | expect(Stack.key).toBe(StackContext.key); |
| 296 | expect(Telemetry.Telemetry).toBe(TelemetryRuntime.Telemetry); |
| 297 | }), |
| 298 | { |
| 299 | tags: [ |
| 300 | "unit", |
| 301 | "provider:cloudflare", |
| 302 | "provider:cloudflare:worker", |
| 303 | "provider:cloudflare:workflow", |
| 304 | "local", |
| 305 | ], |
| 306 | }, |
| 307 | ); |
| 308 | |
| 309 | it.effect( |
| 310 | "@alchemy.run/cloudflare still re-exports the same factories", |
| 311 | () => |
| 312 | Effect.sync(() => { |
| 313 | expect(Cloudflare.makeWorkerBridge).toBe(Bridge.makeWorkerBridge); |
| 314 | expect(Cloudflare.makeDurableObjectBridge).toBe(Bridge.makeDurableObjectBridge); |
| 315 | expect(Cloudflare.makeWorkflowBridge).toBe(Bridge.makeWorkflowBridge); |
| 316 | }), |
| 317 | { tags: ["unit", "provider:cloudflare", "provider:cloudflare:worker", "local"] }, |
| 318 | ); |
| 319 | }); |
| 320 | |
| 321 | for (const dev of [false, true]) { |
| 322 | describe( |
| 323 | `runtime entry (${dev ? "local" : "live"})`, |
| 324 | { tags: ["provider:cloudflare", "provider:cloudflare:worker"] }, |
| 325 | () => { |
| 326 | const { test } = Test.make({ providers: Cloudflare.providers(), dev }); |
| 327 | |
| 328 | test.provider( |
| 329 | "application importing Worker.ts serves requests", |
| 330 | (stack) => |
| 331 | Effect.gen(function* () { |
| 332 | yield* stack.destroy(); |
| 333 | const worker = yield* stack.deploy(RuntimeEntryWorker); |
| 334 | const response = yield* requestWorker(HttpClientRequest.get(worker.url!), { |
| 335 | retryDelay: "3 seconds", |
| 336 | }); |
| 337 | expect(response.status).toBe(200); |
| 338 | expect(yield* response.text).toBe(`runtime-entry:${stack.stage}`); |
| 339 | yield* stack.destroy(); |
| 340 | }), |
| 341 | { tags: [...(dev ? ["local"] : ["live"])] }, |
| 342 | ); |
| 343 | }, |
| 344 | ); |
| 345 | } |