The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import assert from "node:assert"; |
| 2 | import * as Context from "effect/Context"; |
| 3 | import * as Effect from "effect/Effect"; |
| 4 | import * as Option from "effect/Option"; |
| 5 | import * as Path from "effect/Path"; |
| 6 | import * as Queue from "effect/Queue"; |
| 7 | import * as Schema from "effect/Schema"; |
| 8 | import * as Semaphore from "effect/Semaphore"; |
| 9 | import * as Stream from "effect/Stream"; |
| 10 | import type * as rolldown from "rolldown"; |
| 11 | import { dotAlchemyDirectory } from "../AlchemyContext.ts"; |
| 12 | import { encodeFqn } from "../FQN.ts"; |
| 13 | import { ResourceContext } from "../ResourceContext.ts"; |
| 14 | import { StackContext } from "../StackContext.ts"; |
| 15 | import { LogAnnotation } from "../Util/LogAnnotation.ts"; |
| 16 | import { sha256, sha256Object } from "../Util/sha256.ts"; |
| 17 | import { bundleAnalyzerPlugin, type BundleAnalyzerPluginOptions } from "./BundleAnalyzerPlugin.ts"; |
| 18 | import { namespaceImportPlugin } from "./NamespaceImportPlugin.ts"; |
| 19 | import { purePlugin, type PurePluginOptions } from "./PurePlugin.ts"; |
| 20 | import { rawPlugin } from "./RawPlugin.ts"; |
| 21 | import { unreachableChunksPlugin } from "./UnreachableChunksPlugin.ts"; |
| 22 | |
| 23 | /** |
| 24 | * `resolve.conditionNames` for a bundle that runs on bun / node. |
| 25 | * |
| 26 | * Rolldown's DEFAULT conditions are import-kind specific: `import` for |
| 27 | * `import` statements and `require` for `require()` calls. An explicit |
| 28 | * `conditionNames` list is applied as one set to BOTH kinds, and rolldown |
| 29 | * adds only the current kind on top. Listing `"import"` here therefore |
| 30 | * made every `require()` also match a package's `"import"` export — and |
| 31 | * `exports` maps are matched in the PACKAGE's key order, so for `pg-pool` |
| 32 | * (`{ import, require }`) a `require("pg-pool")` received the ESM namespace |
| 33 | * and `pg` died with `TypeError: The superclass is not a constructor`. |
| 34 | * |
| 35 | * So: never put `import` or `require` in these lists. Only the runtime |
| 36 | * condition and the kind-agnostic ones; rolldown supplies the kind. |
| 37 | */ |
| 38 | export const BUN_CONDITION_NAMES: readonly string[] = ["bun", "module", "default"]; |
| 39 | export const NODE_CONDITION_NAMES: readonly string[] = ["node", "module", "default"]; |
| 40 | |
| 41 | /** |
| 42 | * Rolldown is loaded lazily on first {@link build}/{@link watch} so that |
| 43 | * merely importing alchemy — the CLI command tree, the Cloudflare provider |
| 44 | * barrel — never loads `@rolldown/binding-*`. A stack that bundles |
| 45 | * nothing must not require the native bundler to be loadable (#562). |
| 46 | */ |
| 47 | const loadRolldown = () => import("rolldown"); |
| 48 | |
| 49 | /** |
| 50 | * Extra options accepted by {@link build} / {@link watch} on top of the |
| 51 | * standard rolldown input/output options. |
| 52 | */ |
| 53 | export interface BundleExtraOptions { |
| 54 | /** |
| 55 | * Configures the {@link purePlugin} which annotates top-level |
| 56 | * call/new expressions in matching packages with `/*#__PURE__*\/` |
| 57 | * so rolldown can tree-shake them. |
| 58 | * |
| 59 | * - `undefined` (default): plugin is enabled with the default packages |
| 60 | * (`effect`, `@effect/*`, `alchemy`, `@alchemy.run/*`, |
| 61 | * `@distilled.cloud/*` — see `DEFAULT_PURE_PACKAGES`). |
| 62 | * - `PurePluginOptions`: plugin is enabled with the provided options. |
| 63 | * `packages` extends the defaults; set `replaceDefaults: true` to |
| 64 | * replace them instead. |
| 65 | * - `false`: plugin is disabled. |
| 66 | */ |
| 67 | readonly pure?: PurePluginOptions | false; |
| 68 | /** |
| 69 | * Configures the {@link bundleAnalyzerPlugin} which emits a bundle analysis |
| 70 | * report alongside the bundle output, describing chunks, modules, and the |
| 71 | * import graph reachable from each entry point. The report is written next |
| 72 | * to the bundle (see {@link BundleConfig.output}). |
| 73 | * |
| 74 | * - `undefined` / `false` (default): plugin is disabled. |
| 75 | * - `true`: plugin is enabled with default options. |
| 76 | * - `BundleAnalyzerPluginOptions`: plugin is enabled with the provided options. |
| 77 | */ |
| 78 | readonly bundleAnalyzer?: BundleAnalyzerPluginOptions | boolean; |
| 79 | } |
| 80 | |
| 81 | /** |
| 82 | * The user-facing bundler configuration shared by every resource that |
| 83 | * bundles an entrypoint with rolldown (AWS Lambda Function, Batch |
| 84 | * JobDefinition, App Runner Service, ECR image sources, EC2 hosted |
| 85 | * instances, Docker service images, Cloudflare container images, …): |
| 86 | * rolldown input/output overrides plus the {@link BundleExtraOptions} |
| 87 | * (pure-annotation packages via `pure`, bundle analyzer). |
| 88 | * |
| 89 | * Unused code is tree-shaken. `effect`, alchemy, and `@distilled.cloud` |
| 90 | * are marked pure so unused parts prune more aggressively. List extra |
| 91 | * packages with `pure.packages`, or disable with `pure: false`. |
| 92 | */ |
| 93 | export interface BundleConfig extends BundleExtraOptions { |
| 94 | /** |
| 95 | * Rolldown input options overrides. |
| 96 | */ |
| 97 | readonly input?: Partial<rolldown.InputOptions>; |
| 98 | /** |
| 99 | * Rolldown output options overrides. |
| 100 | * |
| 101 | * The bundle is written to `.alchemy/bundles/<stack>-<stage>-<resource>`, |
| 102 | * which is cleared before every build, so you can inspect exactly what |
| 103 | * ships. Set `dir` or `file` to write it somewhere else; Alchemy never |
| 104 | * clears a directory you choose. |
| 105 | */ |
| 106 | readonly output?: Partial<rolldown.OutputOptions>; |
| 107 | } |
| 108 | |
| 109 | export interface BundleOutput { |
| 110 | /** |
| 111 | * The files in the bundle. |
| 112 | * The first file is the entry. |
| 113 | */ |
| 114 | readonly files: [BundleFile, ...BundleFile[]]; |
| 115 | /** |
| 116 | * The SHA-256 hash of all files in the bundle. |
| 117 | */ |
| 118 | readonly hash: string; |
| 119 | } |
| 120 | |
| 121 | export interface BundleFile { |
| 122 | readonly path: string; |
| 123 | readonly content: string | Uint8Array<ArrayBufferLike>; |
| 124 | readonly hash: string; |
| 125 | /** |
| 126 | * The platform's module type for this file, when its extension doesn't |
| 127 | * decide it (e.g. a Cloudflare `Text` rule over `.md` files). |
| 128 | */ |
| 129 | readonly type?: string; |
| 130 | } |
| 131 | |
| 132 | export class BundleError extends Schema.TaggedError<BundleError>()("BundleError", { |
| 133 | message: Schema.String, |
| 134 | cause: Schema.optional(Schema.Defect({ includeStack: true })), |
| 135 | }) {} |
| 136 | |
| 137 | export type BundleWatchEvent = |
| 138 | | BundleWatchEvent.Start |
| 139 | | BundleWatchEvent.Success |
| 140 | | BundleWatchEvent.Error; |
| 141 | |
| 142 | export declare namespace BundleWatchEvent { |
| 143 | interface Start { |
| 144 | readonly _tag: "Start"; |
| 145 | } |
| 146 | interface Success { |
| 147 | readonly _tag: "Success"; |
| 148 | readonly output: BundleOutput; |
| 149 | } |
| 150 | interface Error { |
| 151 | readonly _tag: "Error"; |
| 152 | readonly error: BundleError; |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | /** |
| 157 | * Compile-time constants substituted into every bundle via rolldown's |
| 158 | * `transform.define`. |
| 159 | * |
| 160 | * `globalThis.__ALCHEMY_RUNTIME__` is the runtime-phase flag: it is folded to |
| 161 | * `true` in all bundled (runtime) artifacts — deployed Workers, Lambdas, |
| 162 | * Containers, etc. — so any plan-only code guarded by |
| 163 | * `if (!globalThis.__ALCHEMY_RUNTIME__)` becomes `if (!true)` and is |
| 164 | * dead-code-eliminated from what ships. |
| 165 | * |
| 166 | * When the same source runs WITHOUT the bundler (the plan process executing |
| 167 | * `.ts` directly with bun/node), `globalThis.__ALCHEMY_RUNTIME__` reads as |
| 168 | * `undefined` (falsy) rather than throwing, so plan-only branches run. |
| 169 | * See `ALCHEMY_PHASE` in `Phase.ts`. |
| 170 | */ |
| 171 | const ALCHEMY_DEFINE: Record<string, string> = { |
| 172 | "globalThis.__ALCHEMY_RUNTIME__": "true", |
| 173 | }; |
| 174 | |
| 175 | /** |
| 176 | * Default rolldown `moduleTypes` applied to every bundle, mirroring the |
| 177 | * `Text` module rules Wrangler applies to Workers (and alchemy's own |
| 178 | * {@link defaultModuleRules} for prebuilt bundles): importing a `.sql`, |
| 179 | * `.txt`, or `.html` file default-exports its contents as a string. |
| 180 | * |
| 181 | * `.sql` is what makes drizzle-kit's generated Durable Object migrations |
| 182 | * bundle (`migrations.js` does `import m0000 from './0000_x.sql'`) work |
| 183 | * without a wrangler-style rules config or a codegen step. |
| 184 | */ |
| 185 | const ALCHEMY_MODULE_TYPES: NonNullable<rolldown.InputOptions["moduleTypes"]> = { |
| 186 | ".sql": "text", |
| 187 | ".txt": "text", |
| 188 | ".html": "text", |
| 189 | }; |
| 190 | |
| 191 | /** |
| 192 | * Merge {@link ALCHEMY_DEFINE} into the caller's `transform.define` (the |
| 193 | * framework flags win over any caller-provided keys) and |
| 194 | * {@link ALCHEMY_MODULE_TYPES} into the caller's `moduleTypes` (caller |
| 195 | * keys win, so an extension can be remapped or disabled per bundle). |
| 196 | * |
| 197 | * Also enables `experimental.lazyBarrel` unless the caller sets it, so a |
| 198 | * runtime importing one service from `@alchemy.run/aws` (a barrel of every |
| 199 | * AWS service) compiles that service, not all of them. See |
| 200 | * {@link namespaceImportPlugin} for `import * as AWS`. |
| 201 | */ |
| 202 | const withAlchemyDefine = (inputOptions: rolldown.InputOptions): rolldown.InputOptions => ({ |
| 203 | ...inputOptions, |
| 204 | experimental: { |
| 205 | lazyBarrel: true, |
| 206 | ...inputOptions.experimental, |
| 207 | }, |
| 208 | transform: { |
| 209 | ...inputOptions.transform, |
| 210 | define: { |
| 211 | ...inputOptions.transform?.define, |
| 212 | ...ALCHEMY_DEFINE, |
| 213 | }, |
| 214 | }, |
| 215 | moduleTypes: { |
| 216 | ...ALCHEMY_MODULE_TYPES, |
| 217 | ...inputOptions.moduleTypes, |
| 218 | }, |
| 219 | }); |
| 220 | |
| 221 | /** |
| 222 | * Default `minify` to `"dce-only"` when the caller hasn't chosen a mode, so the |
| 223 | * `if (false) { … }` branches produced by {@link ALCHEMY_DEFINE} are physically |
| 224 | * removed from every bundle (define alone only folds the condition; removal |
| 225 | * needs DCE). Callers that opt into full minification (e.g. Workers) keep it. |
| 226 | */ |
| 227 | const withDceDefault = (outputOptions?: rolldown.OutputOptions): rolldown.OutputOptions => ({ |
| 228 | ...outputOptions, |
| 229 | minify: outputOptions?.minify ?? "dce-only", |
| 230 | }); |
| 231 | |
| 232 | /** Whether the caller chose where the bundle is written (`dir` or `file`). */ |
| 233 | export const hasOutputLocation = (outputOptions?: Partial<rolldown.OutputOptions>): boolean => |
| 234 | outputOptions?.dir !== undefined || outputOptions?.file !== undefined; |
| 235 | |
| 236 | /** |
| 237 | * The directory a resource's bundle is written to when its `output` sets |
| 238 | * neither `dir` nor `file`: `.alchemy/bundles/<stack>-<stage>-<fqn>`, one flat |
| 239 | * level under `bundles/` (namespace separators in the FQN become `__`). Every |
| 240 | * resource gets its own directory, so concurrent stages never share one and |
| 241 | * the directory can be cleared before each build. |
| 242 | */ |
| 243 | export const outputDirectory = (resource: { |
| 244 | readonly stack: string; |
| 245 | readonly stage: string; |
| 246 | readonly fqn: string; |
| 247 | }) => |
| 248 | Effect.gen(function* () { |
| 249 | const path = yield* Path.Path; |
| 250 | const dotAlchemy = yield* dotAlchemyDirectory; |
| 251 | // A relative `.alchemy` (standalone callers) stays relative, so rolldown |
| 252 | // resolves it against the bundle `cwd` like any other output `dir`. |
| 253 | return path.join( |
| 254 | dotAlchemy, |
| 255 | "bundles", |
| 256 | `${resource.stack}-${resource.stage}-${encodeFqn(resource.fqn)}`, |
| 257 | ); |
| 258 | }); |
| 259 | |
| 260 | /** |
| 261 | * Resolve where a bundle is written: |
| 262 | * |
| 263 | * - `dir` or `file` set by the caller: rolldown writes there, as configured. |
| 264 | * - Otherwise, inside a resource lifecycle operation (the engine provides |
| 265 | * {@link ResourceContext} and the stack): the resource's |
| 266 | * {@link outputDirectory}, cleared before each build so stale hashed |
| 267 | * chunks never pile up. |
| 268 | * - Otherwise: the bundle stays in memory. Rolldown's default `dir` (`dist`, |
| 269 | * resolved against `cwd`) would leave an unused copy in the user's package. |
| 270 | * |
| 271 | * Callers always consume the bundle from memory; the copy on disk is for |
| 272 | * inspecting what ships, the bundle analyzer report, and `writeBundle` hooks. |
| 273 | */ |
| 274 | const resolveOutputOptions = (outputOptions?: rolldown.OutputOptions) => |
| 275 | Effect.gen(function* () { |
| 276 | const options = withDceDefault(outputOptions); |
| 277 | if (hasOutputLocation(options)) return options; |
| 278 | const resource = yield* Effect.serviceOption(ResourceContext); |
| 279 | const stack = yield* Effect.serviceOption(StackContext); |
| 280 | const path = yield* Effect.serviceOption(Path.Path); |
| 281 | if (Option.isNone(resource) || Option.isNone(stack) || Option.isNone(path)) return options; |
| 282 | const dir = yield* outputDirectory({ |
| 283 | stack: stack.value.name, |
| 284 | stage: stack.value.stage, |
| 285 | fqn: resource.value.fqn, |
| 286 | }).pipe(Effect.provideService(Path.Path, path.value)); |
| 287 | return { ...options, dir, cleanDir: true } satisfies rolldown.OutputOptions; |
| 288 | }); |
| 289 | |
| 290 | /** |
| 291 | * Process-wide limit on concurrent rolldown builds (one-shot builds and each |
| 292 | * watcher's initial build). Every build holds the full module graph in native |
| 293 | * memory, so an unbounded burst (a stack deploying dozens of functions, or a |
| 294 | * dev session starting one watcher per function) peaks at gigabytes of RSS. |
| 295 | * Override with `ALCHEMY_BUNDLE_CONCURRENCY`. |
| 296 | */ |
| 297 | const bundleConcurrency = (() => { |
| 298 | const configured = Number(process.env.ALCHEMY_BUNDLE_CONCURRENCY); |
| 299 | return Number.isInteger(configured) && configured > 0 ? configured : 4; |
| 300 | })(); |
| 301 | const buildPermits = Semaphore.makeUnsafe(bundleConcurrency); |
| 302 | |
| 303 | /** |
| 304 | * Rolldown's own logs (warnings such as `UNRESOLVED_IMPORT`, plugin timings) |
| 305 | * as `output` records in the context of the build: the resource's `fqn` and |
| 306 | * trace, one record per log instead of raw lines on stderr. Like any tool |
| 307 | * output, they stay in the run log and are never exported. A caller's own |
| 308 | * `onLog` wins. |
| 309 | */ |
| 310 | const withRolldownLogs = ( |
| 311 | inputOptions: rolldown.InputOptions, |
| 312 | context: Context.Context<never>, |
| 313 | ): rolldown.InputOptions => |
| 314 | inputOptions.onLog !== undefined |
| 315 | ? inputOptions |
| 316 | : { |
| 317 | ...inputOptions, |
| 318 | onLog: (level, log) => |
| 319 | Effect.runSyncWith(context)( |
| 320 | Effect.logWithLevel(level === "warn" ? "Warn" : level === "debug" ? "Debug" : "Info")( |
| 321 | log.frame === undefined ? log.message : `${log.message}\n${log.frame}`, |
| 322 | ).pipe( |
| 323 | Effect.annotateLogs({ |
| 324 | [LogAnnotation.stream]: "stderr", |
| 325 | ...(log.code === undefined ? {} : { code: log.code }), |
| 326 | ...(log.plugin === undefined ? {} : { plugin: log.plugin }), |
| 327 | }), |
| 328 | ), |
| 329 | ), |
| 330 | }; |
| 331 | |
| 332 | /** |
| 333 | * Build a bundle using rolldown from the given input options and output options. |
| 334 | * @param inputOptions - The input options for the bundle. |
| 335 | * @param outputOptions - The output options for the bundle. |
| 336 | * @returns The bundle output. |
| 337 | */ |
| 338 | export const build = ( |
| 339 | inputOptions: rolldown.InputOptions, |
| 340 | outputOptions?: rolldown.OutputOptions, |
| 341 | extra?: BundleExtraOptions, |
| 342 | ): Effect.Effect<BundleOutput, BundleError> => |
| 343 | Effect.zip(resolveOutputOptions(outputOptions), Effect.context<never>()).pipe( |
| 344 | Effect.flatMap(([options, context]) => |
| 345 | Effect.tryPromise({ |
| 346 | try: async () => { |
| 347 | const rolldown = await loadRolldown(); |
| 348 | const bundle = await rolldown.rolldown({ |
| 349 | ...withAlchemyDefine(withRolldownLogs(inputOptions, context)), |
| 350 | plugins: [inputOptions.plugins, await builtInPlugins(extra)], |
| 351 | optimization: inputOptions.optimization ?? { |
| 352 | inlineConst: { |
| 353 | mode: "smart", |
| 354 | pass: 3, |
| 355 | }, |
| 356 | }, |
| 357 | }); |
| 358 | const result = hasOutputLocation(options) |
| 359 | ? await bundle.write(options) |
| 360 | : await bundle.generate(options); |
| 361 | await bundle.close(); |
| 362 | return result.output; |
| 363 | }, |
| 364 | catch: bundleErrorFromUnknown, |
| 365 | }).pipe(buildPermits.withPermits(1)), |
| 366 | ), |
| 367 | Effect.flatMap(Effect.forEach(bundleFileFromOutputChunk)), |
| 368 | Effect.flatMap(bundleOutputFromFiles), |
| 369 | ); |
| 370 | |
| 371 | /** |
| 372 | * Watch for changes in the bundle and return a stream of bundle output. |
| 373 | * @param inputOptions - The input options for the bundle. |
| 374 | * @param outputOptions - The output options for the bundle. |
| 375 | * @returns A stream of Result instances containing either the bundle output or an error. |
| 376 | */ |
| 377 | export const watch = ( |
| 378 | inputOptions: rolldown.InputOptions, |
| 379 | outputOptions?: rolldown.OutputOptions, |
| 380 | extra?: BundleExtraOptions, |
| 381 | ): Stream.Stream<BundleWatchEvent> => |
| 382 | Stream.unwrap( |
| 383 | Effect.zipWith( |
| 384 | resolveOutputOptions(outputOptions), |
| 385 | Effect.context<never>(), |
| 386 | (options, context) => watchResolved(withRolldownLogs(inputOptions, context), extra)(options), |
| 387 | ), |
| 388 | ); |
| 389 | |
| 390 | const watchResolved = |
| 391 | (inputOptions: rolldown.InputOptions, extra: BundleExtraOptions | undefined) => |
| 392 | (outputOptions: rolldown.OutputOptions): Stream.Stream<BundleWatchEvent> => |
| 393 | Stream.callback< |
| 394 | | BundleWatchEvent.Start |
| 395 | | BundleWatchEvent.Error |
| 396 | | { |
| 397 | readonly _tag: "Success"; |
| 398 | readonly output: rolldown.OutputBundle; |
| 399 | } |
| 400 | >((queue) => { |
| 401 | const createWatcher = async (settle: () => void) => { |
| 402 | const rolldown = await loadRolldown(); |
| 403 | const watcher = rolldown.watch({ |
| 404 | ...withAlchemyDefine(inputOptions), |
| 405 | plugins: [ |
| 406 | inputOptions.plugins, |
| 407 | await builtInPlugins(extra), |
| 408 | // The watcher event listener does not receive the bundle output, so we grab it using a plugin. |
| 409 | { |
| 410 | name: "alchemy:watch-bundle", |
| 411 | watchChange() { |
| 412 | Queue.offerUnsafe(queue, { |
| 413 | _tag: "Start", |
| 414 | }); |
| 415 | }, |
| 416 | generateBundle(_outputOptions, bundle) { |
| 417 | Queue.offerUnsafe(queue, { |
| 418 | _tag: "Success", |
| 419 | output: bundle, |
| 420 | }); |
| 421 | }, |
| 422 | }, |
| 423 | ], |
| 424 | watch: { |
| 425 | // Watching the full module graph of an Effect worker (all of |
| 426 | // `effect`, `alchemy`, `@distilled.cloud/*`) registers thousands |
| 427 | // of OS watch handles *per worker*; with several Effect workers |
| 428 | // this exhausts the process fd table and the next `posix_spawn` |
| 429 | // (workerd / docker) fails with `spawn EBADF`. Workspace packages |
| 430 | // resolve to their real source paths (outside `node_modules`), so |
| 431 | // they stay watched and local HMR is unaffected. |
| 432 | exclude: ["**/node_modules/**"], |
| 433 | // `generateBundle` still fires, so the output is captured either way. |
| 434 | skipWrite: !hasOutputLocation(outputOptions), |
| 435 | }, |
| 436 | output: outputOptions, |
| 437 | }); |
| 438 | watcher.on("event", (event) => { |
| 439 | if (event.code === "ERROR" || event.code === "BUNDLE_END") { |
| 440 | settle(); |
| 441 | } |
| 442 | if (event.code === "ERROR") { |
| 443 | Queue.offerUnsafe(queue, { |
| 444 | _tag: "Error", |
| 445 | error: bundleErrorFromUnknown(event.error), |
| 446 | }); |
| 447 | } else if (event.code === "BUNDLE_END") { |
| 448 | // This must be called to avoid resource leaks. |
| 449 | event.result.close().catch(() => {}); |
| 450 | } |
| 451 | }); |
| 452 | return watcher; |
| 453 | }; |
| 454 | return Effect.acquireRelease( |
| 455 | Effect.gen(function* () { |
| 456 | // Hold a build permit until the watcher's initial build settles. |
| 457 | yield* buildPermits.take(1); |
| 458 | const context = yield* Effect.context(); |
| 459 | let initialBuildSettled = false; |
| 460 | const settleInitialBuild = () => { |
| 461 | if (initialBuildSettled) return; |
| 462 | initialBuildSettled = true; |
| 463 | Effect.runForkWith(context)(buildPermits.release(1)); |
| 464 | }; |
| 465 | const watcher = yield* Effect.promise(() => createWatcher(settleInitialBuild)).pipe( |
| 466 | Effect.onError(() => Effect.sync(settleInitialBuild)), |
| 467 | ); |
| 468 | return { watcher, settleInitialBuild }; |
| 469 | }), |
| 470 | ({ watcher, settleInitialBuild }) => |
| 471 | Effect.promise(() => watcher.close()).pipe( |
| 472 | Effect.ensuring(Effect.sync(settleInitialBuild)), |
| 473 | ), |
| 474 | ); |
| 475 | }).pipe( |
| 476 | Stream.mapEffect((event) => |
| 477 | Effect.gen(function* () { |
| 478 | if (event._tag !== "Success") { |
| 479 | return event; |
| 480 | } |
| 481 | return yield* bundleOutputFromRolldownOutputBundle(event.output).pipe( |
| 482 | Effect.map((output): BundleWatchEvent.Success => ({ |
| 483 | _tag: "Success", |
| 484 | output, |
| 485 | })), |
| 486 | Effect.catch((error) => |
| 487 | Effect.succeed<BundleWatchEvent.Error>({ |
| 488 | _tag: "Error", |
| 489 | error: bundleErrorFromUnknown(error), |
| 490 | }), |
| 491 | ), |
| 492 | ); |
| 493 | }), |
| 494 | ), |
| 495 | ); |
| 496 | |
| 497 | const ENTRY_PREFIX = "\0virtual:alchemy-entry:"; |
| 498 | const ENTRY_REGEX = /^\0virtual:alchemy-entry:/; |
| 499 | /** |
| 500 | * Ids the `resolveId` hook looks at: the virtual entry ids themselves, plus |
| 501 | * bare package specifiers (not starting with `.`, `/` or `\0`) so an |
| 502 | * unresolvable import in a generated entry fails the build (below). |
| 503 | */ |
| 504 | const ENTRY_OR_BARE_REGEX = /^(?:\0virtual:alchemy-entry:|[^./\0])/; |
| 505 | |
| 506 | export const virtualEntryPlugin = Effect.gen(function* () { |
| 507 | const path = yield* Path.Path; |
| 508 | |
| 509 | const normalizeInput = (input: rolldown.InputOption): Record<string, string> => { |
| 510 | if (typeof input === "string") { |
| 511 | return { [path.parse(input).name || "index"]: input }; |
| 512 | } else if (Array.isArray(input)) { |
| 513 | return Object.fromEntries(input.map((p) => [path.parse(p).name, p])); |
| 514 | } else { |
| 515 | return input; |
| 516 | } |
| 517 | }; |
| 518 | |
| 519 | return (content: (importPath: string) => string) => { |
| 520 | const entries = new Map<string, string>(); |
| 521 | return { |
| 522 | name: "alchemy:virtual-entry", |
| 523 | options: { |
| 524 | order: "pre", |
| 525 | handler(inputOptions) { |
| 526 | const cwd = inputOptions.cwd ?? process.cwd(); |
| 527 | const input = normalizeInput(inputOptions.input ?? {}); |
| 528 | inputOptions.input = Object.fromEntries( |
| 529 | Object.entries(input).map(([name, p]) => { |
| 530 | const id = `${ENTRY_PREFIX}${name}`; |
| 531 | entries.set(id, path.resolve(cwd, p)); |
| 532 | return [name, id]; |
| 533 | }), |
| 534 | ); |
| 535 | }, |
| 536 | }, |
| 537 | resolveId: { |
| 538 | filter: { id: ENTRY_OR_BARE_REGEX }, |
| 539 | async handler(id, importer) { |
| 540 | if (ENTRY_REGEX.test(id)) { |
| 541 | return entries.has(id) ? { id } : null; |
| 542 | } |
| 543 | // A bare import made BY a generated entry. Rolldown only WARNS on |
| 544 | // an unresolved import and leaves it external, which for a |
| 545 | // generated entry means the deployed process dies at boot with |
| 546 | // `Cannot find module` — the class of bug the shim design |
| 547 | // (`{Provider}/Bootstrap/*`) exists to prevent. Make it a build |
| 548 | // error with the cause spelled out instead. Externals resolve to |
| 549 | // `{ external: true }`, not null, so they pass through. |
| 550 | if (importer === undefined || !ENTRY_REGEX.test(importer)) { |
| 551 | return null; |
| 552 | } |
| 553 | const resolved = await this.resolve(id, importer, { |
| 554 | skipSelf: true, |
| 555 | }); |
| 556 | if (resolved === null) { |
| 557 | const entry = entries.get(importer); |
| 558 | this.error( |
| 559 | new Error( |
| 560 | `The generated entry for ${entry} imports "${id}", which cannot be resolved from the project. ` + |
| 561 | "A generated entry may only import its bootstrap module (from `alchemy` or the provider package that generated it) and the entry itself; " + |
| 562 | "check that the package is installed in the project containing the entry.", |
| 563 | ), |
| 564 | ); |
| 565 | } |
| 566 | return resolved; |
| 567 | }, |
| 568 | }, |
| 569 | load: { |
| 570 | filter: { id: ENTRY_REGEX }, |
| 571 | handler(id) { |
| 572 | const entry = entries.get(id); |
| 573 | assert(entry !== undefined, `unknown alchemy entry: ${id}`); |
| 574 | return { |
| 575 | code: content(entry), |
| 576 | moduleType: "ts", |
| 577 | }; |
| 578 | }, |
| 579 | }, |
| 580 | } satisfies rolldown.Plugin; |
| 581 | }; |
| 582 | }); |
| 583 | |
| 584 | export function bundleOutputFromRolldownOutputBundle( |
| 585 | bundle: rolldown.OutputBundle, |
| 586 | ): Effect.Effect<BundleOutput, BundleError> { |
| 587 | const files = Object.values(bundle); |
| 588 | // These are sanity checks - with rolldown, the first file is always an entry chunk. |
| 589 | if (!files[0] || files[0].type !== "chunk" || !files[0].isEntry) { |
| 590 | return Effect.fail( |
| 591 | BundleError.make({ |
| 592 | message: "Invalid bundle output", |
| 593 | }), |
| 594 | ); |
| 595 | } |
| 596 | return Effect.forEach( |
| 597 | files as [rolldown.OutputChunk, ...(rolldown.OutputChunk | rolldown.OutputAsset)[]], |
| 598 | bundleFileFromOutputChunk, |
| 599 | ).pipe(Effect.flatMap(bundleOutputFromFiles)); |
| 600 | } |
| 601 | |
| 602 | /** |
| 603 | * Returns the built-in plugins appended after the user-provided plugin chain, |
| 604 | * configured by {@link BundleExtraOptions}. |
| 605 | * |
| 606 | * These run LAST so they see module ids that have already been resolved into |
| 607 | * `node_modules/<pkg>/...` by upstream resolver plugins such as |
| 608 | * `@alchemy.run/cloudflare-runtime/rolldown`. |
| 609 | */ |
| 610 | async function builtInPlugins(extra?: BundleExtraOptions): Promise<rolldown.RolldownPluginOption> { |
| 611 | return [ |
| 612 | extra?.bundleAnalyzer |
| 613 | ? await bundleAnalyzerPlugin(extra.bundleAnalyzer === true ? {} : extra.bundleAnalyzer) |
| 614 | : undefined, |
| 615 | namespaceImportPlugin(), |
| 616 | extra?.pure !== false ? purePlugin(extra?.pure ?? {}) : undefined, |
| 617 | rawPlugin(), |
| 618 | unreachableChunksPlugin(), |
| 619 | ]; |
| 620 | } |
| 621 | |
| 622 | export function bundleErrorFromUnknown(error: unknown): BundleError { |
| 623 | const message = error instanceof Error ? error.message : String(error); |
| 624 | return BundleError.make({ |
| 625 | message, |
| 626 | cause: error, |
| 627 | }); |
| 628 | } |
| 629 | |
| 630 | export function bundleOutputFromFiles( |
| 631 | files: [BundleFile, ...BundleFile[]], |
| 632 | ): Effect.Effect<BundleOutput> { |
| 633 | return Effect.map( |
| 634 | sha256Object( |
| 635 | files.map((file) => ({ |
| 636 | path: file.path, |
| 637 | hash: file.hash, |
| 638 | ...(file.type ? { type: file.type } : {}), |
| 639 | })), |
| 640 | ), |
| 641 | (hash) => ({ files, hash }), |
| 642 | ); |
| 643 | } |
| 644 | |
| 645 | function bundleFileFromOutputChunk( |
| 646 | chunk: rolldown.OutputChunk | rolldown.OutputAsset, |
| 647 | ): Effect.Effect<BundleFile> { |
| 648 | switch (chunk.type) { |
| 649 | case "chunk": |
| 650 | return Effect.map(sha256(chunk.code), (hash) => ({ |
| 651 | path: chunk.fileName, |
| 652 | content: chunk.code, |
| 653 | hash, |
| 654 | })); |
| 655 | case "asset": |
| 656 | return Effect.map(sha256(chunk.source), (hash) => ({ |
| 657 | path: chunk.fileName, |
| 658 | content: chunk.source, |
| 659 | hash, |
| 660 | })); |
| 661 | } |
| 662 | } |