The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as fs from "node:fs/promises"; |
| 2 | import * as path from "node:path"; |
| 3 | import type { |
| 4 | CallExpression, |
| 5 | ExportDefaultDeclaration, |
| 6 | ExportNamedDeclaration, |
| 7 | Expression, |
| 8 | ExpressionStatement, |
| 9 | NewExpression, |
| 10 | Program, |
| 11 | Statement, |
| 12 | VariableDeclaration, |
| 13 | } from "@oxc-project/types"; |
| 14 | import picomatch from "picomatch"; |
| 15 | import type * as rolldown from "rolldown"; |
| 16 | |
| 17 | /** |
| 18 | * `rolldown` and `rolldown/parseAst` load `@rolldown/binding-*` at module |
| 19 | * scope, so they are imported lazily on first use — importing this module |
| 20 | * (e.g. via the `alchemy/Bundle` barrel) must never load the native |
| 21 | * binding (#562). |
| 22 | */ |
| 23 | const loadRolldown = () => import("rolldown"); |
| 24 | const loadParseAst = () => import("rolldown/parseAst"); |
| 25 | |
| 26 | /** |
| 27 | * Default packages whose modules will receive `/*#__PURE__*\/` annotations. |
| 28 | * Mirrors what `effect-smol` ships via `babel-plugin-annotate-pure-calls` |
| 29 | * applied to its own `dist/` output. |
| 30 | * |
| 31 | * `alchemy` is included so its own resources (which consist almost entirely |
| 32 | * of `Effect.fn(...)`, `Context.Service(...)(...)`, `Layer.effect(...)` and |
| 33 | * `Data.TaggedError(...)` top-level calls) become tree-shakeable. The |
| 34 | * package already declares `"sideEffects": false`, so it is safe. |
| 35 | * |
| 36 | * `@distilled.cloud/*` is included so the generated SDK service modules |
| 37 | * (large files of top-level `const op = make(...)` operation definitions) |
| 38 | * tree-shake down to the operations a Worker actually calls. Every |
| 39 | * distilled package declares `"sideEffects": false`. |
| 40 | */ |
| 41 | export const DEFAULT_PURE_PACKAGES: ReadonlyArray<string> = [ |
| 42 | "effect", |
| 43 | "@effect/*", |
| 44 | "alchemy", |
| 45 | "@alchemy.run/*", |
| 46 | "@distilled.cloud/*", |
| 47 | ]; |
| 48 | |
| 49 | /** |
| 50 | * Options for {@link purePlugin}. |
| 51 | */ |
| 52 | export interface PurePluginOptions { |
| 53 | /** |
| 54 | * Extra package names or globs to annotate, in addition to |
| 55 | * {@link DEFAULT_PURE_PACKAGES}. Globs are matched with picomatch |
| 56 | * against the package name (e.g. `effect`, `@effect/cluster`). |
| 57 | * |
| 58 | * Listing a package that declares `"sideEffects": false` (or `[]`) |
| 59 | * in its `package.json` opts it into full annotation, including |
| 60 | * top-level calls whose result is discarded — see {@link purePlugin}. |
| 61 | */ |
| 62 | readonly packages?: ReadonlyArray<string>; |
| 63 | /** |
| 64 | * If true, the configured `packages` list replaces the defaults |
| 65 | * entirely instead of extending them. |
| 66 | * @default false |
| 67 | */ |
| 68 | readonly replaceDefaults?: boolean; |
| 69 | /** |
| 70 | * If true, also marks matched modules as side-effect free |
| 71 | * (mirrors `"sideEffects": []` in package.json), so rolldown drops |
| 72 | * unused re-exports from those packages. |
| 73 | * @default true |
| 74 | */ |
| 75 | readonly markSideEffectFree?: boolean; |
| 76 | } |
| 77 | |
| 78 | const PURE_COMMENT = "/*#__PURE__*/ "; |
| 79 | const SUPPORTED_FILE_RE = /\.(?:m?[jt]sx?|cjs|cts)$/; |
| 80 | |
| 81 | /** |
| 82 | * Rolldown plugin that injects `/*#__PURE__*\/` annotations on top-level |
| 83 | * call/new expressions of modules belonging to the configured packages, |
| 84 | * enabling tree-shaking of `effect`, `@effect/*`, and any user-listed |
| 85 | * packages without requiring a babel post-build pass. |
| 86 | * |
| 87 | * Annotation is strictly explicit: only {@link DEFAULT_PURE_PACKAGES} and |
| 88 | * packages listed via `packages` are touched. Listing a package that |
| 89 | * declares `sideEffects: false` / `[]` is a deliberate opt-in to full |
| 90 | * annotation, including discarded-result statement calls (#949). The |
| 91 | * package owning the bundle entry gets no special treatment — apps that |
| 92 | * want their own bound calls tree-shaken list themselves explicitly. |
| 93 | */ |
| 94 | export const purePlugin = (options: PurePluginOptions = {}): rolldown.Plugin => { |
| 95 | const patterns = options.replaceDefaults |
| 96 | ? [...(options.packages ?? DEFAULT_PURE_PACKAGES)] |
| 97 | : [...DEFAULT_PURE_PACKAGES, ...(options.packages ?? [])]; |
| 98 | const markSideEffectFreeOpt = options.markSideEffectFree ?? true; |
| 99 | const isMatch = picomatch(patterns); |
| 100 | // Per-bundle cache of directory -> owning package metadata. |
| 101 | // Avoids walking the filesystem for every module of a large package. |
| 102 | const pkgInfoCache = new Map<string, PackageInfo | null>(); |
| 103 | // Resolved absolute paths of entry modules. Marking an entry module as |
| 104 | // `moduleSideEffects: false` makes rolldown treat its top-level |
| 105 | // statements (including `console.log` etc.) as eliminable, often |
| 106 | // collapsing the whole bundle. We always preserve entries' side |
| 107 | // effects, regardless of the package they belong to. |
| 108 | const entryPaths = new Set<string>(); |
| 109 | |
| 110 | return { |
| 111 | name: "alchemy:annotate-pure", |
| 112 | options(opts) { |
| 113 | for (const input of inputFilePaths(opts)) entryPaths.add(input); |
| 114 | return null; |
| 115 | }, |
| 116 | transform: { |
| 117 | filter: { id: SUPPORTED_FILE_RE }, |
| 118 | async handler(code, id, meta) { |
| 119 | const cleanId = stripIdSuffix(id); |
| 120 | const info = await resolvePackageInfo(path.dirname(cleanId), pkgInfoCache); |
| 121 | // A nameless package.json (e.g. a nested `dist/package.json` |
| 122 | // holding only `{"type": "module"}`) can't be matched against the |
| 123 | // configured patterns — fall back to the path-derived |
| 124 | // `node_modules/<pkg>` name when one exists. |
| 125 | const name = info?.name ?? packageNameFromId(cleanId); |
| 126 | if (name === null || !isMatch(name)) return null; |
| 127 | |
| 128 | // Only override `moduleSideEffects` when the owning package |
| 129 | // explicitly opts in via `sideEffects: false` / `[]`. Marking |
| 130 | // arbitrary modules side-effect-free could erase intentional |
| 131 | // registrations / mutations the author made at the top level of |
| 132 | // files in packages that did not declare so. |
| 133 | const isEntry = entryPaths.has(cleanId); |
| 134 | const sideEffectFreePkg = isSideEffectFree(info?.sideEffects); |
| 135 | const markSideEffectFree = markSideEffectFreeOpt && !isEntry && sideEffectFreePkg; |
| 136 | |
| 137 | const anchors = await collectPureAnchorsCached(code, cleanId); |
| 138 | // Annotating a call whose result is BOUND (variable initializer, |
| 139 | // export) only lets the minifier drop it when the binding itself |
| 140 | // is unused — safe everywhere. Annotating a call whose result is |
| 141 | // DISCARDED (a bare expression statement like `app.get("/", h)`) |
| 142 | // is an instruction to delete the call under minification, so it |
| 143 | // is only applied when the owning package explicitly declared |
| 144 | // itself side-effect free, and never to entry modules, whose side |
| 145 | // effects we always preserve (#949). |
| 146 | const annotateDiscarded = !isEntry && sideEffectFreePkg; |
| 147 | const positions = |
| 148 | anchors === null |
| 149 | ? [] |
| 150 | : annotateDiscarded |
| 151 | ? [...anchors.bound, ...anchors.discarded] |
| 152 | : anchors.bound; |
| 153 | if (positions.length === 0) { |
| 154 | // Metadata-only result: omitting `code` tells rolldown the |
| 155 | // source was NOT transformed, so no sourcemap is expected and |
| 156 | // no SOURCEMAP_BROKEN warning is emitted. |
| 157 | return markSideEffectFree ? { moduleSideEffects: false } : null; |
| 158 | } |
| 159 | // `meta.magicString` is rolldown's native (Rust) MagicString over |
| 160 | // `code`. Returning it as `code` hands sourcemap generation to |
| 161 | // rolldown's native side (computed on a background thread). The |
| 162 | // fallback covers direct hook invocations (unit tests). |
| 163 | const s = meta.magicString ?? new (await loadRolldown()).RolldownMagicString(code); |
| 164 | for (const anchor of positions) s.appendLeft(anchor, PURE_COMMENT); |
| 165 | return { |
| 166 | code: s, |
| 167 | moduleSideEffects: markSideEffectFree ? false : null, |
| 168 | }; |
| 169 | }, |
| 170 | }, |
| 171 | }; |
| 172 | }; |
| 173 | |
| 174 | /** Strips rolldown's `?query` / `#hash` suffixes from a module id. */ |
| 175 | const stripIdSuffix = (id: string): string => id.replace(/[?#].*$/, ""); |
| 176 | |
| 177 | /** |
| 178 | * Returns the absolute paths of every real entry module declared on the |
| 179 | * rolldown input options. Handles all three input shapes (string, array, |
| 180 | * `{ name -> path }` record) and skips `\0`-prefixed virtual ids (e.g. |
| 181 | * the ones `virtualEntryPlugin` substitutes in its `pre` options hook). |
| 182 | */ |
| 183 | function inputFilePaths(opts: rolldown.InputOptions): string[] { |
| 184 | const raw: unknown[] = |
| 185 | typeof opts.input === "string" |
| 186 | ? [opts.input] |
| 187 | : Array.isArray(opts.input) |
| 188 | ? opts.input |
| 189 | : opts.input && typeof opts.input === "object" |
| 190 | ? Object.values(opts.input) |
| 191 | : []; |
| 192 | const cwd = opts.cwd ?? process.cwd(); |
| 193 | return raw |
| 194 | .filter((entry): entry is string => typeof entry === "string" && !entry.startsWith("\0")) |
| 195 | .map((entry) => path.resolve(cwd, entry)); |
| 196 | } |
| 197 | |
| 198 | /** |
| 199 | * Metadata extracted from a `package.json`. `name` may be `null` when the |
| 200 | * file exists but has no `"name"` field (rare, but possible for private |
| 201 | * subpackage roots). |
| 202 | */ |
| 203 | export interface PackageInfo { |
| 204 | readonly name: string | null; |
| 205 | readonly sideEffects: unknown; |
| 206 | } |
| 207 | |
| 208 | /** |
| 209 | * Resolves the owning {@link PackageInfo} for a directory by walking up |
| 210 | * to the nearest `package.json`. This is what makes the plugin work for |
| 211 | * workspace-linked sources (e.g. our own `packages/alchemy/src/**` when |
| 212 | * consumers import via the `worker`/`bun` conditions which resolve to |
| 213 | * `.ts`). |
| 214 | * |
| 215 | * Caches both positive and negative results per directory. Every visited |
| 216 | * directory is a descendant-or-self of the directory where the walk |
| 217 | * stops (found `package.json`, cache hit, `node_modules` boundary, or |
| 218 | * filesystem root), so backfilling all of them with the result never |
| 219 | * poisons sibling packages. |
| 220 | */ |
| 221 | export async function resolvePackageInfo( |
| 222 | startDir: string, |
| 223 | cache: Map<string, PackageInfo | null>, |
| 224 | ): Promise<PackageInfo | null> { |
| 225 | let dir = path.resolve(startDir); |
| 226 | const visited: string[] = []; |
| 227 | let result: PackageInfo | null = null; |
| 228 | // Hard ceiling to prevent runaway walks on weird paths. |
| 229 | for (let i = 0; i < 64; i++) { |
| 230 | // Never walk above a `node_modules` boundary: the owning package of a |
| 231 | // `node_modules/<pkg>/...` id lives at or below `<pkg>`. Climbing past |
| 232 | // it can latch onto an unrelated package.json higher up (e.g. a stray |
| 233 | // one at the filesystem root). |
| 234 | if (path.basename(dir) === "node_modules") break; |
| 235 | const cached = cache.get(dir); |
| 236 | if (cached !== undefined) { |
| 237 | result = cached; |
| 238 | break; |
| 239 | } |
| 240 | visited.push(dir); |
| 241 | const info = await readPackageJson(path.join(dir, "package.json")); |
| 242 | if (info !== null) { |
| 243 | result = info; |
| 244 | break; |
| 245 | } |
| 246 | const parent = path.dirname(dir); |
| 247 | if (parent === dir) break; |
| 248 | dir = parent; |
| 249 | } |
| 250 | for (const v of visited) cache.set(v, result); |
| 251 | return result; |
| 252 | } |
| 253 | |
| 254 | async function readPackageJson(file: string): Promise<PackageInfo | null> { |
| 255 | try { |
| 256 | const contents = await fs.readFile(file, "utf8"); |
| 257 | const json = JSON.parse(contents) as { |
| 258 | name?: unknown; |
| 259 | sideEffects?: unknown; |
| 260 | }; |
| 261 | return { |
| 262 | name: typeof json.name === "string" ? json.name : null, |
| 263 | sideEffects: json.sideEffects, |
| 264 | }; |
| 265 | } catch { |
| 266 | // package.json missing or unreadable. |
| 267 | return null; |
| 268 | } |
| 269 | } |
| 270 | |
| 271 | /** |
| 272 | * Mirrors how rolldown / rollup interpret the `sideEffects` package.json |
| 273 | * field. We only treat `false` and `[]` as "fully side-effect free"; an |
| 274 | * array of files or `true` is treated as not safe to auto-annotate the |
| 275 | * whole package. |
| 276 | */ |
| 277 | function isSideEffectFree(value: unknown): boolean { |
| 278 | if (value === false) return true; |
| 279 | if (Array.isArray(value) && value.length === 0) return true; |
| 280 | return false; |
| 281 | } |
| 282 | |
| 283 | /** |
| 284 | * Extracts the npm package name from a resolved module id by walking back to |
| 285 | * the last `node_modules/` segment. Handles scoped packages. This is the |
| 286 | * fast path that does not hit the filesystem; it works for ordinary |
| 287 | * `node_modules/<pkg>/...` ids but NOT for workspace-linked sources whose |
| 288 | * resolved path is e.g. `<repo>/packages/alchemy/src/Bundle/PurePlugin.ts`. |
| 289 | * |
| 290 | * @example |
| 291 | * packageNameFromId("/proj/node_modules/effect/dist/Effect.js") |
| 292 | * // => "effect" |
| 293 | * packageNameFromId("/proj/node_modules/@effect/cluster/dist/index.js") |
| 294 | * // => "@effect/cluster" |
| 295 | */ |
| 296 | export function packageNameFromId(id: string): string | null { |
| 297 | const normalized = id.replace(/\\/g, "/"); |
| 298 | const idx = normalized.lastIndexOf("/node_modules/"); |
| 299 | if (idx === -1) return null; |
| 300 | const rest = normalized.slice(idx + "/node_modules/".length); |
| 301 | const parts = rest.split("/"); |
| 302 | if (parts.length === 0 || parts[0] === "") return null; |
| 303 | if (parts[0].startsWith("@")) { |
| 304 | if (parts.length < 2) return null; |
| 305 | return `${parts[0]}/${parts[1]}`; |
| 306 | } |
| 307 | return parts[0]; |
| 308 | } |
| 309 | |
| 310 | /** |
| 311 | * Process-wide memo of {@link collectPureAnchors} results keyed by module id. |
| 312 | * |
| 313 | * Parsing with oxc dominates the plugin's main-thread CPU (it showed up as |
| 314 | * ~60% of the profile of a test run), and the same modules — effect/alchemy |
| 315 | * dist files — are re-scanned for EVERY bundle built in the process. The |
| 316 | * single-process test runner builds dozens of worker bundles per run, so |
| 317 | * this cache eliminates all repeat parses. The stored `code` is compared on |
| 318 | * lookup, so a changed file (e.g. dev watch mode) never serves a stale |
| 319 | * result. |
| 320 | */ |
| 321 | const anchorsCache = new Map< |
| 322 | string, |
| 323 | { readonly code: string; readonly anchors: PureAnchors | null } |
| 324 | >(); |
| 325 | const ANCHORS_CACHE_MAX = 10_000; |
| 326 | |
| 327 | const collectPureAnchorsCached = async ( |
| 328 | code: string, |
| 329 | filename: string, |
| 330 | ): Promise<PureAnchors | null> => { |
| 331 | const cached = anchorsCache.get(filename); |
| 332 | if (cached !== undefined && cached.code === code) { |
| 333 | return cached.anchors; |
| 334 | } |
| 335 | const anchors = await collectPureAnchors(code, filename); |
| 336 | if (anchorsCache.size >= ANCHORS_CACHE_MAX) { |
| 337 | anchorsCache.clear(); |
| 338 | } |
| 339 | anchorsCache.set(filename, { code, anchors }); |
| 340 | return anchors; |
| 341 | }; |
| 342 | |
| 343 | /** |
| 344 | * Offsets at which `/*#__PURE__*\/` may be inserted, split by whether the |
| 345 | * call's result is consumed. |
| 346 | */ |
| 347 | export interface PureAnchors { |
| 348 | /** |
| 349 | * Calls whose result is bound — variable initializers, exports, |
| 350 | * assignment right-hand sides. Annotating these only lets the minifier |
| 351 | * drop the call when the binding itself is unused, so it is safe for |
| 352 | * any module. |
| 353 | */ |
| 354 | readonly bound: number[]; |
| 355 | /** |
| 356 | * Top-level calls whose result is discarded (bare expression |
| 357 | * statements such as `app.get("/", handler)`). Annotating these tells |
| 358 | * the minifier the whole statement is deletable, so they are only safe |
| 359 | * in packages that explicitly declare `sideEffects: false` / `[]`. |
| 360 | */ |
| 361 | readonly discarded: number[]; |
| 362 | } |
| 363 | |
| 364 | /** |
| 365 | * Parses `code` and returns the offsets at which `/*#__PURE__*\/` must be |
| 366 | * inserted — before every top-level `CallExpression` callee / `new` |
| 367 | * keyword — classified by whether the call result is bound or discarded. |
| 368 | * Returns `null` if the file does not need to be modified (parse failure |
| 369 | * or no annotations needed). |
| 370 | */ |
| 371 | export async function collectPureAnchors( |
| 372 | code: string, |
| 373 | filename: string, |
| 374 | ): Promise<PureAnchors | null> { |
| 375 | const { parseAst } = await loadParseAst(); |
| 376 | let program: Program; |
| 377 | try { |
| 378 | // Use TS lang so the parser tolerates TS syntax (`as`, `satisfies`, |
| 379 | // non-null assertions) even when scanning published .js dist files |
| 380 | // — TS is a strict superset of JS for our purposes here. |
| 381 | program = parseAst(code, { sourceType: "module", lang: "ts" }, filename); |
| 382 | } catch { |
| 383 | return null; |
| 384 | } |
| 385 | |
| 386 | const bound: number[] = []; |
| 387 | const discarded: number[] = []; |
| 388 | |
| 389 | const visitCall = (call: CallExpression | NewExpression, isDiscarded: boolean) => { |
| 390 | if (isIIFE(call)) return; |
| 391 | // For `new X()`, anchor BEFORE the `new` keyword so we get |
| 392 | // `/*#__PURE__*/ new X()` (matches babel-plugin-annotate-pure-calls). |
| 393 | const anchor = call.type === "NewExpression" ? call.start : call.callee.start; |
| 394 | if (alreadyAnnotated(code, anchor)) return; |
| 395 | (isDiscarded ? discarded : bound).push(anchor); |
| 396 | }; |
| 397 | |
| 398 | const visitExpression = (expr: Expression | null | undefined, isDiscarded: boolean) => { |
| 399 | if (!expr) return; |
| 400 | switch (expr.type) { |
| 401 | case "CallExpression": |
| 402 | case "NewExpression": |
| 403 | visitCall(expr, isDiscarded); |
| 404 | return; |
| 405 | case "SequenceExpression": { |
| 406 | // All but the last expression's results are always discarded; |
| 407 | // the last one takes the surrounding context. |
| 408 | const exprs = expr.expressions; |
| 409 | for (let i = 0; i < exprs.length; i++) { |
| 410 | visitExpression(exprs[i], i < exprs.length - 1 ? true : isDiscarded); |
| 411 | } |
| 412 | return; |
| 413 | } |
| 414 | case "ParenthesizedExpression": |
| 415 | visitExpression(expr.expression, isDiscarded); |
| 416 | return; |
| 417 | case "LogicalExpression": |
| 418 | visitExpression(expr.left, isDiscarded); |
| 419 | visitExpression(expr.right, isDiscarded); |
| 420 | return; |
| 421 | case "ConditionalExpression": |
| 422 | visitExpression(expr.consequent, isDiscarded); |
| 423 | visitExpression(expr.alternate, isDiscarded); |
| 424 | return; |
| 425 | case "AssignmentExpression": |
| 426 | // The right-hand side's result is stored in the target, so it is |
| 427 | // bound even when the assignment appears in statement position. |
| 428 | visitExpression(expr.right, false); |
| 429 | return; |
| 430 | case "TSAsExpression": |
| 431 | case "TSSatisfiesExpression": |
| 432 | case "TSNonNullExpression": |
| 433 | case "TSTypeAssertion": |
| 434 | visitExpression(expr.expression, isDiscarded); |
| 435 | return; |
| 436 | case "ChainExpression": { |
| 437 | const inner = expr.expression; |
| 438 | if (inner.type === "CallExpression") visitCall(inner, isDiscarded); |
| 439 | return; |
| 440 | } |
| 441 | default: |
| 442 | return; |
| 443 | } |
| 444 | }; |
| 445 | |
| 446 | const visitTopLevel = (node: Statement) => { |
| 447 | switch (node.type) { |
| 448 | case "ExpressionStatement": |
| 449 | visitExpression((node as ExpressionStatement).expression, true); |
| 450 | return; |
| 451 | case "VariableDeclaration": |
| 452 | for (const decl of (node as VariableDeclaration).declarations) { |
| 453 | visitExpression(decl.init, false); |
| 454 | } |
| 455 | return; |
| 456 | case "ExportNamedDeclaration": { |
| 457 | const decl = (node as ExportNamedDeclaration).declaration; |
| 458 | if (decl) visitTopLevel(decl as Statement); |
| 459 | return; |
| 460 | } |
| 461 | case "ExportDefaultDeclaration": { |
| 462 | const decl = (node as ExportDefaultDeclaration).declaration; |
| 463 | if ( |
| 464 | decl && |
| 465 | decl.type !== "FunctionDeclaration" && |
| 466 | decl.type !== "ClassDeclaration" && |
| 467 | decl.type !== "TSInterfaceDeclaration" |
| 468 | ) { |
| 469 | visitExpression(decl as Expression, false); |
| 470 | } |
| 471 | return; |
| 472 | } |
| 473 | default: |
| 474 | return; |
| 475 | } |
| 476 | }; |
| 477 | |
| 478 | for (const node of program.body) { |
| 479 | // Directive nodes (e.g. "use strict") have type "ExpressionStatement" |
| 480 | // with a `directive` field and a string literal expression — they |
| 481 | // cannot contain calls, so visiting them is a safe no-op. |
| 482 | visitTopLevel(node as Statement); |
| 483 | } |
| 484 | |
| 485 | return bound.length === 0 && discarded.length === 0 ? null : { bound, discarded }; |
| 486 | } |
| 487 | |
| 488 | function isIIFE(node: CallExpression | NewExpression): boolean { |
| 489 | let callee: Expression = node.callee; |
| 490 | while (callee.type === "ParenthesizedExpression") { |
| 491 | callee = callee.expression; |
| 492 | } |
| 493 | return callee.type === "FunctionExpression" || callee.type === "ArrowFunctionExpression"; |
| 494 | } |
| 495 | |
| 496 | function alreadyAnnotated(code: string, pos: number): boolean { |
| 497 | const start = Math.max(0, pos - 32); |
| 498 | const slice = code.slice(start, pos); |
| 499 | return slice.includes("/*#__PURE__*/") || slice.includes("/*@__PURE__*/"); |
| 500 | } |