diff --git a/.changeset/filesystem-pure-annotations.md b/.changeset/filesystem-pure-annotations.md new file mode 100644 index 00000000000..490f6f7823b --- /dev/null +++ b/.changeset/filesystem-pure-annotations.md @@ -0,0 +1,5 @@ +--- +"effect": patch +--- + +Annotate the `glob` and `stream` constructors in `FileSystem.make` as pure, so bundlers can drop them when a `FileSystem` implementation's derived methods are unused. diff --git a/packages/effect/src/FileSystem.ts b/packages/effect/src/FileSystem.ts index 964c11fa576..88b36bdabe1 100644 --- a/packages/effect/src/FileSystem.ts +++ b/packages/effect/src/FileSystem.ts @@ -570,7 +570,7 @@ export const make = ( FileSystem.of({ ...impl, [TypeId]: TypeId, - glob: Glob.make(impl), + glob: /* @__PURE__ */ Glob.make(impl), exists: (path) => pipe( impl.access(path), @@ -592,7 +592,7 @@ export const make = ( cause }) })), - stream: Effect.fnUntraced(function*(path, options) { + stream: /* @__PURE__ */ Effect.fnUntraced(function*(path, options) { const file = yield* impl.open(path, { flag: "r" }) const offset = options?.offset === undefined ? undefined : ByteSize.fromInputUnsafe(options.offset) if (offset) { diff --git a/packages/tools/bundle/fixtures/service-shaking/arguments-callbacks.ts b/packages/tools/bundle/fixtures/service-shaking/arguments-callbacks.ts new file mode 100644 index 00000000000..49b48bbaf59 --- /dev/null +++ b/packages/tools/bundle/fixtures/service-shaking/arguments-callbacks.ts @@ -0,0 +1,40 @@ +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +interface Store { + read(): number + unused(): number +} + +// Callbacks that reach their argument through `arguments` instead of a +// declared parameter. +const Consumed = Context.Service("test/ArgumentsConsumer") +const Released = Context.Service("test/ArgumentsRelease") + +const main = () => { + const log: Array = [] + const ReleasedLayer = Layer.effect( + Released, + Effect.acquireRelease( + Effect.sync(() => ({ read: () => 1, unused: () => 2 })), + function() { + // oxlint-disable-next-line prefer-rest-params + const store: Store = arguments[0] + return Effect.sync(() => log.push(`released ${store.unused()}`)) + } + ) + ) + const program = Effect.all([ + // oxlint-disable-next-line prefer-rest-params + Consumed.useSync(function() { + return (arguments[0] as Store).unused() + }), + Released.useSync((s) => s.read()) + ]) + const layers = Layer.mergeAll(Layer.succeed(Consumed, { read: () => 1, unused: () => 2 }), ReleasedLayer) + return Effect.runPromise(Effect.provide(program, layers)).then((results) => [...results, ...log].join(",")) +} + +// A closed program: it exports nothing and prints its result. +main().then((output) => console.log(output)) diff --git a/packages/tools/bundle/fixtures/service-shaking/async-factory.ts b/packages/tools/bundle/fixtures/service-shaking/async-factory.ts new file mode 100644 index 00000000000..6c9f0ce7ab2 --- /dev/null +++ b/packages/tools/bundle/fixtures/service-shaking/async-factory.ts @@ -0,0 +1,27 @@ +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +interface Store { + read(): number + unused(): number +} + +// The service is a Promise. The object literal is its resolved value, not the +// service itself. +const Async = Context.Service>("test/Async") + +async function make(): Promise { + return { read: () => 1, unused: () => 2 } +} + +const main = () => + Effect.runPromise( + Effect.provide( + Async.use((p) => Effect.promise(() => p.then((s) => `${s.read()}`))), + Layer.succeed(Async, make()) + ) + ) + +// A closed program: it exports nothing and prints its result. +main().then((output) => console.log(output)) diff --git a/packages/tools/bundle/fixtures/service-shaking/bailout-escape.ts b/packages/tools/bundle/fixtures/service-shaking/bailout-escape.ts new file mode 100644 index 00000000000..3f21c40d243 --- /dev/null +++ b/packages/tools/bundle/fixtures/service-shaking/bailout-escape.ts @@ -0,0 +1,20 @@ +import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem" +import * as Effect from "effect/Effect" +import * as FileSystem from "effect/FileSystem" + +// A plain computed read, so this fixture only depends on the rule it targets. +const property = (target: object, key: string): any => (target as Record)[key] + +const methodType = (fs: FileSystem.FileSystem, method: string): string => typeof property(fs, method) + +const program = Effect.fnUntraced(function*(path: string, method: string) { + const fs = yield* FileSystem.FileSystem + const bytes = yield* fs.readFile(path) + return `${bytes.length} ${method}: ${methodType(fs, method)}` +}) + +const main = (path: string, method: string): Promise => + Effect.runPromise(Effect.provide(program(path, method), NodeFileSystem.layer)) + +// A closed program: it exports nothing and prints its result. +main(process.argv[2]!, process.argv[3]!).then((output) => console.log(output)) diff --git a/packages/tools/bundle/fixtures/service-shaking/bailout-inspect.ts b/packages/tools/bundle/fixtures/service-shaking/bailout-inspect.ts new file mode 100644 index 00000000000..38d6e45eeb9 --- /dev/null +++ b/packages/tools/bundle/fixtures/service-shaking/bailout-inspect.ts @@ -0,0 +1,14 @@ +import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem" +import * as Effect from "effect/Effect" +import * as FileSystem from "effect/FileSystem" + +const program = Effect.fnUntraced(function*(path: string) { + const fs = yield* FileSystem.FileSystem + const bytes = yield* fs.readFile(path) + return `${bytes.length} ${Object.keys(fs).sort().join(",")}` +}) + +const main = (path: string): Promise => Effect.runPromise(Effect.provide(program(path), NodeFileSystem.layer)) + +// A closed program: it exports nothing and prints its result. +main(process.argv[2]!).then((output) => console.log(output)) diff --git a/packages/tools/bundle/fixtures/service-shaking/bailout-unsafe-key.ts b/packages/tools/bundle/fixtures/service-shaking/bailout-unsafe-key.ts new file mode 100644 index 00000000000..7f65a479946 --- /dev/null +++ b/packages/tools/bundle/fixtures/service-shaking/bailout-unsafe-key.ts @@ -0,0 +1,16 @@ +import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import type * as FileSystem from "effect/FileSystem" + +const program = Effect.fnUntraced(function*(path: string) { + const context = yield* Effect.context() + const fs = Context.getOrUndefinedUnsafe(context, "effect/FileSystem")! + const bytes = yield* fs.readFile(path) + return `${bytes.length} copy: ${typeof fs.copy}` +}) + +const main = (path: string): Promise => Effect.runPromise(Effect.provide(program(path), NodeFileSystem.layer)) + +// A closed program: it exports nothing and prints its result. +main(process.argv[2]!).then((output) => console.log(output)) diff --git a/packages/tools/bundle/fixtures/service-shaking/combinators.ts b/packages/tools/bundle/fixtures/service-shaking/combinators.ts new file mode 100644 index 00000000000..3e2f4b6fadb --- /dev/null +++ b/packages/tools/bundle/fixtures/service-shaking/combinators.ts @@ -0,0 +1,15 @@ +import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem" +import * as Effect from "effect/Effect" +import * as FileSystem from "effect/FileSystem" + +const program = (path: string) => + Effect.all([ + FileSystem.FileSystem.use((fs) => fs.readFile(path)), + Effect.flatMap(FileSystem.FileSystem, (fs) => fs.readFile(path)), + FileSystem.FileSystem.pipe(Effect.flatMap((fs) => fs.readFile(path))) + ]).pipe(Effect.map((results) => results.map((bytes) => bytes.length).join(","))) + +const main = (path: string): Promise => Effect.runPromise(Effect.provide(program(path), NodeFileSystem.layer)) + +// A closed program: it exports nothing and prints its result. +main(process.argv[2]!).then((output) => console.log(output)) diff --git a/packages/tools/bundle/fixtures/service-shaking/constructor-gen.ts b/packages/tools/bundle/fixtures/service-shaking/constructor-gen.ts new file mode 100644 index 00000000000..cb46e38e6b1 --- /dev/null +++ b/packages/tools/bundle/fixtures/service-shaking/constructor-gen.ts @@ -0,0 +1,85 @@ +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +interface Store { + readOne(): string + writeOne(): string +} +interface Dependency { + read(): string + prepare(): string + write(): string +} +interface Audit { + record(): string +} + +// A provider built by a constructor: its methods are local consts, and only +// `writeOne` uses the audit service, the cache and the prepared value. The +// program never calls `writeOne`. +const Store = Context.Service("test/ConstructorGenStore") +const Dependency = Context.Service("test/ConstructorGenDependency") +const Audit = Context.Service("test/ConstructorGenAudit") + +const log: Array = [] + +// Module-scope helpers, so the test can see which ones the bundle keeps. +const dependencyRead = () => "read" +const dependencyPrepare = () => { + log.push("prepared") + return "prepared" +} +const dependencyWrite = () => "write" +const auditRecord = () => "audited" +const constructorWriteHelper = (value: string) => `wrote ${value}` +const makeWriteCache = () => { + log.push("cache made") + return new Map() +} + +const DependencyLayer = Layer.succeed(Dependency, { + read: dependencyRead, + prepare: dependencyPrepare, + write: dependencyWrite +}) +const AuditLayer = Layer.effect( + Audit, + Effect.acquireRelease( + Effect.sync(() => { + log.push("audit acquired") + return { record: auditRecord } + }), + () => Effect.sync(() => log.push("audit released")) + ) +) + +const StoreLayer = Layer.effect( + Store, + Effect.gen(function*() { + const dependency = yield* Dependency + // Acquired while constructing, even though only `writeOne` uses it. + const audit = yield* Audit + yield* Effect.sync(() => log.push("constructed")) + // Runs while constructing: `prepare` is called now, not inside `writeOne`. + const prepared = dependency.prepare() + const cache = makeWriteCache() + const readOne = () => dependency.read() + const writeOne = () => { + cache.set(prepared, dependency.write()) + return constructorWriteHelper(audit.record()) + } + return Store.of({ readOne, writeOne }) + }) +) + +const main = () => + Effect.runPromise( + Effect.provide( + Store.useSync((store) => store.readOne()), + StoreLayer.pipe(Layer.provide(Layer.mergeAll(DependencyLayer, AuditLayer))) + ) + ).then((result) => [result, ...log].join(",")) + +// A closed program: it exports nothing and prints its result. +main().then((output) => console.log(output)) diff --git a/packages/tools/bundle/fixtures/service-shaking/constructor-map.ts b/packages/tools/bundle/fixtures/service-shaking/constructor-map.ts new file mode 100644 index 00000000000..f44b4d5d151 --- /dev/null +++ b/packages/tools/bundle/fixtures/service-shaking/constructor-map.ts @@ -0,0 +1,52 @@ +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +interface Store { + readOne(): string + writeOne(): string +} +interface Dependency { + read(): string + describe(): string + write(): string +} + +// A provider built in an `Effect.map` callback. `describe` is shared by the +// removable `writeOne` and code that runs while constructing. +const Store = Context.Service("test/ConstructorMapStore") +const Dependency = Context.Service("test/ConstructorMapDependency") + +const log: Array = [] + +// Module-scope helpers, so the test can see which ones the bundle keeps. +const dependencyRead = () => "read" +const dependencyDescribe = () => "described" +const dependencyWrite = () => "write" +const constructorWriteHelper = (value: string) => `wrote ${value}` + +const DependencyLayer = Layer.succeed(Dependency, { + read: dependencyRead, + describe: dependencyDescribe, + write: dependencyWrite +}) + +const StoreLayer = Layer.effect( + Store, + Effect.map(Dependency, (dependency) => { + const describe = (label: string) => `${label}:${dependency.describe()}` + // Runs while constructing, so `describe` and `dependency.describe` stay live. + log.push(describe("init")) + const readOne = () => dependency.read() + const writeOne = () => constructorWriteHelper(`${describe("write")}:${dependency.write()}`) + return Store.of({ readOne, writeOne }) + }) +) + +const main = () => + Effect.runPromise( + Effect.provide(Store.useSync((store) => store.readOne()), StoreLayer.pipe(Layer.provide(DependencyLayer))) + ).then((result) => [result, ...log].join(",")) + +// A closed program: it exports nothing and prints its result. +main().then((output) => console.log(output)) diff --git a/packages/tools/bundle/fixtures/service-shaking/context.ts b/packages/tools/bundle/fixtures/service-shaking/context.ts new file mode 100644 index 00000000000..fc1fce0c680 --- /dev/null +++ b/packages/tools/bundle/fixtures/service-shaking/context.ts @@ -0,0 +1,15 @@ +import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as FileSystem from "effect/FileSystem" + +const program = (path: string) => + Effect.context().pipe( + Effect.flatMap((context) => Context.get(context, FileSystem.FileSystem).readFile(path)), + Effect.map((bytes) => `${bytes.length}`) + ) + +const main = (path: string): Promise => Effect.runPromise(Effect.provide(program(path), NodeFileSystem.layer)) + +// A closed program: it exports nothing and prints its result. +main(process.argv[2]!).then((output) => console.log(output)) diff --git a/packages/tools/bundle/fixtures/service-shaking/exported-layer.ts b/packages/tools/bundle/fixtures/service-shaking/exported-layer.ts new file mode 100644 index 00000000000..dec1b9c00c7 --- /dev/null +++ b/packages/tools/bundle/fixtures/service-shaking/exported-layer.ts @@ -0,0 +1,16 @@ +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +interface Store { + read(): number + unused(): number +} + +// The key stays private, but the exported Layer lets code outside the bundle +// build the Context that holds the provider. +const Exported = Context.Service("test/Exported") + +export const layer = Layer.succeed(Exported, { read: () => 1, unused: () => 2 }) + +export const main = () => Effect.runPromise(Effect.provide(Exported.useSync((s) => `${s.read()}`), layer)) diff --git a/packages/tools/bundle/fixtures/service-shaking/external-helper.ts b/packages/tools/bundle/fixtures/service-shaking/external-helper.ts new file mode 100644 index 00000000000..819de5561a8 --- /dev/null +++ b/packages/tools/bundle/fixtures/service-shaking/external-helper.ts @@ -0,0 +1,7 @@ +// Imported by `external-module.ts`. The test marks this module external, so +// the analysis never sees it reading the running Fiber's services. It has no +// imports, so every runtime can load it from the bundle's temporary directory. +export const unusedType = (): string => { + const fiber = (globalThis as Record)["~effect/Fiber/currentFiber"] + return typeof fiber.context.mapUnsafe.get("test/ExternalModule").unused +} diff --git a/packages/tools/bundle/fixtures/service-shaking/external-module.ts b/packages/tools/bundle/fixtures/service-shaking/external-module.ts new file mode 100644 index 00000000000..55264d5afef --- /dev/null +++ b/packages/tools/bundle/fixtures/service-shaking/external-module.ts @@ -0,0 +1,20 @@ +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" +import { unusedType } from "./external-helper.ts" + +interface Store { + read(): number + unused(): number +} + +const External = Context.Service("test/ExternalModule") +const layer = Layer.succeed(External, { read: () => 1, unused: () => 2 }) + +const main = () => + Effect.runPromise( + Effect.provide(Effect.flatMap(External.useSync((s) => s.read()), () => Effect.sync(unusedType)), layer) + ) + +// A closed program: it exports nothing and prints its result. +main().then((output) => console.log(output)) diff --git a/packages/tools/bundle/fixtures/service-shaking/generator.ts b/packages/tools/bundle/fixtures/service-shaking/generator.ts new file mode 100644 index 00000000000..32f9e6a6ddc --- /dev/null +++ b/packages/tools/bundle/fixtures/service-shaking/generator.ts @@ -0,0 +1,14 @@ +import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem" +import * as Effect from "effect/Effect" +import * as FileSystem from "effect/FileSystem" + +const program = Effect.fnUntraced(function*(path: string) { + const fs = yield* FileSystem.FileSystem + const bytes = yield* fs.readFile(path) + return `${bytes.length}` +}) + +const main = (path: string): Promise => Effect.runPromise(Effect.provide(program(path), NodeFileSystem.layer)) + +// A closed program: it exports nothing and prints its result. +main(process.argv[2]!).then((output) => console.log(output)) diff --git a/packages/tools/bundle/fixtures/service-shaking/global-fiber.ts b/packages/tools/bundle/fixtures/service-shaking/global-fiber.ts new file mode 100644 index 00000000000..c49c22fa024 --- /dev/null +++ b/packages/tools/bundle/fixtures/service-shaking/global-fiber.ts @@ -0,0 +1,29 @@ +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// A plain computed read, so this fixture only depends on the rule it targets. +const property = (target: object, key: string): any => (target as Record)[key] + +interface Store { + read(): number + unused(): number +} + +// The running Fiber is published on globalThis under a string key. +const Global = Context.Service("test/GlobalFiber") +const layer = Layer.succeed(Global, { read: () => 1, unused: () => 2 }) + +const unusedType = () => { + const fiber: object = property(globalThis, "~effect/Fiber/currentFiber") + const services: ReadonlyMap = property(property(fiber, "context"), "mapUnsafe") + return typeof property(services.get("test/GlobalFiber")!, "unused") +} + +const main = () => + Effect.runPromise( + Effect.provide(Effect.flatMap(Global.useSync((s) => s.read()), () => Effect.sync(unusedType)), layer) + ) + +// A closed program: it exports nothing and prints its result. +main().then((output) => console.log(output)) diff --git a/packages/tools/bundle/fixtures/service-shaking/inherited-members.ts b/packages/tools/bundle/fixtures/service-shaking/inherited-members.ts new file mode 100644 index 00000000000..4887e49ad50 --- /dev/null +++ b/packages/tools/bundle/fixtures/service-shaking/inherited-members.ts @@ -0,0 +1,23 @@ +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +interface Store { + read(): number + unused(): number +} + +// Members inherited from Object.prototype observe the whole service. +const Inherited = Context.Service("test/Inherited") + +const main = () => + Effect.runPromise( + Effect.provide( + // oxlint-disable-next-line no-prototype-builtins + Inherited.useSync((s) => `${s.read()} ${s.hasOwnProperty("unused")} ${Object.keys(s.valueOf()).join(",")}`), + Layer.succeed(Inherited, { read: () => 1, unused: () => 2 }) + ) + ) + +// A closed program: it exports nothing and prints its result. +main().then((output) => console.log(output)) diff --git a/packages/tools/bundle/fixtures/service-shaking/key-mutation.ts b/packages/tools/bundle/fixtures/service-shaking/key-mutation.ts new file mode 100644 index 00000000000..4c156d1e225 --- /dev/null +++ b/packages/tools/bundle/fixtures/service-shaking/key-mutation.ts @@ -0,0 +1,21 @@ +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +interface Store { + read(): number + unused(): number +} + +// After the write, looking up `Mutated` finds the service provided for `Target`. +const Mutated = Context.Service("test/Mutated") +const Target = Context.Service("test/Target") +;(Mutated as { key: string }).key = Target.key + +const main = () => + Effect.runPromise( + Effect.provide(Mutated.useSync((s) => `${s.read()}`), Layer.succeed(Target, { read: () => 1, unused: () => 2 })) + ) + +// A closed program: it exports nothing and prints its result. +main().then((output) => console.log(output)) diff --git a/packages/tools/bundle/fixtures/service-shaking/logger-fiber.ts b/packages/tools/bundle/fixtures/service-shaking/logger-fiber.ts new file mode 100644 index 00000000000..1e50b255da7 --- /dev/null +++ b/packages/tools/bundle/fixtures/service-shaking/logger-fiber.ts @@ -0,0 +1,28 @@ +import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem" +import * as Effect from "effect/Effect" +import * as FileSystem from "effect/FileSystem" +import * as Layer from "effect/Layer" +import * as Logger from "effect/Logger" + +// A plain computed read, so this fixture only depends on the rule it targets. +const property = (target: object, key: string): any => (target as Record)[key] + +// A logger receives the current Fiber, whose Context holds the FileSystem. +const seen: Array = [] +const logger = Logger.make((options) => { + const services: ReadonlyMap = property(property(options.fiber, "context"), "mapUnsafe") + seen.push(`copy: ${typeof property(services.get("effect/FileSystem")!, "copy")}`) +}) + +const program = Effect.fnUntraced(function*(path: string) { + const fs = yield* FileSystem.FileSystem + const bytes = yield* fs.readFile(path) + yield* Effect.log("read") + return `${bytes.length} ${seen.join(",")}` +}) + +const main = (path: string): Promise => + Effect.runPromise(Effect.provide(program(path), Layer.mergeAll(NodeFileSystem.layer, Logger.layer([logger])))) + +// A closed program: it exports nothing and prints its result. +main(process.argv[2]!).then((output) => console.log(output)) diff --git a/packages/tools/bundle/fixtures/service-shaking/mutable-receiver.ts b/packages/tools/bundle/fixtures/service-shaking/mutable-receiver.ts new file mode 100644 index 00000000000..efe5ce8722e --- /dev/null +++ b/packages/tools/bundle/fixtures/service-shaking/mutable-receiver.ts @@ -0,0 +1,29 @@ +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +interface Store { + read(): number + unused(): number +} + +// `read` is reassigned before the provider is built, so its original +// declaration says nothing about what it reads through `this`. +function read(): number { + return 1 +} +// @ts-expect-error reassigning a function declaration is valid JavaScript +// oxlint-disable-next-line no-func-assign +read = function(this: Store) { + return this.unused() +} + +const Receiver = Context.Service("test/MutableReceiver") + +const main = () => + Effect.runPromise( + Effect.provide(Receiver.useSync((s) => `${s.read()}`), Layer.succeed(Receiver, { read, unused: () => 2 })) + ) + +// A closed program: it exports nothing and prints its result. +main().then((output) => console.log(output)) diff --git a/packages/tools/bundle/fixtures/service-shaking/nested-providers.ts b/packages/tools/bundle/fixtures/service-shaking/nested-providers.ts new file mode 100644 index 00000000000..5ac06687fad --- /dev/null +++ b/packages/tools/bundle/fixtures/service-shaking/nested-providers.ts @@ -0,0 +1,24 @@ +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +interface Store { + read(): number + unused(): number +} + +// The removed `unused` method contains another provider whose `b` method is +// removed too. +const Outer = Context.Service("test/NestedOuter") +const Inner = Context.Service<{ a(): number; b(): number }>("test/NestedInner") + +const layer = Layer.succeed(Outer, { + read: () => 1, + unused: () => + Effect.runSync(Effect.provide(Inner.useSync((s) => s.a()), Layer.succeed(Inner, { a: () => 3, b: () => 4 }))) +}) + +const main = () => Effect.runPromise(Effect.provide(Outer.useSync((s) => `${s.read()}`), layer)) + +// A closed program: it exports nothing and prints its result. +main().then((output) => console.log(output)) diff --git a/packages/tools/bundle/fixtures/service-shaking/on-fiber-start.ts b/packages/tools/bundle/fixtures/service-shaking/on-fiber-start.ts new file mode 100644 index 00000000000..6ff439940b9 --- /dev/null +++ b/packages/tools/bundle/fixtures/service-shaking/on-fiber-start.ts @@ -0,0 +1,29 @@ +import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem" +import * as Effect from "effect/Effect" +import * as FileSystem from "effect/FileSystem" + +// A plain computed read, so this fixture only depends on the rule it targets. +const property = (target: object, key: string): any => (target as Record)[key] + +// `onFiberStart` hands the running Fiber, and so its Context, to user code. +let fiber: object | undefined +const copyType = () => { + const services: ReadonlyMap = property(property(fiber!, "context"), "mapUnsafe") + return typeof property(services.get("effect/FileSystem")!, "copy") +} + +const program = Effect.fnUntraced(function*(path: string) { + const fs = yield* FileSystem.FileSystem + const bytes = yield* fs.readFile(path) + return `${bytes.length} copy: ${copyType()}` +}) + +const main = (path: string): Promise => + Effect.runPromise(Effect.provide(program(path), NodeFileSystem.layer), { + onFiberStart: (started) => { + fiber = started + } + }) + +// A closed program: it exports nothing and prints its result. +main(process.argv[2]!).then((output) => console.log(output)) diff --git a/packages/tools/bundle/fixtures/service-shaking/overrides.ts b/packages/tools/bundle/fixtures/service-shaking/overrides.ts new file mode 100644 index 00000000000..0671f8f9c4a --- /dev/null +++ b/packages/tools/bundle/fixtures/service-shaking/overrides.ts @@ -0,0 +1,43 @@ +import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem" +import * as Effect from "effect/Effect" +import * as FileSystem from "effect/FileSystem" +import * as Layer from "effect/Layer" + +const program = (path: string) => { + const log: Array = [] + + const readLength = Effect.gen(function*() { + const fs = yield* FileSystem.FileSystem + const bytes = yield* fs.readFile(path) + return bytes.length + }) + + const Mock = Layer.effect( + FileSystem.FileSystem, + Effect.acquireRelease( + Effect.sync(() => { + log.push("mock acquired") + return FileSystem.makeNoop({ readFile: () => Effect.succeed(new Uint8Array(3)) }) + }), + () => Effect.sync(() => log.push("mock released")) + ) + ) + + return Effect.gen(function*() { + log.push(`node ${yield* readLength}`) + log.push(`mock ${yield* Effect.provide(readLength, Mock)}`) + const updated = yield* readLength.pipe( + Effect.updateService(FileSystem.FileSystem, (fs) => ({ + ...fs, + readFile: (path) => Effect.map(fs.readFile(path), (bytes) => bytes.subarray(1)) + })) + ) + log.push(`updated ${updated}`) + return log.join("\n") + }) +} + +const main = (path: string): Promise => Effect.runPromise(Effect.provide(program(path), NodeFileSystem.layer)) + +// A closed program: it exports nothing and prints its result. +main(process.argv[2]!).then((output) => console.log(output)) diff --git a/packages/tools/bundle/fixtures/service-shaking/receiver-method.ts b/packages/tools/bundle/fixtures/service-shaking/receiver-method.ts new file mode 100644 index 00000000000..b9210a8f02e --- /dev/null +++ b/packages/tools/bundle/fixtures/service-shaking/receiver-method.ts @@ -0,0 +1,23 @@ +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +interface Store { + read(): number + unused(): number +} + +// `read` is not an inline method, but still reads `unused` through `this`. +function read(this: Store): number { + return this.unused() +} + +const Receiver = Context.Service("test/Receiver") + +const main = () => + Effect.runPromise( + Effect.provide(Receiver.useSync((s) => `${s.read()}`), Layer.succeed(Receiver, { read, unused: () => 2 })) + ) + +// A closed program: it exports nothing and prints its result. +main().then((output) => console.log(output)) diff --git a/packages/tools/bundle/fixtures/service-shaking/redactable-option.ts b/packages/tools/bundle/fixtures/service-shaking/redactable-option.ts new file mode 100644 index 00000000000..529b21765e0 --- /dev/null +++ b/packages/tools/bundle/fixtures/service-shaking/redactable-option.ts @@ -0,0 +1,35 @@ +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +interface Store { + read(): number + unused(): number +} +import * as Option from "effect/Option" + +// A plain computed read, so this fixture only depends on the rule it targets. +const property = (target: object, key: string): any => (target as Record)[key] + +// Formatting an Option calls the Redactable protocol, which receives the +// current Fiber's Context. +const Redacted = Context.Service("test/RedactableOption") +const layer = Layer.succeed(Redacted, { read: () => 1, unused: () => 2 }) + +const payload = { + [Symbol.for("~effect/Redactable")](context: object) { + const services: ReadonlyMap = property(context, "mapUnsafe") + return typeof property(services.get("test/RedactableOption")!, "unused") + } +} + +const main = () => + Effect.runPromise( + Effect.provide( + Effect.flatMap(Redacted.useSync((s) => s.read()), () => Effect.sync(() => Option.some(payload).toString())), + layer + ) + ) + +// A closed program: it exports nothing and prints its result. +main().then((output) => console.log(output)) diff --git a/packages/tools/bundle/fixtures/service-shaking/release-and-tap.ts b/packages/tools/bundle/fixtures/service-shaking/release-and-tap.ts new file mode 100644 index 00000000000..166fc8a658c --- /dev/null +++ b/packages/tools/bundle/fixtures/service-shaking/release-and-tap.ts @@ -0,0 +1,37 @@ +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +interface Store { + read(): number + unused(): number +} + +// The acquired value reaches the release callback and a tap callback, which +// both call a method no consumer of the service reads. +const Released = Context.Service("test/Released") +const Tapped = Context.Service("test/Tapped") + +const main = () => { + const log: Array = [] + const ReleasedLayer = Layer.effect( + Released, + Effect.acquireRelease( + Effect.sync(() => ({ read: () => 1, unused: () => 2 })), + (store) => Effect.sync(() => log.push(`released ${store.unused()}`)) + ) + ) + const TappedLayer = Layer.effect( + Tapped, + Effect.sync(() => ({ read: () => 1, unused: () => 2 })).pipe( + Effect.tap((store) => Effect.sync(() => log.push(`tapped ${store.unused()}`))) + ) + ) + const program = Effect.all([Released.useSync((s) => s.read()), Tapped.useSync((s) => s.read())]) + return Effect.runPromise(Effect.provide(program, Layer.mergeAll(ReleasedLayer, TappedLayer))).then((reads) => + [...reads, ...log].join(",") + ) +} + +// A closed program: it exports nothing and prints its result. +main().then((output) => console.log(output)) diff --git a/packages/tools/bundle/fixtures/service-shaking/resolution-drift-a.ts b/packages/tools/bundle/fixtures/service-shaking/resolution-drift-a.ts new file mode 100644 index 00000000000..eab86312ab3 --- /dev/null +++ b/packages/tools/bundle/fixtures/service-shaking/resolution-drift-a.ts @@ -0,0 +1,4 @@ +import * as Context from "effect/Context" +import type { Store } from "./resolution-drift-layer.ts" + +export const Key = Context.Service("test/ResolutionA") diff --git a/packages/tools/bundle/fixtures/service-shaking/resolution-drift-b.ts b/packages/tools/bundle/fixtures/service-shaking/resolution-drift-b.ts new file mode 100644 index 00000000000..e4fdd8d0eee --- /dev/null +++ b/packages/tools/bundle/fixtures/service-shaking/resolution-drift-b.ts @@ -0,0 +1,4 @@ +import * as Context from "effect/Context" +import type { Store } from "./resolution-drift-layer.ts" + +export const Key = Context.Service("test/ResolutionB") diff --git a/packages/tools/bundle/fixtures/service-shaking/resolution-drift-layer.ts b/packages/tools/bundle/fixtures/service-shaking/resolution-drift-layer.ts new file mode 100644 index 00000000000..3c3637556f5 --- /dev/null +++ b/packages/tools/bundle/fixtures/service-shaking/resolution-drift-layer.ts @@ -0,0 +1,14 @@ +import * as Layer from "effect/Layer" +import { Key as A } from "./resolution-drift-a.ts" +import { Key as B } from "./resolution-drift-b.ts" + +export interface Store { + read(): number + unused(): number +} + +// Provides both keys, so both key modules are in every build. +export const layer = Layer.mergeAll( + Layer.succeed(A, { read: () => 1, unused: () => 2 }), + Layer.succeed(B, { read: () => 1, unused: () => 2 }) +) diff --git a/packages/tools/bundle/fixtures/service-shaking/resolution-drift.ts b/packages/tools/bundle/fixtures/service-shaking/resolution-drift.ts new file mode 100644 index 00000000000..8a7d58a1246 --- /dev/null +++ b/packages/tools/bundle/fixtures/service-shaking/resolution-drift.ts @@ -0,0 +1,10 @@ +import * as Effect from "effect/Effect" +import { Key } from "./resolution-drift-a.ts" +import { layer } from "./resolution-drift-layer.ts" + +// The test resolves this module's `Key` import to `resolution-drift-b.ts` in +// the second build only. Every module's source is the same in both builds. +const main = () => Effect.runPromise(Effect.provide(Key.useSync((s) => `${s.read()}`), layer)) + +// A closed program: it exports nothing and prints its result. +main().then((output) => console.log(output)) diff --git a/packages/tools/bundle/fixtures/service-shaking/run-fork-hook.ts b/packages/tools/bundle/fixtures/service-shaking/run-fork-hook.ts new file mode 100644 index 00000000000..22f606cbc96 --- /dev/null +++ b/packages/tools/bundle/fixtures/service-shaking/run-fork-hook.ts @@ -0,0 +1,32 @@ +import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem" +import * as Effect from "effect/Effect" +import * as FileSystem from "effect/FileSystem" + +// A plain computed read, so this fixture only depends on the rule it targets. +const property = (target: object, key: string): any => (target as Record)[key] + +// The fiber returned by `runFork` is discarded, but `onFiberStart` still +// hands it to user code. +let fiber: object | undefined +const copyType = () => { + const services: ReadonlyMap = property(property(fiber!, "context"), "mapUnsafe") + return typeof property(services.get("effect/FileSystem")!, "copy") +} + +const program = Effect.fnUntraced(function*(path: string) { + const fs = yield* FileSystem.FileSystem + const bytes = yield* fs.readFile(path) + return `${bytes.length} copy: ${copyType()}` +}) + +const main = (path: string): Promise => + new Promise((resolve) => { + Effect.runFork(Effect.provide(Effect.map(program(path), resolve), NodeFileSystem.layer), { + onFiberStart: (started) => { + fiber = started + } + }) + }) + +// A closed program: it exports nothing and prints its result. +main(process.argv[2]!).then((output) => console.log(output)) diff --git a/packages/tools/bundle/fixtures/service-shaking/scope-effect-input.ts b/packages/tools/bundle/fixtures/service-shaking/scope-effect-input.ts new file mode 100644 index 00000000000..133b6d7b31e --- /dev/null +++ b/packages/tools/bundle/fixtures/service-shaking/scope-effect-input.ts @@ -0,0 +1,16 @@ +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +interface Store { + read(): number + unused(): number +} + +// The exported function runs an Effect supplied by the importer inside the +// provider's scope. +const Scoped = Context.Service("test/ScopeEffectInput") +const layer = Layer.succeed(Scoped, { read: () => 1, unused: () => 2 }) + +export const main = (input: Effect.Effect): Promise => + Effect.runPromise(Effect.provide(Effect.flatMap(Scoped.useSync((s) => s.read()), () => input), layer)) diff --git a/packages/tools/bundle/fixtures/service-shaking/scope-exported-effect.ts b/packages/tools/bundle/fixtures/service-shaking/scope-exported-effect.ts new file mode 100644 index 00000000000..9216dc68489 --- /dev/null +++ b/packages/tools/bundle/fixtures/service-shaking/scope-exported-effect.ts @@ -0,0 +1,15 @@ +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +interface Store { + read(): number + unused(): number +} + +// The exported Effect logs inside the provider's scope, so the importer's +// logger sees the Fiber holding the service. +const Scoped = Context.Service("test/ScopeExportedEffect") +const layer = Layer.succeed(Scoped, { read: () => 1, unused: () => 2 }) + +export const program = Effect.provide(Scoped.use((s) => Effect.log(s.read())), layer) diff --git a/packages/tools/bundle/fixtures/service-shaking/scope-layer-input.ts b/packages/tools/bundle/fixtures/service-shaking/scope-layer-input.ts new file mode 100644 index 00000000000..58ab661e3d3 --- /dev/null +++ b/packages/tools/bundle/fixtures/service-shaking/scope-layer-input.ts @@ -0,0 +1,16 @@ +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +interface Store { + read(): number + unused(): number +} + +// The exported function builds a Layer supplied by the importer with the +// provider's services. +const Scoped = Context.Service("test/ScopeLayerInput") +const layer = Layer.succeed(Scoped, { read: () => 1, unused: () => 2 }) + +export const main = (input: Layer.Layer): Promise => + Effect.runPromise(Effect.provide(Scoped.useSync((s) => s.read()), Layer.provideMerge(input, layer))) diff --git a/packages/tools/bundle/fixtures/service-shaking/scope-transformer.ts b/packages/tools/bundle/fixtures/service-shaking/scope-transformer.ts new file mode 100644 index 00000000000..2f259870b32 --- /dev/null +++ b/packages/tools/bundle/fixtures/service-shaking/scope-transformer.ts @@ -0,0 +1,17 @@ +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +interface Store { + read(): number + unused(): number +} + +// The exported transformer provides the service to any Effect the importer +// passes it. +const Scoped = Context.Service("test/ScopeTransformer") +const layer = Layer.succeed(Scoped, { read: () => 1, unused: () => 2 }) + +export const supply = Effect.provide(layer) + +export const main = () => Effect.runPromise(supply(Scoped.useSync((s) => `${s.read()}`))) diff --git a/packages/tools/bundle/fixtures/service-shaking/second-pass-drift-layer.ts b/packages/tools/bundle/fixtures/service-shaking/second-pass-drift-layer.ts new file mode 100644 index 00000000000..ec419348698 --- /dev/null +++ b/packages/tools/bundle/fixtures/service-shaking/second-pass-drift-layer.ts @@ -0,0 +1,13 @@ +import * as Context from "effect/Context" +import * as Layer from "effect/Layer" + +export interface Store { + read(): number + unused(): number +} + +// Provider for `second-pass-drift.ts`, kept in its own module so the edited +// module and the consumer that drifts are different files. +export const Drift = Context.Service("test/Drift") + +export const layer = Layer.succeed(Drift, { read: () => 1, unused: () => 2 }) diff --git a/packages/tools/bundle/fixtures/service-shaking/second-pass-drift.ts b/packages/tools/bundle/fixtures/service-shaking/second-pass-drift.ts new file mode 100644 index 00000000000..528ac2589a5 --- /dev/null +++ b/packages/tools/bundle/fixtures/service-shaking/second-pass-drift.ts @@ -0,0 +1,8 @@ +import * as Effect from "effect/Effect" +import { Drift, layer } from "./second-pass-drift-layer.ts" + +// In the second build only, the test makes this consumer call `unused` instead of `read`. +const main = () => Effect.runPromise(Effect.provide(Drift.useSync((s) => `${s.read()}`), layer)) + +// A closed program: it exports nothing and prints its result. +main().then((output) => console.log(output)) diff --git a/packages/tools/bundle/fixtures/service-shaking/separator-comment.ts b/packages/tools/bundle/fixtures/service-shaking/separator-comment.ts new file mode 100644 index 00000000000..8ed9b19530d --- /dev/null +++ b/packages/tools/bundle/fixtures/service-shaking/separator-comment.ts @@ -0,0 +1,23 @@ +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +interface Store { + read(): number + unused(): number +} + +// A comment sits between the removed property and its comma. +const Commented = Context.Service("test/Commented") + +const main = () => + Effect.runPromise( + Effect.provide( + Commented.useSync((s) => `${s.read()}`), + // dprint-ignore + Layer.succeed(Commented, { unused: () => 2 /* comment */, read: () => 1 }) + ) + ) + +// A closed program: it exports nothing and prints its result. +main().then((output) => console.log(output)) diff --git a/packages/tools/bundle/package.json b/packages/tools/bundle/package.json index 5044898d1f1..5678b3d9852 100644 --- a/packages/tools/bundle/package.json +++ b/packages/tools/bundle/package.json @@ -41,6 +41,7 @@ "@rollup/plugin-terser": "^1.0.2", "effect": "workspace:^", "glob": "^14.0.3", + "rolldown": "^1.2.16", "rollup": "^4.67.3", "rollup-plugin-esbuild": "^6.2.1", "rollup-plugin-visualizer": "^7.1.1" diff --git a/packages/tools/bundle/src/ServiceShaking.ts b/packages/tools/bundle/src/ServiceShaking.ts new file mode 100644 index 00000000000..71cee005cc9 --- /dev/null +++ b/packages/tools/bundle/src/ServiceShaking.ts @@ -0,0 +1,289 @@ +/** + * Experimental Rolldown bundling that removes unused methods from Effect + * service implementations. + * + * Rolldown only tree-shakes top-level statements and ES module namespace + * members, so a provider object such as the `FileSystem` built by + * `NodeFileSystem.layer` keeps every method, and every module-scope helper + * those methods reference, even when the program only calls `readFile`. + * + * `bundle` runs two Rolldown builds. The first records every module after the + * other plugins have transformed it, and an analysis computes which methods + * are read from each service key. The second build deletes the properties of + * provider object literals that no consumer can observe, and Rolldown's + * statement-level shaker drops the helpers that only those properties used. + * + * The analysis is conservative. Any use of a service key it does not + * recognise keeps every method of that service. A Context, or a Fiber through + * its public `context`, lets code retrieve any service by its key string, so + * untrusted code may only use an audited list of trusted APIs that never hand + * either out; anything else disables pruning entirely. + * Trusted packages (`effect` and the platform packages by default) are assumed + * not to inspect service values or hand out a Context or Fiber internally. + * The code of trusted packages is not checked against that assumption. + * + * Only closed programs are optimized. The entry module may export nothing but + * primitive constants, every import must be analysed (Node builtins aside), + * and untrusted code may not reach the global object, `Reflect`, `Proxy`, + * `Symbol.for` or symbol-revealing `Object` APIs, because the running Fiber is + * published on the global object and protocol symbols hand out its Context. + * The global built-ins are assumed not to be modified by code outside the bundle. + * + * @since 4.0.0 + */ +import * as fs from "node:fs" +import { builtinModules } from "node:module" +import * as path from "node:path" +import { type InputOptions, type OutputChunk, type Plugin, rolldown } from "rolldown" +import { parseSync } from "rolldown/utils" +import { type Analysis, analyze, type Edit, type ModuleInput } from "./internal/analysis.ts" +import type { Node } from "./internal/scope.ts" + +/** + * Outcome of the service analysis for one bundle. + * + * @category models + * @since 4.0.0 + */ +export interface Report { + /** Reasons the analysis disabled pruning for the whole bundle. */ + readonly globalBailouts: ReadonlyArray + /** Reasons individual service keys keep every method. */ + readonly keyBailouts: ReadonlyMap> + /** Methods read from each service key, or `"all"`. */ + readonly demand: ReadonlyMap | "all"> + /** Removed provider properties, as `module:property`. */ + readonly removed: ReadonlyArray + /** Whether the pruned build was used. */ + readonly applied: boolean +} + +/** + * Options for {@link bundle}. + * + * @category models + * @since 4.0.0 + */ +export interface BundleOptions { + /** + * Package names whose modules may use Context and Fiber APIs internally + * without disabling the optimization. + */ + readonly trustedPackages?: ReadonlyArray | undefined + readonly onReport?: ((report: Report) => void) | undefined +} + +const defaultTrustedPackages = [ + "effect", + "@effect/platform-node", + "@effect/platform-node-shared", + "@effect/platform-bun", + "@effect/platform-deno", + "@effect/platform-browser" +] + +interface Collected { + readonly code: string + readonly program: Node + readonly comments: ModuleInput["comments"] + readonly resolved: Map + readonly externalImports: ReadonlyArray + /** Every import and how it resolved, to detect a different second build. */ + readonly resolution: string +} + +type ResolveContext = { + readonly resolve: (source: string, importer: string) => Promise<{ id: string; external: unknown } | null> +} + +const isBuiltin = (source: string) => source.startsWith("node:") || builtinModules.includes(source) + +const resolveImports = async (context: ResolveContext, program: Node, id: string) => { + const resolved = new Map() + const externalImports: Array = [] + const resolution: Array = [] + for (const source of sourcesOf(program)) { + const result = await context.resolve(source, id) + resolution.push(`${source}\0${result?.id}\0${result?.external}`) + if (result && !result.external) resolved.set(source, result.id) + else if (!isBuiltin(result?.id ?? source)) externalImports.push(source) + } + return { resolved, externalImports, resolution: resolution.join("\n") } +} + +// The module type reflects earlier transforms, e.g. TypeScript already lowered to JavaScript. +const languageOf = (moduleType: string): "js" | "jsx" | "ts" | "tsx" => + /(?:^|\.)[cm]?tsx$/.test(moduleType) + ? "tsx" + : /(?:^|\.)[cm]?ts$/.test(moduleType) + ? "ts" + : /(?:^|\.)jsx$/.test(moduleType) + ? "jsx" + : "js" + +const sourcesOf = (program: Node): Array => { + const sources: Array = [] + const visit = (node: Node) => { + if ( + (node.type === "ImportDeclaration" || node.type === "ExportNamedDeclaration" || + node.type === "ExportAllDeclaration" || node.type === "ImportExpression") && + node.source?.type === "Literal" && typeof node.source.value === "string" + ) { + sources.push(node.source.value) + } + for (const key in node) { + const value = node[key] + if (Array.isArray(value)) { + for (const item of value) if (item && typeof item.type === "string") visit(item) + } else if (value && typeof value.type === "string") { + visit(value) + } + } + } + visit(program) + return sources +} + +interface PackageInfo { + readonly name: string + readonly root: string +} + +const packageOf = (() => { + const cache = new Map() + const lookup = (dir: string): PackageInfo | undefined => { + if (cache.has(dir)) return cache.get(dir) + let info: PackageInfo | undefined + const file = path.join(dir, "package.json") + if (fs.existsSync(file)) { + info = { name: JSON.parse(fs.readFileSync(file, "utf8")).name, root: dir } + } else { + const parent = path.dirname(dir) + info = parent === dir ? undefined : lookup(parent) + } + cache.set(dir, info) + return info + } + return (id: string) => path.isAbsolute(id) ? lookup(path.dirname(id)) : undefined +})() + +// How a trusted module's exports are named in the analysis allow-list: +// `Effect.map` for the effect package, `@effect/platform-node/NodeRuntime.runMain` otherwise. +const apiPrefixOf = (id: string, info: PackageInfo): string => { + const module = path.relative(info.root, id).split(path.sep).join("/") + .replace(/^(?:src|dist)\//, "") + .replace(/\.[cm]?[jt]sx?$/, "") + return info.name === "effect" ? module : `${info.name}/${module}` +} + +const applyEdits = (code: string, edits: ReadonlyArray): string => { + let out = code + for (const edit of [...edits].sort((a, b) => b.start - a.start)) { + out = out.slice(0, edit.start) + out.slice(edit.end) + } + return out +} + +const build = async (options: InputOptions, plugin: Plugin): Promise => { + const bundle = await rolldown({ ...options, plugins: [options.plugins, plugin] }) + try { + const { output } = await bundle.generate({ format: "esm" }) + return output[0] + } finally { + await bundle.close() + } +} + +/** + * Bundles a single entrypoint as ESM and returns the generated code, removing + * service methods the bundled program cannot observe. + * + * @category bundling + * @since 4.0.0 + */ +export const bundle = async (options: InputOptions, bundleOptions: BundleOptions = {}): Promise => { + const trusted = new Set(bundleOptions.trustedPackages ?? defaultTrustedPackages) + const collected = new Map() + const parseFailures: Array = [] + + const collect: Plugin = { + name: "effect-service-shaking:collect", + transform: { + order: "post", + async handler(code, id, meta) { + const parsed = parseSync(id, code, { lang: languageOf(meta.moduleType ?? id) }) + if (parsed.errors.length > 0) { + parseFailures.push(`${id}: ${parsed.errors[0].message}`) + return null + } + const program = parsed.program as unknown as Node + collected.set(id, { + code, + program, + comments: parsed.comments, + ...(await resolveImports(this, program, id)) + }) + return null + } + } + } + const first = await build(options, collect) + + const report = (analysis: Pick, applied: boolean) => + bundleOptions.onReport?.({ ...analysis, applied }) + + if (parseFailures.length > 0) { + report({ globalBailouts: parseFailures, keyBailouts: new Map(), demand: new Map(), removed: [] }, false) + return first.code + } + + const trustOf = (id: string) => { + const info = packageOf(id) + return info !== undefined && trusted.has(info.name) + ? { trusted: true, apiPrefix: apiPrefixOf(id, info) } + : { trusted: false } + } + const analysis: Analysis = analyze( + [...collected].map(([id, module]) => ({ + id, + ...module, + isEntry: first.facadeModuleId === id, + rendered: (first.modules[id]?.renderedLength ?? 0) > 0, + ...trustOf(id) + })) + ) + if (analysis.edits.size === 0) { + report(analysis, false) + return first.code + } + + // Edits are offsets into the code seen in the first build, and demand was + // computed from every module of that build. If any module transforms + // differently the second time, neither can be trusted. + let mismatch = false + const seen = new Set() + const prune: Plugin = { + name: "effect-service-shaking:prune", + transform: { + order: "post", + async handler(code, id) { + seen.add(id) + const first = collected.get(id) + if (first === undefined || first.code !== code) { + mismatch = true + return null + } + if ((await resolveImports(this, first.program, id)).resolution !== first.resolution) { + mismatch = true + return null + } + const edits = analysis.edits.get(id) + return edits === undefined ? null : { code: applyEdits(code, edits) } + } + } + } + const second = await build(options, prune) + if (seen.size !== collected.size) mismatch = true + report(analysis, !mismatch) + return mismatch ? first.code : second.code +} diff --git a/packages/tools/bundle/src/internal/analysis.ts b/packages/tools/bundle/src/internal/analysis.ts new file mode 100644 index 00000000000..873ac8dd539 --- /dev/null +++ b/packages/tools/bundle/src/internal/analysis.ts @@ -0,0 +1,1734 @@ +/** + * Key-level demand analysis for Effect services. + * + * Demand is attached to the string key of a service, not to objects. Every + * syntactic use of a service key must match a recognised consumer, provider + * or neutral pattern, otherwise the key "bails" and keeps every method. Object + * literals are only pruned when a bounded syntactic flow proves they reach a + * Context solely through recognised insertion sites, every callback that sees + * them is accounted for, and the Layer or Context holding them stays inside + * the bundle. + * + * A whole Context, or a Fiber through its public `context`, lets code retrieve + * any service by its key string, bypassing the key-level demand. Untrusted code + * may therefore only reference audited trusted APIs, may not use reflection that reaches the global object or protocol + * symbols, and the entry module may only export primitive constants. Anything + * else disables pruning for the whole bundle. + * + * @internal + */ +import { analyzeScopes, type Binding, children, isFunctionNode, type ModuleScope, type Node } from "./scope.ts" + +/** @internal */ +export interface ModuleInput { + readonly id: string + readonly code: string + readonly program: Node + readonly comments: ReadonlyArray<{ readonly start: number; readonly end: number; readonly value: string }> + /** Resolved module ids by import specifier. External or unresolved specifiers are absent. */ + readonly resolved: ReadonlyMap + readonly isEntry: boolean + /** Whether the module is rendered in the unoptimized bundle. Only rendered modules can run. */ + readonly rendered: boolean + /** Trusted modules may use Context and Fiber APIs internally (the compiler contract). */ + readonly trusted: boolean + /** For trusted modules, the prefix of their exports in `allowedApis`, e.g. `Effect`. */ + readonly apiPrefix?: string | undefined + /** Imports left external other than Node builtins, or that did not resolve. */ + readonly externalImports?: ReadonlyArray | undefined +} + +/** @internal */ +export interface Edit { + readonly start: number + readonly end: number +} + +/** @internal */ +export interface Analysis { + readonly edits: ReadonlyMap> + /** Why the analysis gave up on everything, if it did. */ + readonly globalBailouts: ReadonlyArray + /** Why individual service keys keep every method. */ + readonly keyBailouts: ReadonlyMap> + /** Demanded method names per service key, or "all". */ + readonly demand: ReadonlyMap | "all"> + /** Removed properties, as `module:key`. */ + readonly removed: ReadonlyArray +} + +interface Module { + readonly input: ModuleInput + readonly scope: ModuleScope + readonly exports: Map + readonly stars: Array +} + +type ExportTarget = + | { readonly _tag: "Local"; readonly local: string } + | { readonly _tag: "Reexport"; readonly source: string; readonly imported: string } + | { readonly _tag: "Namespace"; readonly source: string } + | { readonly _tag: "Expression" } + +type Sym = + | { readonly _tag: "Binding"; readonly module: Module; readonly binding: Binding } + | { readonly _tag: "Namespace"; readonly module: Module } + +interface Use { + readonly module: Module + readonly expr: Node + readonly write: boolean +} + +class Demand { + all = false + readonly names = new Set() + add(name: string): boolean { + if (this.all || this.names.has(name)) return false + this.names.add(name) + return true + } + addAll(other: Demand, except?: ReadonlySet): boolean { + if (this.all) return false + if (other.all) return this.setAll() + let changed = false + for (const name of other.names) { + if (except === undefined || !except.has(name)) changed = this.add(name) || changed + } + return changed + } + setAll(): boolean { + if (this.all) return false + this.all = true + return true + } + has(name: string): boolean { + return this.all || this.names.has(name) + } +} + +interface LiteralInfo { + readonly module: Module + readonly node: Node + readonly keys: Set + escaped: boolean + readonly demand: Demand + /** Argument links: this literal is passed for a parameter that is spread into `from`. */ + readonly links: Array +} + +interface ParamSpread { + readonly from: LiteralInfo + readonly spread: Node + readonly param: Binding +} + +interface FunctionInfo { + readonly module: Module + readonly node: Node + readonly binding: Binding | undefined + readonly calls: Array<{ readonly module: Module; readonly call: Node }> +} + +interface SpreadContribution { + readonly key: string + readonly module: Module + readonly literal: Node + readonly spread: Node +} + +interface ValueSink { + member(name: string): void + spread(module: Module, literal: Node, spread: Node): void + argument(module: Module, call: Node, index: number): boolean + fail(reason: string): void +} + +const wrapperTypes = new Set([ + "TSAsExpression", + "TSSatisfiesExpression", + "TSNonNullExpression", + "TSTypeAssertion", + "TSInstantiationExpression", + "ParenthesizedExpression" +]) + +const strip = (node: Node): Node => { + while (wrapperTypes.has(node.type)) node = node.expression + return node +} + +const effectModulePattern = /[\\/]effect[\\/](?:src|dist)[\\/](.+)\.[cm]?[jt]s$/ + +const effectModuleName = (id: string): string | undefined => effectModulePattern.exec(id)?.[1] + +const staticName = (node: Node, computed: boolean): string | undefined => { + if (!computed && node.type === "Identifier") return node.name + if (node.type === "Literal" && (typeof node.value === "string" || typeof node.value === "number")) { + return String(node.value) + } + if (node.type === "TemplateLiteral" && node.expressions.length === 0) return node.quasis[0].value.cooked + return undefined +} + +const memberName = (node: Node): string | undefined => staticName(node.property, node.computed) + +const retrievalApis = new Set(["Context.get", "Context.getUnsafe", "Context.getOrElse", "Context.getOrUndefined"]) +const effectOps = new Set(["Effect.map", "Effect.flatMap", "Effect.andThen", "Effect.tap"]) + +// Trusted APIs that untrusted code may reference. A Fiber exposes its Context +// as a public property, and a Context hands out any service by key string +// (`Context.getUnsafe` with a rebuilt key, `mapUnsafe`, or plain traversal with +// `Object.values`), so any API that can hand either to the caller or to a +// callback must disable pruning. That set cannot be +// enumerated reliably: Fibers hide inside option and callback types such as +// `Logger.Options` or `RunOptions.onFiberStart`. Untrusted code is therefore +// limited to this audited list, and any other trusted API disables pruning. +// Each entry was checked to take no callback that receives a Fiber or Context +// and to return neither. +const allowedApis = new Set([ + "Effect.gen", + "Effect.fn", + "Effect.fnUntraced", + "Effect.succeed", + "Effect.sync", + "Effect.fail", + "Effect.die", + "Effect.promise", + "Effect.tryPromise", + "Effect.suspend", + "Effect.map", + "Effect.flatMap", + "Effect.andThen", + "Effect.tap", + "Effect.as", + "Effect.asVoid", + "Effect.all", + "Effect.forEach", + "Effect.catchTag", + "Effect.catchTags", + "Effect.orDie", + "Effect.matchEffect", + "Effect.match", + // Takes a Context or Layer as input only. + "Effect.provide", + "Effect.provideService", + "Effect.provideServiceEffect", + "Effect.updateService", + "Effect.service", + "Effect.serviceOption", + "Effect.scoped", + "Effect.acquireRelease", + "Effect.acquireUseRelease", + "Effect.addFinalizer", + "Effect.ensuring", + "Effect.onExit", + "Effect.log", + "Effect.logInfo", + "Effect.logDebug", + "Effect.logWarning", + "Effect.logError", + "Effect.annotateLogs", + "Effect.withLogSpan", + "Effect.sleep", + "Effect.yieldNow", + // The register callback's `this` is the Scheduler, which exposes no Fiber. + "Effect.callback", + "Effect.exit", + "Effect.when", + "Effect.zip", + "Effect.zipWith", + "Effect.flatten", + "Effect.isEffect", + "Effect.ignore", + "Effect.option", + "Effect.result", + "Effect.timeout", + "Effect.delay", + "Layer.succeed", + "Layer.effect", + "Layer.sync", + "Layer.merge", + "Layer.mergeAll", + "Layer.provide", + "Layer.provideMerge", + "Layer.launch", + "Layer.empty", + "Layer.effectDiscard", + "Context.get", + "Context.getUnsafe", + "Context.getOrElse", + "Context.getOrUndefined", + "Context.getOption", + "Context.isContext", + "FileSystem.make", + "FileSystem.makeNoop", + "FileSystem.layerNoop", + "@effect/platform-node/NodeFileSystem.layer", + "@effect/platform-node/NodeServices.layer", + // The teardown callback receives an Exit, not a Fiber. + "@effect/platform-node/NodeRuntime.runMain" +]) +// Their `RunOptions` argument can install `onFiberStart`, so they are only +// allowed with the effect as the single argument. +const runApis = new Set(["Effect.runPromise", "Effect.runPromiseExit", "Effect.runSync", "Effect.runSyncExit"]) +// Data modules whose declarations mention no Fiber, Context or Effect runtime type. +const allowedModules = new Set([ + "Option", + "Array", + "Order", + "Equivalence", + "Equal", + "Hash", + "Data", + "Predicate", + "String", + "Number", + "BigInt", + "Boolean", + "Struct", + "Record", + "Tuple", + "Duration", + "Chunk", + "HashMap", + "HashSet", + "Result", + "Redacted", + "Brand", + "Function", + "Iterable", + "Match" +]) +// Globals that reach the global object or run code that can: the running +// Fiber, and so its Context, is published on the global object. +const reflectiveGlobals = new Set([ + "globalThis", + "global", + "self", + "window", + "frames", + "parent", + "top", + "eval", + "Function", + "Reflect", + "Proxy", + "require" +]) +// `Symbol.for` returns protocol symbols such as `~effect/Redactable`, whose +// methods receive the current Context. Only these members of `Symbol` are allowed. +const allowedSymbolMembers = new Set(["iterator", "asyncIterator"]) +// `Object` members that cannot reveal symbol-keyed protocol methods. +const allowedObjectMembers = new Set(["keys", "values", "entries", "fromEntries", "assign", "freeze", "is"]) + +// Reading one of these on a service observes the whole object. +const objectMembers = new Set(Object.getOwnPropertyNames(Object.prototype)) +// Members that read a whole Context from Fibers, runtimes or Contexts. +const exposingMembers = new Set(["context", "mapUnsafe"]) + +const pureComment = /[@#]__PURE__/ + +/** @internal */ +export const analyze = (inputs: ReadonlyArray): Analysis => { + const modules = new Map() + for (const input of inputs) { + const scope = analyzeScopes(input.program) + const module: Module = { input, scope, exports: new Map(), stars: [] } + collectExports(module) + modules.set(input.id, module) + } + + const globalBailouts: Array = [] + const keyBailouts = new Map>() + const keyDemand = new Map() + const literals = new Map() + const functions = new Map() + const flowCalls = new Set() + const spreads: Array = [] + // Keys provided at least once by something other than a tracked literal. + const unknownProviders = new Set() + // Parameter spreads, and whether every argument for them is a tracked literal. + const completeSpreads = new Map() + const escapedNamespaces = new Set() + const escapedBindings = new Set() + + const location = (module: Module, node: Node) => { + const code = module.input.code + let line = 1 + for (let i = 0; i < node.start; i++) if (code.charCodeAt(i) === 10) line++ + return `${module.input.id}:${line} \`${code.slice(node.start, node.start + 60).replace(/\s+/g, " ")}\`` + } + const globalBail = (module: Module, node: Node, reason: string) => { + globalBailouts.push(`${reason} (${location(module, node)})`) + } + const demandOf = (key: string): Demand => { + let demand = keyDemand.get(key) + if (demand === undefined) { + demand = new Demand() + keyDemand.set(key, demand) + } + return demand + } + const bail = (key: string, module: Module, node: Node, reason: string) => { + demandOf(key).setAll() + let reasons = keyBailouts.get(key) + if (reasons === undefined) { + reasons = [] + keyBailouts.set(key, reasons) + } + reasons.push(`${reason} (${location(module, node)})`) + } + + // == symbol resolution + + const moduleFor = (from: Module, source: string): Module | undefined => { + const id = from.input.resolved.get(source) + return id === undefined ? undefined : modules.get(id) + } + + const resolveExport = (module: Module, name: string, seen = new Set()): Sym | undefined => { + const marker = `${module.input.id}#${name}` + if (seen.has(marker)) return undefined + seen.add(marker) + const target = module.exports.get(name) + if (target !== undefined) { + switch (target._tag) { + case "Local": { + const binding = module.scope.scope.bindings.get(target.local) + if (binding === undefined) return undefined + return binding.kind === "import" + ? resolveImport(module, binding, seen) + : { _tag: "Binding", module, binding } + } + case "Reexport": { + const source = moduleFor(module, target.source) + return source && resolveExport(source, target.imported, seen) + } + case "Namespace": { + const source = moduleFor(module, target.source) + return source && { _tag: "Namespace", module: source } + } + case "Expression": + return undefined + } + } + if (name === "default") return undefined + for (const star of module.stars) { + const source = moduleFor(module, star) + const sym = source && resolveExport(source, name, seen) + if (sym) return sym + } + return undefined + } + + const resolveImport = (module: Module, binding: Binding, seen?: Set): Sym | undefined => { + const specifier = binding.declaration + const declaration = module.scope.parents.get(specifier)! + const source = moduleFor(module, declaration.source.value) + if (source === undefined) return undefined + switch (specifier.type) { + case "ImportNamespaceSpecifier": + return { _tag: "Namespace", module: source } + case "ImportDefaultSpecifier": + return resolveExport(source, "default", seen) + default: + return resolveExport(source, staticName(specifier.imported, false)!, seen) + } + } + + const symbolOf = (module: Module, expr: Node): Sym | undefined => { + const node = strip(expr) + if (node.type === "Identifier") { + const binding = module.scope.resolved.get(node) + if (binding === undefined || binding.scope !== module.scope.scope) return undefined + return binding.kind === "import" ? resolveImport(module, binding) : { _tag: "Binding", module, binding } + } + if (node.type === "MemberExpression") { + const name = memberName(node) + if (name === undefined) return undefined + const object = symbolOf(module, node.object) + return object?._tag === "Namespace" ? resolveExport(object.module, name) : undefined + } + return undefined + } + + const apiName = (sym: Sym | undefined): string | undefined => { + if (sym?._tag !== "Binding") return undefined + const name = effectModuleName(sym.module.input.id) + return name === undefined ? undefined : `${name}.${sym.binding.name}` + } + const apiOf = (module: Module, expr: Node) => apiName(symbolOf(module, expr)) + + const symKey = (sym: Sym & { _tag: "Binding" }) => `${sym.module.input.id}#${sym.binding.name}` + + // == reference index: every use of a top-level binding, across modules + + const uses = new Map>() + const indexUse = (sym: Sym & { _tag: "Binding" }, use: Use) => { + const key = symKey(sym) + let list = uses.get(key) + if (list === undefined) { + list = [] + uses.set(key, list) + } + list.push(use) + } + + const parentOf = (module: Module, node: Node): Node | undefined => module.scope.parents.get(node) + + // Walks up through type assertions and parentheses. + const up = (module: Module, node: Node): { readonly node: Node; readonly parent: Node | undefined } => { + let parent = parentOf(module, node) + while (parent !== undefined && wrapperTypes.has(parent.type) && parent.expression === node) { + node = parent + parent = parentOf(module, node) + } + return { node, parent } + } + + for (const module of modules.values()) { + for (const binding of module.scope.scope.bindings.values()) { + for (const ref of binding.refs) { + let sym: Sym | undefined = binding.kind === "import" + ? resolveImport(module, binding) + : { _tag: "Binding", module, binding } + let expr = ref.node + while (sym?._tag === "Namespace") { + const { node, parent } = up(module, expr) + const name = parent?.type === "MemberExpression" && parent.object === node ? memberName(parent) : undefined + if (name === undefined) { + if (module.input.rendered) { + if (!module.input.trusted) globalBail(module, expr, "module namespace used as a value") + escapedNamespaces.add(sym.module) + } + sym = undefined + break + } + expr = parent! + sym = resolveExport(sym.module, name) + } + if (sym?._tag === "Binding") indexUse(sym, { module, expr, write: ref.write }) + } + } + if (module.input.isEntry) { + for (const [name] of module.exports) { + const sym = resolveExport(module, name) + if (sym?._tag === "Binding") escapedBindings.add(sym.binding) + else if (sym?._tag === "Namespace") escapedNamespaces.add(sym.module) + } + for (const star of module.stars) { + const source = moduleFor(module, star) + if (source) escapedNamespaces.add(source) + } + } + } + + // Uses through an escaped namespace object are invisible, so every module + // reachable through its exports escapes as a whole. + const escapedModules = new Set() + const escapeModule = (module: Module) => { + if (escapedModules.has(module)) return + escapedModules.add(module) + const sources = [...module.stars] + for (const target of module.exports.values()) { + if (target._tag === "Reexport" || target._tag === "Namespace") sources.push(target.source) + if (target._tag === "Local") { + const binding = module.scope.scope.bindings.get(target.local) + if (binding?.kind === "import") sources.push(module.scope.parents.get(binding.declaration)!.source.value) + } + } + for (const source of sources) { + const target = moduleFor(module, source) + if (target) escapeModule(target) + } + } + escapedNamespaces.forEach(escapeModule) + + const usesOf = (sym: Sym & { _tag: "Binding" }): ReadonlyArray => uses.get(symKey(sym)) ?? [] + + const isEscapedBinding = (module: Module, binding: Binding) => + escapedBindings.has(binding) || (binding.scope === module.scope.scope && escapedModules.has(module)) + + // All references of a binding, including uses from other modules for top-level bindings. + const referencesOf = (module: Module, binding: Binding): ReadonlyArray => + binding.scope === module.scope.scope + ? usesOf({ _tag: "Binding", module, binding }) + : binding.refs.map((ref) => ({ module, expr: ref.node, write: ref.write })) + + // == service keys + + const keys = new Map() // symKey -> key string + const keyCreation = (module: Module, expr: Node | null | undefined): string | null | undefined => { + if (expr == null) return undefined + const node = strip(expr) + if (node.type !== "CallExpression") return undefined + const callee = strip(node.callee) + const api = apiOf(module, callee) + const direct = api === "Context.Service" || api === "Context.Reference" + const curried = callee.type === "CallExpression" && callee.arguments.length === 0 && + apiOf(module, callee.callee) === "Context.Service" + if (!direct && !curried) return undefined + const arg = node.arguments[0] + return arg === undefined ? null : constString(module, arg) ?? null + } + // A string literal, or a const binding initialised with one. + const constString = (module: Module, expr: Node): string | undefined => { + const node = strip(expr) + if (node.type !== "Identifier") return staticName(node, true) + const sym = symbolOf(module, node) + const declaration = sym?._tag === "Binding" && sym.binding.kind === "const" ? sym.binding.declaration : undefined + return declaration?.type === "VariableDeclarator" && declaration.init + ? staticName(strip(declaration.init), true) + : undefined + } + const creationCallees = new Set() + for (const module of modules.values()) { + for (const binding of module.scope.scope.bindings.values()) { + const declaration = binding.declaration + const init = declaration.type === "VariableDeclarator" && declaration.id.type === "Identifier" + ? declaration.init + : declaration.type === "ClassDeclaration" + ? declaration.superClass + : undefined + const key = keyCreation(module, init) + if (typeof key !== "string") continue + if (declaration.type === "VariableDeclarator" && binding.kind !== "const") continue + const call = strip(init) + creationCallees.add(strip(call.callee)) + creationCallees.add(strip(strip(call.callee).callee ?? call.callee)) + keys.set(symKey({ _tag: "Binding", module, binding }), key) + if (isEscapedBinding(module, binding)) { + bail(key, module, declaration, "service key escapes through an export or namespace") + } + if (declaration.type === "ClassDeclaration" && containsThis(declaration.body)) { + bail(key, module, declaration, "class service with `this` in its body") + } + } + } + + const keyOf = (module: Module, expr: Node): string | undefined => { + const sym = symbolOf(module, expr) + return sym?._tag === "Binding" ? keys.get(symKey(sym)) : undefined + } + + // == consumers + + const isWriteTarget = (module: Module, node: Node): boolean => { + const { node: self, parent } = up(module, node) + if (parent === undefined) return false + switch (parent.type) { + case "AssignmentExpression": + return parent.left === self + case "UpdateExpression": + return true + case "UnaryExpression": + return parent.operator === "delete" + case "ForInStatement": + case "ForOfStatement": + return parent.left === self + case "Property": + case "ArrayPattern": + case "AssignmentPattern": + case "RestElement": + case "ObjectPattern": + return true + default: + return false + } + } + + const valueUses = (module: Module, expr: Node, sink: ValueSink): void => { + const { node, parent } = up(module, expr) + if (parent === undefined) return sink.fail("value at program level") + switch (parent.type) { + case "MemberExpression": { + if (parent.object !== node) break + const name = memberName(parent) + if (name === undefined) return sink.fail("computed member access") + if (isWriteTarget(module, parent)) return sink.fail("member write") + return sink.member(name) + } + case "ChainExpression": + return valueUses(module, parent, sink) + case "VariableDeclarator": + if (parent.init !== node) break + return patternUses(module, parent.id, sink) + case "SpreadElement": { + const literal = parentOf(module, parent) + if (literal?.type === "ObjectExpression") return sink.spread(module, literal, parent) + break + } + case "CallExpression": + case "NewExpression": { + const index = parent.arguments.indexOf(node) + if (index !== -1 && sink.argument(module, parent, index)) return + break + } + } + sink.fail(`value used in ${parent.type}`) + } + + const patternUses = (module: Module, pattern: Node, sink: ValueSink): void => { + switch (pattern.type) { + case "Identifier": { + const binding = module.scope.declared.get(pattern) + if (binding === undefined) return sink.fail("unresolved binding") + if (isEscapedBinding(module, binding)) return sink.fail("exported binding") + for (const ref of referencesOf(module, binding)) { + if (ref.write) return sink.fail("reassigned binding") + valueUses(ref.module, ref.expr, sink) + } + return + } + case "ObjectPattern": + for (const property of pattern.properties) { + const name = property.type === "Property" ? staticName(property.key, property.computed) : undefined + if (name === undefined) return sink.fail("rest or computed destructuring") + sink.member(name) + } + return + case "AssignmentPattern": + return patternUses(module, pattern.left, sink) + default: + sink.fail(`${pattern.type} pattern`) + } + } + + const callbackParam = (module: Module, fn: Node | undefined, sink: ValueSink): void => { + const node = fn && strip(fn) + if (node === undefined || !isFunctionNode(node)) return sink.fail("callback is not an inline function") + // `arguments` aliases the value without going through the parameter. + if (node.type !== "ArrowFunctionExpression" && referencesArguments(module, node)) { + return sink.fail("callback reads `arguments`") + } + const param = node.params[0] + if (param !== undefined) patternUses(module, param, sink) + } + + // `expr` evaluates to an Effect that succeeds with the value described by `sink`. + const effectUses = (module: Module, expr: Node, sink: ValueSink): void => { + const { node, parent } = up(module, expr) + if (parent?.type === "YieldExpression" && parent.delegate) return valueUses(module, parent, sink) + if (parent?.type === "MemberExpression" && parent.object === node && memberName(parent) === "pipe") { + const call = up(module, parent) + if (call.parent?.type === "CallExpression" && call.parent.callee === call.node) { + return pipeUses(module, call.parent, call.parent.arguments, 0, sink) + } + } + if (parent?.type === "CallExpression" && parent.arguments[0] === node) { + const api = apiOf(module, parent.callee) + if (api !== undefined && effectOps.has(api) && parent.arguments.length >= 2) { + return opUses(module, api, parent.arguments[1], parent, sink) + } + if (api === "Function.pipe") return pipeUses(module, parent, parent.arguments, 1, sink) + } + sink.fail(`effect used in ${parent?.type}`) + } + + // `andThen` ignores the value when given anything but a function. Only a + // syntactically non-callable argument proves that. + const isNonCallable = (node: Node): boolean => { + const value = strip(node) + return value.type === "Literal" || value.type === "ObjectExpression" || value.type === "ArrayExpression" || + value.type === "TemplateLiteral" + } + + const opUses = (module: Module, api: string, fn: Node, call: Node, sink: ValueSink): void => { + if (api === "Effect.andThen" && isNonCallable(fn)) return + callbackParam(module, fn, sink) + if (api === "Effect.tap") effectUses(module, call, sink) + } + + const pipeUses = (module: Module, call: Node, ops: ReadonlyArray, index: number, sink: ValueSink): void => { + if (index >= ops.length) return effectUses(module, call, sink) + const op = strip(ops[index]) + const api = op.type === "CallExpression" ? apiOf(module, op.callee) : undefined + if (api === undefined || !effectOps.has(api) || op.arguments.length !== 1) { + return sink.fail("unrecognised pipe operation") + } + if (api === "Effect.andThen" && isNonCallable(op.arguments[0])) return + callbackParam(module, op.arguments[0], sink) + if (api === "Effect.tap") pipeUses(module, call, ops, index + 1, sink) + } + + const serviceSink = (key: string, module: Module, node: Node): ValueSink => ({ + member: (name) => { + if (objectMembers.has(name)) bail(key, module, node, `inherited member \`${name}\` read`) + else demandOf(key).add(name) + }, + spread: (spreadModule, literal, spread) => { + spreads.push({ key, module: spreadModule, literal, spread }) + }, + argument: () => false, + fail: (reason) => bail(key, module, node, reason) + }) + + const contextSink = (module: Module, node: Node): ValueSink => ({ + member: () => globalBail(module, node, "member read on a whole Context"), + spread: () => globalBail(module, node, "whole Context spread"), + argument: (argModule, call, index) => index === 0 && retrievalApis.has(apiOf(argModule, call.callee) ?? ""), + fail: (reason) => globalBail(module, node, `whole Context escapes: ${reason}`) + }) + + // Uses of provider objects before they reach a Context, e.g. in a release or + // tap callback. Static reads add demand, anything else keeps the literal. + const literalSink = (targets: ReadonlyArray): ValueSink => ({ + member: (name) => { + for (const literal of targets) { + if (objectMembers.has(name)) literal.escaped = true + else literal.demand.add(name) + } + }, + spread: () => { + for (const literal of targets) literal.escaped = true + }, + argument: () => false, + fail: () => { + for (const literal of targets) literal.escaped = true + } + }) + + // == providers + + // Set whenever a provider flow reaches something other than an object + // literal, so callers can tell a complete flow from a partial one. + let unknownSource = false + + // Values returned by a function. Async functions return a Promise and + // generators an iterator, so their return statements are not the result. + const returnsOf = (fn: Node, generator = false): Array => { + const node = strip(fn) + if (!isFunctionNode(node) || node.async || node.generator !== generator) { + unknownSource = true + return [] + } + if (node.body.type !== "BlockStatement") return [node.body] + const out: Array = [] + const visit = (current: Node) => { + for (const child of children(current)) { + if (isFunctionNode(child) || child.type === "ClassDeclaration" || child.type === "ClassExpression") continue + if (child.type === "ReturnStatement") { + if (child.argument) out.push(child.argument) + } else { + visit(child) + } + } + } + visit(node.body) + return out + } + + const literalInfo = (module: Module, node: Node): LiteralInfo => { + let info = literals.get(node) + if (info === undefined) { + info = { module, node, keys: new Set(), escaped: false, demand: new Demand(), links: [] } + literals.set(node, info) + } + return info + } + + // A const binding whose only use is `use` (so its value flows nowhere else). + const singleUseInit = (module: Module, expr: Node): { module: Module; init: Node } | undefined => { + const binding = module.scope.resolved.get(expr) + if (binding === undefined || binding.kind !== "const" || isEscapedBinding(module, binding)) return undefined + const declaration = binding.declaration + if (declaration.type !== "VariableDeclarator" || declaration.id.type !== "Identifier" || !declaration.init) { + return undefined + } + if (referencesOf(module, binding).length !== 1) return undefined + return { module, init: declaration.init } + } + + const functionOf = (module: Module, callee: Node): FunctionInfo | undefined => { + const node = strip(callee) + if (isFunctionNode(node)) return functionInfo(module, node, undefined) + const sym = symbolOf(module, node) + if (sym?._tag !== "Binding") return undefined + const declaration = sym.binding.declaration + if (declaration.type === "FunctionDeclaration") return functionInfo(sym.module, declaration, sym.binding) + if (declaration.type === "VariableDeclarator" && sym.binding.kind === "const" && declaration.init) { + const init = strip(declaration.init) + if (isFunctionNode(init)) return functionInfo(sym.module, init, sym.binding) + } + return undefined + } + + const functionInfo = (module: Module, node: Node, binding: Binding | undefined): FunctionInfo => { + let info = functions.get(node) + if (info === undefined) { + info = { module, node, binding, calls: [] } + functions.set(node, info) + } + return info + } + + const flowValue = (module: Module, expr: Node, seen = new Set()): Array => { + const node = strip(expr) + if (seen.has(node)) { + unknownSource = true + return [] + } + seen.add(node) + switch (node.type) { + case "ObjectExpression": + return [literalInfo(module, node)] + case "ConditionalExpression": + return [...flowValue(module, node.consequent, seen), ...flowValue(module, node.alternate, seen)] + case "LogicalExpression": + return [...flowValue(module, node.left, seen), ...flowValue(module, node.right, seen)] + case "SequenceExpression": + return flowValue(module, node.expressions[node.expressions.length - 1], seen) + case "Identifier": { + const single = singleUseInit(module, node) + if (single) return flowValue(single.module, single.init, seen) + break + } + case "CallExpression": { + const callee = strip(node.callee) + if (callee.type === "MemberExpression" && memberName(callee) === "of" && keyOf(module, callee.object)) { + if (node.arguments.length === 1) return flowValue(module, node.arguments[0], seen) + break + } + const fn = functionOf(module, callee) + if (fn === undefined) break + flowCalls.add(node) + fn.calls.push({ module, call: node }) + return returnsOf(fn.node).flatMap((result) => flowValue(fn.module, result, seen)) + } + } + unknownSource = true + return [] + } + + // Applies a callback that receives the provider objects as its first argument. + const consume = (module: Module, fn: Node | undefined, targets: ReadonlyArray) => { + if (targets.length > 0) callbackParam(module, fn, literalSink(targets)) + } + + const flowEffect = (module: Module, expr: Node, seen = new Set()): Array => { + const node = strip(expr) + if (seen.has(node)) { + unknownSource = true + return [] + } + seen.add(node) + if (node.type === "Identifier") { + const single = singleUseInit(module, node) + if (single) return flowEffect(single.module, single.init, seen) + } + if (node.type !== "CallExpression") { + unknownSource = true + return [] + } + const args = node.arguments + const callee = strip(node.callee) + if (callee.type === "MemberExpression" && memberName(callee) === "pipe") { + // Walks back from the last operation. Taps after the producing operation + // receive the provider objects. + const taps: Array = [] + const tapped = (targets: Array) => { + for (const tap of taps) consume(module, tap, targets) + return targets + } + for (let i = args.length - 1; i >= 0; i--) { + const op = strip(args[i]) + const api = op.type === "CallExpression" && op.arguments.length === 1 ? apiOf(module, op.callee) : undefined + if (api === "Effect.map") { + return tapped(returnsOf(op.arguments[0]).flatMap((r) => flowValue(module, r, seen))) + } + if (api === "Effect.flatMap") { + return tapped(returnsOf(op.arguments[0]).flatMap((r) => flowEffect(module, r, seen))) + } + if (api !== "Effect.tap") { + unknownSource = true + return [] + } + taps.push(op.arguments[0]) + } + return tapped(flowEffect(module, callee.object, seen)) + } + switch (apiOf(module, callee)) { + case "Effect.succeed": + if (args.length === 1) return flowValue(module, args[0], seen) + break + case "Effect.sync": + if (args.length === 1) return returnsOf(args[0]).flatMap((r) => flowValue(module, r, seen)) + break + case "Effect.map": + if (args.length === 2) return returnsOf(args[1]).flatMap((r) => flowValue(module, r, seen)) + break + case "Effect.flatMap": + if (args.length === 2) return returnsOf(args[1]).flatMap((r) => flowEffect(module, r, seen)) + break + case "Effect.acquireRelease": + case "Effect.tap": { + if (args.length !== 2) break + // The release and tap callbacks receive the acquired value. + const targets = flowEffect(module, args[0], seen) + consume(module, args[1], targets) + return targets + } + case "Effect.gen": { + const body = args[args.length - 1] + if (body) return returnsOf(body, true).flatMap((r) => flowValue(module, r, seen)) + break + } + } + unknownSource = true + return [] + } + + const insert = (key: string, flow: () => Array) => { + unknownSource = false + for (const literal of flow()) literal.keys.add(key) + if (unknownSource) unknownProviders.add(key) + } + const insertValue = (key: string, module: Module, expr: Node | undefined) => + insert(key, () => expr === undefined ? (unknownSource = true, []) : flowValue(module, expr)) + const insertEffect = (key: string, module: Module, expr: Node | undefined) => + insert(key, () => expr === undefined ? (unknownSource = true, []) : flowEffect(module, expr)) + + // Applies `f` to the argument of a curried call `api(key)(arg)` and returns + // that outer call. + const curried = (module: Module, call: Node, f: (arg: Node | undefined) => void): Node | undefined => { + const { node, parent } = up(module, call) + if (parent?.type !== "CallExpression" || parent.callee !== node) return undefined + f(parent.arguments[0]) + return parent + } + + const layerCombinators = new Set(["Layer.merge", "Layer.mergeAll", "Layer.provide", "Layer.provideMerge"]) + + // A Layer or Context built from a provider must stay inside the bundle: + // whoever builds it can read every service it holds. `fail` is called when + // it may escape. + const containerFlow = ( + module: Module, + expr: Node, + fail: (reason: string) => void, + seen = new Set() + ): void => { + if (seen.has(expr)) return + seen.add(expr) + const { node, parent } = up(module, expr) + if (parent === undefined) return fail("Layer at program level") + switch (parent.type) { + case "CallExpression": { + if (parent.callee === node) return fail("Layer called") + const api = apiOf(module, parent.callee) + if (api === "Effect.provide" || api === "Layer.launch") return + if (api !== undefined && layerCombinators.has(api)) { + // Curried combinators produce a function applied to another Layer. + const applied = parent.arguments.length === 1 && api !== "Layer.mergeAll" + ? appliedTo(module, parent) + : parent + return applied ? containerFlow(module, applied, fail, seen) : fail("curried Layer combinator escapes") + } + return fail(`Layer passed to ${api ?? "an unrecognised function"}`) + } + case "MemberExpression": { + // `layer.pipe(...)` with Layer combinators only. + const call = up(module, parent) + if ( + parent.object !== node || memberName(parent) !== "pipe" || call.parent?.type !== "CallExpression" || + call.parent.callee !== call.node + ) { + break + } + for (const op of call.parent.arguments) { + const opNode = strip(op) + const api = opNode.type === "CallExpression" ? apiOf(module, opNode.callee) : undefined + if (api === "Effect.provide" || api === "Layer.launch") return + if (api === undefined || !layerCombinators.has(api)) return fail("Layer piped into an unrecognised function") + } + return containerFlow(module, call.parent, fail, seen) + } + case "VariableDeclarator": { + if (parent.init !== node || parent.id.type !== "Identifier") break + const binding = module.scope.declared.get(parent.id)! + if (binding.kind !== "const") return fail("Layer in a mutable binding") + if (isEscapedBinding(module, binding)) return fail("Layer exported from the entry module") + for (const use of referencesOf(module, binding)) { + if (use.module.input.rendered) containerFlow(use.module, use.expr, fail, seen) + } + return + } + case "ArrowFunctionExpression": + case "ReturnStatement": { + // Returned from a function: follow its calls. + const fn = parent.type === "ArrowFunctionExpression" ? parent : enclosingFunction(module, parent) + if (fn === undefined) break + const owner = up(module, fn).parent + const binding = owner?.type === "VariableDeclarator" && owner.id.type === "Identifier" + ? module.scope.declared.get(owner.id) + : fn.type === "FunctionDeclaration" && fn.id + ? module.scope.declared.get(fn.id) + : undefined + if (binding === undefined || binding.scope !== module.scope.scope || binding.kind === "let") break + if (isEscapedBinding(module, binding)) return fail("Layer factory exported from the entry module") + for (const use of referencesOf(module, binding)) { + if (!use.module.input.rendered) continue + const call = up(use.module, use.expr) + if (call.parent?.type !== "CallExpression" || call.parent.callee !== call.node) { + return fail("Layer factory used as a value") + } + containerFlow(use.module, call.parent, fail, seen) + } + return + } + } + fail(`Layer used in ${parent.type}`) + } + + // For `f(...)` used as a pipe operation or called directly, the expression + // holding its result. + const appliedTo = (module: Module, call: Node): Node | undefined => { + const { node, parent } = up(module, call) + if (parent?.type !== "CallExpression") return undefined + if (parent.callee === node) return parent + const callee = strip(parent.callee) + return callee.type === "MemberExpression" && memberName(callee) === "pipe" ? parent : undefined + } + + const enclosingFunction = (module: Module, node: Node): Node | undefined => { + for (let current = parentOf(module, node); current; current = parentOf(module, current)) { + if (isFunctionNode(current)) return current + } + return undefined + } + + const keyUse = (key: string, module: Module, expr: Node): void => { + const sink = serviceSink(key, module, expr) + // Untrusted code may store or mutate a key it passes around, which can + // change what other keys resolve to. + const escape = (reason: string) => + module.input.trusted + ? bail(key, module, expr, reason) + : globalBail(module, expr, `service key escapes: ${reason}`) + const contained = (container: Node | undefined) => { + if (container) containerFlow(module, container, (reason) => bail(key, module, expr, reason)) + else bail(key, module, expr, "Layer or Context escapes") + } + const { node, parent } = up(module, expr) + if (parent?.type === "MemberExpression" && parent.object === node) { + const name = memberName(parent) + const call = up(module, parent) + const isCall = call.parent?.type === "CallExpression" && call.parent.callee === call.node + if (isWriteTarget(module, parent)) return globalBail(module, expr, `service key member \`${name}\` written`) + if (name === "key") return + if (isCall && name === "of") return + if (isCall && (name === "use" || name === "useSync")) { + return callbackParam(module, call.parent!.arguments[0], sink) + } + if (isCall && name === "context") { + insertValue(key, module, call.parent!.arguments[0]) + return contained(call.parent) + } + if (isCall && name === "pipe") return pipeUses(module, call.parent!, call.parent!.arguments, 0, sink) + return escape(`unrecognised member \`${name}\` of the service key`) + } + if (parent?.type === "CallExpression" && parent.callee !== node) { + const index = parent.arguments.indexOf(node) + const args = parent.arguments + const api = apiOf(module, parent.callee) + const returned = (fn: Node | undefined) => + insert(key, () => returnsOf(fn ?? parent).flatMap((r) => flowValue(module, r))) + // Curried providers return a function that must be applied in the bundle. + const applied = () => { + if (appliedTo(module, parent) === undefined) bail(key, module, expr, "curried provider escapes") + } + switch (api) { + case "Effect.service": + return effectUses(module, parent, sink) + case "Effect.map": + case "Effect.flatMap": + case "Effect.andThen": + case "Effect.tap": + if (index === 0 && args.length >= 2) return opUses(module, api, args[1], parent, sink) + break + case "Function.pipe": + if (index === 0) return pipeUses(module, parent, args, 1, sink) + break + case "Context.get": + case "Context.getUnsafe": + case "Context.getOrElse": + case "Context.getOrUndefined": + if (index === 1) return valueUses(module, parent, sink) + break + case "Context.omit": + return + case "Layer.succeed": + if (index === 0 && args.length === 2) { + insertValue(key, module, args[1]) + return contained(parent) + } + if (index === 0) return contained(curried(module, parent, (arg) => insertValue(key, module, arg))) + break + case "Layer.effect": + if (index === 0 && args.length === 2) { + insertEffect(key, module, args[1]) + return contained(parent) + } + if (index === 0) return contained(curried(module, parent, (arg) => insertEffect(key, module, arg))) + break + case "Layer.sync": + if (index === 0 && args.length === 2) { + returned(args[1]) + return contained(parent) + } + if (index === 0) return contained(curried(module, parent, returned)) + break + case "Effect.provideService": + if (index === 1 && args.length === 3) return insertValue(key, module, args[2]) + if (index === 0 && args.length === 2) { + insertValue(key, module, args[1]) + return applied() + } + break + case "Effect.provideServiceEffect": + if (index === 1 && args.length === 3) return insertEffect(key, module, args[2]) + if (index === 0 && args.length === 2) { + insertEffect(key, module, args[1]) + return applied() + } + break + case "Effect.updateService": { + const fn = index === 1 && args.length === 3 ? args[2] : index === 0 && args.length === 2 ? args[1] : undefined + if (fn === undefined) break + callbackParam(module, fn, sink) + returned(fn) + if (args.length === 2) applied() + return + } + case "Context.make": + if (index === 0 && args.length === 2) { + insertValue(key, module, args[1]) + return contained(parent) + } + break + case "Context.add": + if (index === 1 && args.length === 3) { + insertValue(key, module, args[2]) + return contained(parent) + } + if (index === 0 && args.length === 2) { + insertValue(key, module, args[1]) + return contained(appliedTo(module, parent)) + } + break + } + return api === undefined + ? escape("passed to an unrecognised function") + : bail(key, module, expr, `passed to ${api}`) + } + if (parent?.type === "YieldExpression" && parent.delegate) return valueUses(module, parent, sink) + escape(`used in ${parent?.type}`) + } + + // == classify every use + + for (const [key, list] of uses) { + const serviceKey = keys.get(key) + for (const use of list) { + const { module, expr } = use + if (!module.input.rendered) continue + if (serviceKey !== undefined) { + if (use.write) bail(serviceKey, module, expr, "service key reassigned") + else keyUse(serviceKey, module, expr) + continue + } + const sym = symbolOf(module, expr) + const api = apiName(sym) + if (api === "Context.Service" || api === "Context.Reference") { + if (!creationCallees.has(expr) && sym!._tag === "Binding" && sym!.module !== module) { + const { parent } = up(module, expr) + const literal = parent?.type === "CallExpression" ? keyCreation(module, parent) : undefined + if (typeof literal === "string") bail(literal, module, expr, "service key created outside a declaration") + else globalBail(module, expr, "service key with a dynamic or untracked key string") + } + continue + } + if (module.input.trusted || sym?._tag !== "Binding" || !sym.module.input.trusted) continue + const name = `${sym.module.input.apiPrefix}.${sym.binding.name}` + const { node, parent } = up(module, expr) + const call = parent?.type === "CallExpression" && parent.callee === node ? parent : undefined + if (name === "Effect.context" && call !== undefined) { + effectUses(module, call, contextSink(module, expr)) + continue + } + // `runFork` returns the Fiber, so its result must also be discarded. + if ( + name === "Effect.runFork" && call !== undefined && call.arguments.length === 1 && + up(module, call).parent?.type === "ExpressionStatement" + ) { + continue + } + if (runApis.has(name) && call !== undefined && call.arguments.length === 1) continue + if (allowedApis.has(name) || allowedModules.has(sym.module.input.apiPrefix ?? "")) continue + globalBail(module, expr, `${name} is not an audited API`) + } + } + + for (const module of modules.values()) { + if (!module.input.rendered) continue + // Code outside the analysed graph can do anything with the values it gets. + for (const source of module.input.externalImports ?? []) { + globalBail(module, module.input.program, `external import \`${source}\``) + } + if (module.input.trusted) continue + for (const node of module.scope.globals) { + const { node: self, parent } = up(module, node) + const member = parent?.type === "MemberExpression" && parent.object === self ? memberName(parent) : undefined + const call = parent?.type === "CallExpression" && parent.callee === self + if (reflectiveGlobals.has(node.name)) { + globalBail(module, node, `\`${node.name}\` may reach the global object or the running Fiber`) + } else if (node.name === "Symbol" && !call && !allowedSymbolMembers.has(member ?? "")) { + globalBail(module, node, `\`Symbol${member === undefined ? "" : `.${member}`}\` may reveal protocol symbols`) + } else if (node.name === "Object" && !allowedObjectMembers.has(member ?? "")) { + globalBail(module, node, `\`Object${member === undefined ? "" : `.${member}`}\` may reveal protocol symbols`) + } + } + const visit = (node: Node) => { + if ( + node.type === "MemberExpression" && exposingMembers.has(memberName(node) ?? "") && + symbolOf(module, node.object)?._tag !== "Namespace" + ) { + globalBail(module, node, `\`.${memberName(node)}\` may read a whole Context`) + } + if (node.type === "ImportExpression") globalBail(module, node, "dynamic import") + if (node.type === "MemberExpression" && /^(?:prepare|capture)StackTrace$/.test(memberName(node) ?? "")) { + globalBail(module, node, "stack trace hooks expose call frames") + } + for (const child of children(node)) visit(child) + } + visit(module.input.program) + } + + // == entry exports + // + // An importer of the bundle can pass objects whose getters or `toString` + // run inside a provider's scope, call exported functions with Effects or + // Layers, or run exported Effects with its own logger. None of that can be + // checked from here, so only primitive constants may be exported. + for (const module of modules.values()) { + if (!module.input.isEntry) continue + for (const star of module.stars) globalBail(module, module.input.program, `entry module re-exports \`${star}\``) + for (const [name] of module.exports) { + const sym = resolveExport(module, name) + const declaration = sym?._tag === "Binding" && sym.binding.kind === "const" ? sym.binding.declaration : undefined + const init = declaration?.type === "VariableDeclarator" && declaration.init ? strip(declaration.init) : undefined + const primitive = init !== undefined && + ((init.type === "Literal" && init.regex == null) || + (init.type === "TemplateLiteral" && init.expressions.length === 0)) + if (!primitive) globalBail(module, module.input.program, `entry module exports \`${name}\``) + } + } + + // == escapes of provider functions and their literals + + for (const fn of functions.values()) { + let escaped = false + if (fn.binding !== undefined) { + if (isEscapedBinding(fn.module, fn.binding)) escaped = true + for (const use of usesOf({ _tag: "Binding", module: fn.module, binding: fn.binding })) { + const { node, parent } = up(use.module, use.expr) + if (use.write || parent?.type !== "CallExpression" || parent.callee !== node || !flowCalls.has(parent)) { + escaped = true + } + } + } + for (const result of returnsOf(fn.node)) { + for (const literal of flowValue(fn.module, result)) { + if (escaped) literal.escaped = true + linkParamSpreads(fn, literal) + } + } + } + + function usesArguments(fn: FunctionInfo): boolean { + return referencesArguments(fn.module, fn.node) + } + + function referencesArguments(module: Module, fn: Node): boolean { + return module.scope.globals.some((node) => node.name === "arguments" && within(node, fn)) + } + + function linkParamSpreads(fn: FunctionInfo, literal: LiteralInfo) { + for (const property of literal.node.properties) { + if (property.type !== "SpreadElement") continue + const argument = strip(property.argument) + if (argument.type !== "Identifier") continue + const param = fn.module.scope.resolved.get(argument) + const index = param === undefined ? -1 : fn.node.params.indexOf(param.declaration) + if (param === undefined || param.kind !== "param" || index === -1 || param.declaration.type !== "Identifier") { + continue + } + // `arguments` aliases every parameter, so their uses cannot be listed. + if (fn.node.type !== "ArrowFunctionExpression" && usesArguments(fn)) continue + let complete = true + for (const { module, call } of fn.calls) { + const args: ReadonlyArray = call.arguments + const arg = args[index] + if (arg === undefined || args.slice(0, index + 1).some((arg) => arg.type === "SpreadElement")) { + complete = false + continue + } + unknownSource = false + const targets = flowValue(module, arg) + if (unknownSource) complete = false + for (const target of targets) { + if (!target.links.some((link) => link.from === literal && link.spread === property)) { + target.links.push({ from: literal, spread: property, param }) + } + } + } + completeSpreads.set(property, complete && (completeSpreads.get(property) ?? true)) + } + } + + // == fixpoint + + const isPure = (module: Module, expr: Node): boolean => { + const node = strip(expr) + switch (node.type) { + case "Identifier": + case "Literal": + case "FunctionExpression": + case "ArrowFunctionExpression": + return true + case "TemplateLiteral": + return node.expressions.length === 0 + case "MemberExpression": + // Reading an export through a module namespace has no side effects. + return memberName(node) !== undefined && symbolOf(module, node.object)?._tag === "Namespace" + case "CallExpression": + case "NewExpression": + return hasPureComment(module, node) && node.arguments.every((arg: Node) => isPure(module, arg)) + default: + return false + } + } + + const hasPureComment = (module: Module, node: Node): boolean => + module.input.comments.some((comment) => + comment.end <= node.start && pureComment.test(comment.value) && + module.input.code.slice(comment.end, node.start).trim() === "" + ) + + const propertyName = (property: Node): string | undefined => + property.type === "Property" && property.kind === "init" ? staticName(property.key, property.computed) : undefined + + const isPrunable = (literal: LiteralInfo, property: Node): boolean => { + const name = propertyName(property) + return name !== undefined && name !== "__proto__" && isPure(literal.module, property.value) + } + + const isRetained = (literal: LiteralInfo, property: Node): boolean => + !isPrunable(literal, property) || literal.demand.has(propertyName(property)!) + + const keysAfter = (literal: Node, spread: Node): Set => { + const out = new Set() + const index = literal.properties.indexOf(spread) + for (const property of literal.properties.slice(index + 1)) { + const name = propertyName(property) + if (name !== undefined) out.add(name) + } + return out + } + + // Properties read through `this` in a function body, ignoring nested + // non-arrow functions. + const thisReads = (module: Module, fn: Node, demand: Demand): boolean => { + let changed = false + const visit = (node: Node) => { + for (const child of children(node)) { + if (child.type === "FunctionExpression" || child.type === "FunctionDeclaration") continue + if (child.type === "ThisExpression") { + const { node: self, parent } = up(module, child) + const name = parent?.type === "MemberExpression" && parent.object === self ? memberName(parent) : undefined + changed = (name === undefined || objectMembers.has(name) || isWriteTarget(module, parent!) + ? demand.setAll() + : demand.add(name)) || changed + } + visit(child) + } + } + if (fn.body) visit(fn.body) + return changed + } + + // Properties a property value may read through its receiver when called as + // a method. Values that cannot be resolved may read anything. + const receiverReads = (module: Module, expr: Node, demand: Demand, depth = 0): boolean => { + const node = strip(expr) + if (depth > 8) return demand.setAll() + switch (node.type) { + case "ArrowFunctionExpression": + case "Literal": + case "TemplateLiteral": + return false + case "FunctionExpression": + case "FunctionDeclaration": + return thisReads(module, node, demand) + case "Identifier": + case "MemberExpression": { + const sym = symbolOf(module, node) + if (sym?._tag !== "Binding") return demand.setAll() + const declaration = sym.binding.declaration + // A reassigned function may be anything at runtime. + if (sym.binding.refs.some((ref) => ref.write)) return demand.setAll() + if (declaration.type === "FunctionDeclaration") return thisReads(sym.module, declaration, demand) + if (declaration.type === "VariableDeclarator" && sym.binding.kind === "const" && declaration.init) { + return receiverReads(sym.module, declaration.init, demand, depth + 1) + } + return demand.setAll() + } + case "CallExpression": { + // A call whose callee returns only resolvable functions, e.g. an IIFE. + const fn = functionOf(module, node.callee) + if (fn === undefined) return demand.setAll() + unknownSource = false + const results = returnsOf(fn.node) + if (unknownSource || results.length === 0) return demand.setAll() + let changed = false + for (const result of results) changed = receiverReads(fn.module, result, demand, depth + 1) || changed + return changed + } + default: + return demand.setAll() + } + } + + // Reads through `this` by the methods a literal holds. Every object holding + // a method can be its receiver, so a literal needs the reads of its own + // retained methods and of every method spread into it. Only reads by its own + // methods are owed by the objects spread into it: spread-in methods arrive + // together with the properties they read. + const ownReads = new Map() + const spreadInReads = new Map() + const demandIn = (map: Map, literal: LiteralInfo) => { + let demand = map.get(literal) + if (demand === undefined) { + demand = new Demand() + map.set(literal, demand) + } + return demand + } + const methodReads = (literal: LiteralInfo): Demand => { + const demand = new Demand() + demand.addAll(demandIn(ownReads, literal)) + demand.addAll(demandIn(spreadInReads, literal)) + return demand + } + const consumerSpreads = new Map(spreads.map((c) => [c.spread, c.key])) + + const updateMethodReads = (literal: LiteralInfo): boolean => { + const own = demandIn(ownReads, literal) + const spreadIn = demandIn(spreadInReads, literal) + let changed = false + for (const property of literal.node.properties) { + if (property.type === "SpreadElement") { + if (completeSpreads.get(property) === true) continue + const key = consumerSpreads.get(property) + if (key !== undefined && !unknownProviders.has(key)) { + for (const source of literals.values()) { + if (source.keys.has(key)) changed = spreadIn.addAll(methodReads(source)) || changed + } + continue + } + // Methods from an unknown object may read any property. + changed = own.setAll() || changed + } else if (isRetained(literal, property)) { + changed = receiverReads(literal.module, property.value, own) || changed + } + } + for (const source of literals.values()) { + if (source.links.some((link) => link.from === literal)) { + changed = spreadIn.addAll(methodReads(source)) || changed + } + } + return changed + } + + const linkDemand = (link: ParamSpread, demand: Demand): boolean => { + const { from, spread, param } = link + let changed = demand.addAll(from.demand, keysAfter(from.node, spread)) + const module = from.module + for (const ref of param.refs) { + if (ref.node === strip(spread.argument)) continue + const pruned = from.node.properties.some((property: Node) => + property.type === "Property" && within(ref.node, property) && !isRetained(from, property) + ) + if (pruned) continue + if (ref.write) { + changed = demand.setAll() || changed + continue + } + const { node, parent } = up(module, ref.node) + const name = parent?.type === "MemberExpression" && parent.object === node ? memberName(parent) : undefined + changed = (name === undefined || objectMembers.has(name) || isWriteTarget(module, parent!) + ? demand.setAll() + : demand.add(name)) || changed + } + return changed + } + + // What a literal needs from the service objects spread into it. + const owed = (literal: LiteralInfo): Demand => { + const demand = new Demand() + for (const key of literal.keys) demand.addAll(demandOf(key)) + for (const link of literal.links) linkDemand(link, demand) + demand.addAll(demandIn(ownReads, literal)) + return demand + } + + let changed = true + while (changed) { + changed = false + for (const contribution of spreads) { + const literal = literals.get(contribution.literal) + const demand = demandOf(contribution.key) + changed = (literal === undefined || literal.escaped || literal.keys.size === 0 + ? demand.setAll() + : demand.addAll(owed(literal), keysAfter(literal.node, contribution.spread))) || changed + } + for (const literal of literals.values()) { + const demand = literal.demand + if (literal.escaped) { + changed = demand.setAll() || changed + continue + } + for (const key of literal.keys) changed = demand.addAll(demandOf(key)) || changed + for (const link of literal.links) changed = linkDemand(link, demand) || changed + changed = updateMethodReads(literal) || changed + changed = demand.addAll(methodReads(literal)) || changed + if (literal.keys.size === 0 && literal.links.length === 0) changed = demand.setAll() || changed + } + } + + // == edits + + const edits = new Map>() + const removed: Array = [] + if (globalBailouts.length === 0) { + for (const literal of literals.values()) { + if (literal.demand.all) continue + const code = literal.module.input.code + for (const property of literal.node.properties) { + if (isRetained(literal, property)) continue + // The separator may follow whitespace and comments. + let end = property.end + let next = end + for (;;) { + while (next < code.length && /\s/.test(code[next])) next++ + const comment = literal.module.input.comments.find((comment) => comment.start === next) + if (comment === undefined) break + next = comment.end + } + if (code[next] === ",") end = next + 1 + const id = literal.module.input.id + let list = edits.get(id) + if (list === undefined) { + list = [] + edits.set(id, list) + } + list.push({ start: property.start, end }) + removed.push(`${id}:${propertyName(property)}`) + } + } + } + + // A removed property can contain another removed property. Applying both + // would shift the outer range, and removing the outer one covers the inner. + for (const [id, list] of edits) { + list.sort((a, b) => a.start - b.start || b.end - a.end) + const disjoint: Array = [] + for (const edit of list) { + const last = disjoint[disjoint.length - 1] + if (last === undefined || edit.start >= last.end) disjoint.push(edit) + } + edits.set(id, disjoint) + } + + return { + edits, + globalBailouts, + keyBailouts, + demand: new Map([...keyDemand].map(([key, demand]) => [key, demand.all ? "all" : [...demand.names].sort()])), + removed + } +} + +const within = (node: Node, outer: Node) => node.start >= outer.start && node.end <= outer.end + +const containsThis = (node: Node): boolean => + node.type === "ThisExpression" || + children(node).some((child) => child.type !== "FunctionExpression" && containsThis(child)) + +const collectExports = (module: Module) => { + for (const statement of module.input.program.body as ReadonlyArray) { + if (statement.exportKind === "type" || statement.declare === true) continue + switch (statement.type) { + case "ExportNamedDeclaration": { + const declaration = statement.declaration + if (declaration) { + if (declaration.declare === true || declaration.type.startsWith("TS")) continue + const ids: Array = declaration.type === "VariableDeclaration" + ? declaration.declarations.flatMap((d: Node) => bindingIds(d.id)) + : declaration.id + ? [declaration.id] + : [] + for (const id of ids) module.exports.set(id.name, { _tag: "Local", local: id.name }) + } + for (const specifier of statement.specifiers ?? []) { + if (specifier.exportKind === "type") continue + const exported = staticName(specifier.exported, false)! + const local = staticName(specifier.local, false)! + module.exports.set( + exported, + statement.source + ? { _tag: "Reexport", source: statement.source.value, imported: local } + : { _tag: "Local", local } + ) + } + break + } + case "ExportDefaultDeclaration": { + const declaration = statement.declaration + module.exports.set( + "default", + declaration.id ? { _tag: "Local", local: declaration.id.name } : { _tag: "Expression" } + ) + break + } + case "ExportAllDeclaration": + if (statement.exported) { + module.exports.set(staticName(statement.exported, false)!, { + _tag: "Namespace", + source: statement.source.value + }) + } else { + module.stars.push(statement.source.value) + } + break + } + } +} + +const bindingIds = (pattern: Node): Array => { + switch (pattern.type) { + case "Identifier": + return [pattern] + case "ObjectPattern": + return pattern.properties.flatMap((p: Node) => bindingIds(p.type === "RestElement" ? p.argument : p.value)) + case "ArrayPattern": + return pattern.elements.flatMap((e: Node | null) => (e ? bindingIds(e) : [])) + case "AssignmentPattern": + return bindingIds(pattern.left) + case "RestElement": + return bindingIds(pattern.argument) + default: + return [] + } +} diff --git a/packages/tools/bundle/src/internal/scope.ts b/packages/tools/bundle/src/internal/scope.ts new file mode 100644 index 00000000000..cca56604e7c --- /dev/null +++ b/packages/tools/bundle/src/internal/scope.ts @@ -0,0 +1,408 @@ +/** + * Minimal ESTree scope analysis for the service shaking analysis. + * + * Resolves every identifier reference in value positions to the binding that + * declares it, records writes, and keeps a parent map so references can be + * classified by the syntax around them. TypeScript-only syntax is skipped. + * + * @internal + */ + +/** @internal */ +export interface Node { + readonly type: string + readonly start: number + readonly end: number + readonly [key: string]: any +} + +/** @internal */ +export type BindingKind = + | "import" + | "var" + | "let" + | "const" + | "using" + | "function" + | "class" + | "param" + | "catch" + | "enum" + +/** @internal */ +export interface Reference { + readonly node: Node + readonly write: boolean +} + +/** @internal */ +export interface Binding { + readonly name: string + readonly kind: BindingKind + readonly scope: Scope + /** The declaring node: a VariableDeclarator, function, class, import specifier, or the parameter pattern root. */ + readonly declaration: Node + readonly refs: Array +} + +/** @internal */ +export interface Scope { + readonly node: Node + readonly parent: Scope | undefined + readonly bindings: Map + readonly isFunction: boolean +} + +/** @internal */ +export interface ModuleScope { + readonly program: Node + readonly scope: Scope + readonly parents: Map + readonly resolved: Map + /** Binding identifier nodes to the binding they declare. */ + readonly declared: Map + /** References to names that are not declared in the module. */ + readonly globals: Array +} + +const skippedKeys = new Set([ + "typeAnnotation", + "returnType", + "typeParameters", + "typeArguments", + "superTypeArguments", + "superTypeParameters", + "implements" +]) + +const valueTsNodes = new Set([ + "TSAsExpression", + "TSSatisfiesExpression", + "TSNonNullExpression", + "TSTypeAssertion", + "TSInstantiationExpression", + "TSParameterProperty", + "TSExportAssignment", + "TSEnumDeclaration", + "TSEnumBody", + "TSEnumMember" +]) + +const isNode = (value: unknown): value is Node => + typeof value === "object" && value !== null && typeof (value as Node).type === "string" + +const isSkipped = (node: Node): boolean => + node.declare === true || (node.type.startsWith("TS") && !valueTsNodes.has(node.type)) || + node.importKind === "type" || node.exportKind === "type" + +/** @internal */ +export const children = (node: Node): Array => { + const out: Array = [] + for (const key in node) { + if (skippedKeys.has(key)) continue + const value = node[key] + if (Array.isArray(value)) { + for (const item of value) { + if (isNode(item) && !isSkipped(item)) out.push(item) + } + } else if (isNode(value) && !isSkipped(value)) { + out.push(value) + } + } + return out +} + +/** @internal */ +export const isFunctionNode = (node: Node): boolean => + node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || + node.type === "ArrowFunctionExpression" + +const patternNames = (pattern: Node, out: Array): Array => { + switch (pattern.type) { + case "Identifier": + out.push(pattern) + break + case "ObjectPattern": + for (const property of pattern.properties) { + patternNames(property.type === "RestElement" ? property.argument : property.value, out) + } + break + case "ArrayPattern": + for (const element of pattern.elements) { + if (element) patternNames(element, out) + } + break + case "AssignmentPattern": + patternNames(pattern.left, out) + break + case "RestElement": + patternNames(pattern.argument, out) + break + case "TSParameterProperty": + patternNames(pattern.parameter, out) + break + } + return out +} + +/** @internal */ +export const analyzeScopes = (program: Node): ModuleScope => { + const parents = new Map() + const resolved = new Map() + const declared = new Map() + const globals: Array = [] + + const setParents = (node: Node) => { + for (const child of children(node)) { + parents.set(child, node) + setParents(child) + } + } + setParents(program) + + const makeScope = (node: Node, parent: Scope | undefined, isFunction: boolean): Scope => ({ + node, + parent, + bindings: new Map(), + isFunction + }) + + const declare = (scope: Scope, id: Node, kind: BindingKind, declaration: Node) => { + let binding = scope.bindings.get(id.name) + if (binding === undefined) { + binding = { name: id.name, kind, scope, declaration, refs: [] } + scope.bindings.set(id.name, binding) + } + declared.set(id, binding) + } + + const declarePattern = (scope: Scope, pattern: Node, kind: BindingKind, declaration: Node) => { + for (const id of patternNames(pattern, [])) declare(scope, id, kind, declaration) + } + + const hoistStatements = (scope: Scope, statements: ReadonlyArray) => { + for (let statement of statements) { + if ( + (statement.type === "ExportNamedDeclaration" || statement.type === "ExportDefaultDeclaration") && + statement.declaration + ) { + statement = statement.declaration + } + if (isSkipped(statement)) continue + switch (statement.type) { + case "ImportDeclaration": + for (const specifier of statement.specifiers ?? []) { + if (specifier.importKind !== "type") declare(scope, specifier.local, "import", specifier) + } + break + case "VariableDeclaration": + if (statement.kind !== "var") { + for (const declarator of statement.declarations) { + declarePattern(scope, declarator.id, statement.kind === "const" ? "const" : statement.kind, declarator) + } + } + break + case "FunctionDeclaration": + case "ClassDeclaration": + if (statement.id) { + declare(scope, statement.id, statement.type === "ClassDeclaration" ? "class" : "function", statement) + } + break + case "TSEnumDeclaration": + declare(scope, statement.id, "enum", statement) + break + } + } + } + + const hoistVars = (scope: Scope, node: Node) => { + for (const child of children(node)) { + if (isFunctionNode(child) || child.type === "ClassDeclaration" || child.type === "ClassExpression") continue + if (child.type === "VariableDeclaration" && child.kind === "var") { + for (const declarator of child.declarations) declarePattern(scope, declarator.id, "var", declarator) + } + hoistVars(scope, child) + } + } + + const reference = (node: Node, scope: Scope, write: boolean) => { + for (let current: Scope | undefined = scope; current; current = current.parent) { + const binding = current.bindings.get(node.name) + if (binding) { + binding.refs.push({ node, write }) + resolved.set(node, binding) + return + } + } + globals.push(node) + } + + const visitPattern = (pattern: Node, scope: Scope, assign: boolean): void => { + switch (pattern.type) { + case "Identifier": + if (assign) reference(pattern, scope, true) + return + case "ObjectPattern": + for (const property of pattern.properties) { + if (property.type === "RestElement") { + visitPattern(property.argument, scope, assign) + } else { + if (property.computed) visit(property.key, scope) + visitPattern(property.value, scope, assign) + } + } + return + case "ArrayPattern": + for (const element of pattern.elements) { + if (element) visitPattern(element, scope, assign) + } + return + case "AssignmentPattern": + visitPattern(pattern.left, scope, assign) + visit(pattern.right, scope) + return + case "RestElement": + visitPattern(pattern.argument, scope, assign) + return + case "TSParameterProperty": + visitPattern(pattern.parameter, scope, assign) + return + default: + visit(pattern, scope) + } + } + + const visitFunction = (node: Node, scope: Scope) => { + const fnScope = makeScope(node, scope, true) + if (node.type === "FunctionExpression" && node.id) declare(fnScope, node.id, "function", node) + for (const param of node.params) declarePattern(fnScope, param, "param", param) + for (const param of node.params) visitPattern(param, fnScope, false) + const body = node.body + if (!body) return + if (body.type === "BlockStatement") { + hoistStatements(fnScope, body.body) + hoistVars(fnScope, body) + for (const statement of body.body) visit(statement, fnScope) + } else { + visit(body, fnScope) + } + } + + const visitBlock = (node: Node, statements: ReadonlyArray, scope: Scope) => { + const blockScope = makeScope(node, scope, false) + hoistStatements(blockScope, statements) + for (const child of children(node)) visit(child, blockScope) + } + + const visit = (node: Node, scope: Scope): void => { + if (isSkipped(node)) return + switch (node.type) { + case "Identifier": + reference(node, scope, false) + return + case "ImportDeclaration": + case "ExportAllDeclaration": + case "MetaProperty": + case "BreakStatement": + case "ContinueStatement": + case "Super": + case "ThisExpression": + return + case "ExportNamedDeclaration": + if (node.declaration) visit(node.declaration, scope) + return + case "LabeledStatement": + visit(node.body, scope) + return + case "MemberExpression": + visit(node.object, scope) + if (node.computed) visit(node.property, scope) + return + case "Property": + case "MethodDefinition": + case "PropertyDefinition": + case "AccessorProperty": + for (const decorator of node.decorators ?? []) visit(decorator, scope) + if (node.computed) visit(node.key, scope) + if (node.value) visit(node.value, scope) + return + case "VariableDeclaration": + for (const declarator of node.declarations) { + visitPattern(declarator.id, scope, false) + if (declarator.init) visit(declarator.init, scope) + } + return + case "FunctionDeclaration": + case "FunctionExpression": + case "ArrowFunctionExpression": + visitFunction(node, scope) + return + case "ClassDeclaration": + case "ClassExpression": { + for (const decorator of node.decorators ?? []) visit(decorator, scope) + if (node.superClass) visit(node.superClass, scope) + const classScope = makeScope(node, scope, false) + if (node.type === "ClassExpression" && node.id) declare(classScope, node.id, "class", node) + visit(node.body, classScope) + return + } + case "BlockStatement": + case "StaticBlock": + visitBlock(node, node.body, scope) + return + case "SwitchStatement": { + visit(node.discriminant, scope) + const switchScope = makeScope(node, scope, false) + hoistStatements(switchScope, node.cases.flatMap((c: Node) => c.consequent)) + for (const c of node.cases) visit(c, switchScope) + return + } + case "ForStatement": + case "ForInStatement": + case "ForOfStatement": { + const loopScope = makeScope(node, scope, false) + const head = node.type === "ForStatement" ? node.init : node.left + if (head?.type === "VariableDeclaration" && head.kind !== "var") { + for (const declarator of head.declarations) { + declarePattern(loopScope, declarator.id, head.kind === "const" ? "const" : head.kind, declarator) + } + } + if (head && head.type !== "VariableDeclaration" && node.type !== "ForStatement") { + visitPattern(head, loopScope, true) + } else if (head) { + visit(head, loopScope) + } + for (const key of ["test", "update", "right", "body"]) { + if (node[key]) visit(node[key], loopScope) + } + return + } + case "CatchClause": { + const catchScope = makeScope(node, scope, false) + if (node.param) { + declarePattern(catchScope, node.param, "catch", node.param) + visitPattern(node.param, catchScope, false) + } + visit(node.body, catchScope) + return + } + case "AssignmentExpression": + visitPattern(node.left, scope, true) + visit(node.right, scope) + return + case "UpdateExpression": + if (node.argument.type === "Identifier") reference(node.argument, scope, true) + else visit(node.argument, scope) + return + default: + for (const child of children(node)) visit(child, scope) + } + } + + const moduleScope = makeScope(program, undefined, true) + hoistStatements(moduleScope, program.body) + hoistVars(moduleScope, program) + for (const statement of program.body) visit(statement, moduleScope) + + return { program, scope: moduleScope, parents, resolved, declared, globals } +} diff --git a/packages/tools/bundle/test/ServiceShaking.test.ts b/packages/tools/bundle/test/ServiceShaking.test.ts new file mode 100644 index 00000000000..c3e9ca25672 --- /dev/null +++ b/packages/tools/bundle/test/ServiceShaking.test.ts @@ -0,0 +1,398 @@ +import * as babel from "@babel/core" +import * as ServiceShaking from "@effect/bundle/ServiceShaking" +import { assert, describe, it } from "@effect/vitest" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" +import * as Logger from "effect/Logger" +import * as esbuild from "esbuild" +import { execFile } from "node:child_process" +import * as fs from "node:fs/promises" +import * as os from "node:os" +import * as path from "node:path" +import { fileURLToPath, pathToFileURL } from "node:url" +import { type InputOptions, type Plugin, rolldown } from "rolldown" + +const packageDir = fileURLToPath(new URL("..", import.meta.url)) +const packagesDir = fileURLToPath(new URL("../../../", import.meta.url)) +const fixturesDir = path.join(packageDir, "fixtures", "service-shaking") +const nodeFileSystemSource = path.join(packagesDir, "platform", "node-shared", "src", "NodeFileSystem.ts") + +// Fixtures whose only FileSystem demand is `readFile`, reached through a +// different access path in each. +const prunable = ["generator.ts", "combinators.ts", "context.ts", "overrides.ts"] + +// Fixtures that can observe any FileSystem method, so nothing may be removed. +const bailouts = ["bailout-escape.ts", "bailout-inspect.ts", "bailout-unsafe-key.ts"] + +// Small programs from the adversarial review where pruning changed behaviour. +// Bailing out is an acceptable fix for each of them. +const regressions = [ + "release-and-tap.ts", + "logger-fiber.ts", + "on-fiber-start.ts", + "run-fork-hook.ts", + "receiver-method.ts", + "inherited-members.ts", + "async-factory.ts", + "key-mutation.ts", + "separator-comment.ts", + "redactable-option.ts", + "global-fiber.ts", + "arguments-callbacks.ts", + "mutable-receiver.ts", + "nested-providers.ts" +] + +// Providers built by constructors whose methods are local bindings. The +// program only calls `readOne`. +const constructors = ["constructor-gen.ts", "constructor-map.ts"] + +// Module-scope code that only `writeOne` reaches, directly or through the +// services it calls, and code construction must keep running. +const constructorCode: Record< + string, + { readonly removed: ReadonlyArray; readonly kept: ReadonlyArray } +> = { + "constructor-gen.ts": { + removed: [/\bconstructorWriteHelper\b/, /\bdependencyWrite\b/, /\bauditRecord\b/], + kept: [/\bdependencyPrepare\b/, /\bmakeWriteCache\b/] + }, + "constructor-map.ts": { + removed: [/\bconstructorWriteHelper\b/, /\bdependencyWrite\b/], + kept: [/\bdependencyDescribe\b/] + } +} + +const fixtureArgs: Record> = { + "bailout-escape.ts": ["copy"] +} + +// Code that only the unused NodeFileSystem methods reach: `copy`, `watch`, +// `makeTempDirectory*`, `truncate`, and the node:crypto / node:os imports used +// by the temp file helpers. +const unusedMethodCode = [ + /\bnodeCp\b/, + /\bwatchNode\b/, + /\bmakeTempDirectoryFactory\b/, + /\bnodeTruncate\b/, + /["']node:crypto["']/, + /["']node:os["']/ +] + +// The published build annotates pure calls with babel. Rolldown relies on +// those annotations to drop unused module-scope calls such as the +// `const copy = (() => { ... })()` helpers in NodeFileSystem, so the same step +// is applied to every workspace source module. +const annotated = new Map>() +const annotatePureCalls: Plugin = { + name: "annotate-pure-calls", + transform: { + filter: { id: /\.ts$/ }, + async handler(code, id) { + if (!id.startsWith(packagesDir) || id.startsWith(packageDir)) { + return null + } + const key = `${id}\0${code}` + let result = annotated.get(key) + if (result === undefined) { + result = esbuild.transform(code, { + loader: "ts", + format: "esm", + target: "es2022", + sourcefile: id, + tsconfigRaw: { compilerOptions: { verbatimModuleSyntax: true } } + }).then((transpiled) => + babel.transformAsync(transpiled.code, { + babelrc: false, + configFile: false, + compact: false, + cwd: packageDir, + filename: id, + plugins: ["annotate-pure-calls"] + }) + ).then((output) => output!.code!) + annotated.set(key, result) + } + return { code: await result, moduleType: "js" } + } + } +} + +// The hand-trimmed ceiling: NodeFileSystem built with `FileSystem.make({ readFile })` +// instead of the full implementation. This is the most a correct optimization +// can remove for a program that only reads files. +const keepOnlyReadFile: Plugin = { + name: "keep-only-read-file", + transform: { + filter: { id: /NodeFileSystem\.ts$/ }, + handler(code, id) { + if (id !== nodeFileSystemSource) { + return null + } + const start = code.indexOf("FileSystem.make({") + const end = code.indexOf("\n }))", start) + if (start === -1 || end === -1) { + throw new Error("NodeFileSystem no longer builds its service with FileSystem.make({ ... })") + } + return code.slice(0, start) + "FileSystem.make({ readFile }" + code.slice(end + "\n }".length) + } + } +} + +const inputOptions = (fixture: string, plugins: ReadonlyArray = []): InputOptions => ({ + input: path.join(fixturesDir, fixture), + cwd: packageDir, + platform: "node", + logLevel: "silent", + plugins: [...plugins, annotatePureCalls] +}) + +const build = async (options: InputOptions): Promise => { + const bundle = await rolldown(options) + try { + const { output } = await bundle.generate({ format: "esm" }) + return output[0].code + } finally { + await bundle.close() + } +} + +const memo = (f: (fixture: string) => Promise) => { + const cache = new Map>() + return (fixture: string): Promise => { + let result = cache.get(fixture) + if (result === undefined) { + result = f(fixture) + cache.set(fixture, result) + } + return result + } +} + +const baseline = memo((fixture) => build(inputOptions(fixture))) +const ceiling = memo((fixture) => build(inputOptions(fixture, [keepOnlyReadFile]))) +const shaken = memo((fixture) => ServiceShaking.bundle(inputOptions(fixture))) + +let tempDir: Promise | undefined +const getTempDir = () => + tempDir ??= fs.mkdtemp(path.join(os.tmpdir(), "effect-service-shaking-")).then(async (dir) => { + await fs.writeFile(path.join(dir, "input.txt"), "hello") + return dir + }) + +let runs = 0 +const load = async (code: string) => { + const dir = await getTempDir() + const file = path.join(dir, `bundle-${runs++}.mjs`) + await fs.writeFile(file, code) + return import(/* @vite-ignore */ pathToFileURL(file).href) +} + +// Fixtures other than the exported-entry cases are closed programs that print +// their result, so they run in a separate process. +const run = async (code: string, fixture: string): Promise => { + const dir = await getTempDir() + const file = path.join(dir, `bundle-${runs++}.mjs`) + await fs.writeFile(file, code) + const args = [file, path.join(dir, "input.txt"), ...(fixtureArgs[fixture] ?? [])] + return new Promise((resolve, reject) => + execFile( + process.execPath, + process.versions.deno === undefined ? args : ["run", "-A", ...args], + (error, stdout, stderr) => error ? reject(new Error(`${error.message}\n${stderr}`)) : resolve(stdout.trimEnd()) + ) + ) +} + +const size = (code: string) => Buffer.byteLength(code) + +// Every build bundles the reachable Effect source through esbuild and babel. +const timeout = 60_000 + +describe("ServiceShaking", () => { + for (const fixture of [...prunable, ...bailouts, ...regressions, ...constructors]) { + it(`${fixture} behaves like the unoptimized bundle`, { timeout }, async () => { + const [expected, actual] = await Promise.all([ + baseline(fixture).then((code) => run(code, fixture)), + shaken(fixture).then((code) => run(code, fixture)) + ]) + assert.strictEqual(actual, expected) + }) + } + + for (const fixture of prunable) { + it(`${fixture} drops FileSystem methods the program never reads`, { timeout }, async () => { + const [base, trimmed, actual] = await Promise.all([baseline(fixture), ceiling(fixture), shaken(fixture)]) + for (const code of unusedMethodCode) { + assert.match(base, code, "baseline should contain the unused methods") + assert.notMatch(trimmed, code, "hand-trimmed ceiling should not contain the unused methods") + } + for (const code of unusedMethodCode) { + assert.notMatch(actual, code) + } + assert.isAtMost( + size(actual), + Math.ceil(size(trimmed) * 1.05), + `baseline ${size(base)} bytes, hand-trimmed ceiling ${size(trimmed)} bytes` + ) + }) + } + + for (const fixture of bailouts) { + it(`${fixture} keeps every FileSystem method`, { timeout }, async () => { + const [untrimmed, trimmed] = await Promise.all([ + baseline(fixture).then((code) => run(code, fixture)), + ceiling(fixture).then((code) => run(code, fixture)) + ]) + assert.notStrictEqual(trimmed, untrimmed, "trimming FileSystem should be observable in this fixture") + const actual = await shaken(fixture) + for (const code of unusedMethodCode) { + assert.match(actual, code) + } + }) + } + + for (const fixture of constructors) { + it(`${fixture} drops constructor-created methods and the demand only they had`, { timeout }, async () => { + const [base, actual] = await Promise.all([baseline(fixture), shaken(fixture)]) + const { kept, removed } = constructorCode[fixture] + for (const code of [...removed, ...kept]) { + assert.match(base, code, "baseline should contain every helper") + } + for (const code of removed) { + assert.notMatch(actual, code) + } + for (const code of kept) { + assert.match(actual, code) + } + }) + } + + it("exported-layer.ts keeps provider methods reachable from outside the bundle", { timeout }, async () => { + const fixture = "exported-layer.ts" + // Builds the exported Layer the way an importer of the bundle would. + const methods = async (code: string) => { + const { layer } = await load(code) + const context = await Effect.runPromise(Effect.scoped(Layer.build(layer))) + return Object.keys(Context.getOrUndefinedUnsafe(context, "test/Exported") ?? {}).sort() + } + const [expected, actual] = await Promise.all([baseline(fixture).then(methods), shaken(fixture).then(methods)]) + assert.deepStrictEqual(expected, ["read", "unused"]) + assert.deepStrictEqual(actual, expected) + }) + + it("second-pass-drift.ts ignores edits when a consumer transforms differently in the second build", { + timeout + }, async () => { + const fixture = "second-pass-drift.ts" + let transforms = 0 + const drift: Plugin = { + name: "second-pass-drift", + transform: { + filter: { id: /second-pass-drift\.ts$/ }, + handler: (code) => ++transforms === 1 ? null : code.replace("s.read()", "s.unused()") + } + } + const code = await ServiceShaking.bundle(inputOptions(fixture, [drift])) + // Demand was computed from the first build, so only its output is safe. + assert.strictEqual(await run(code, fixture), "1") + }) + + it("resolution-drift.ts ignores edits when an import resolves differently in the second build", { + timeout + }, async () => { + const fixture = "resolution-drift.ts" + let builds = 0 + const drift: Plugin = { + name: "resolution-drift", + buildStart: () => { + builds++ + }, + resolveId: (source, importer) => + builds === 2 && source === "./resolution-drift-a.ts" && importer?.endsWith(`${path.sep}resolution-drift.ts`) + ? path.join(fixturesDir, "resolution-drift-b.ts") + : null + } + const code = await ServiceShaking.bundle(inputOptions(fixture, [drift])) + assert.strictEqual(await run(code, fixture), "1") + }) + + it("external-module.ts keeps methods an external module can observe", { timeout }, async () => { + const fixture = "external-module.ts" + const external: Plugin = { + name: "external-helper", + resolveId: (source) => + source === "./external-helper.ts" ? { id: path.join(fixturesDir, "external-helper.ts"), external: true } : null + } + // The bundle runs from a temporary directory, so the import must stay absolute. + const options: InputOptions = { ...inputOptions(fixture, [external]), makeAbsoluteExternalsRelative: false } + const expected = await run(await build(options), fixture) + const actual = await run(await ServiceShaking.bundle(options), fixture) + assert.strictEqual(expected, "function") + assert.strictEqual(actual, expected) + }) + + describe("code importing the bundle can run inside a provider's scope", () => { + // Lists the methods of a service, read from the current Context by key. + const methodsOf = (key: string) => + Effect.map( + Effect.context(), + (context) => Object.keys(Context.getOrUndefinedUnsafe(context, key) ?? {}).sort() + ) + + // Runs `use` against the unoptimized bundle, then the shaken one. + const importer = async (fixture: string, use: (module: any) => Promise) => { + const expected = await use(await load(await baseline(fixture))) + const actual = await use(await load(await shaken(fixture))) + return { expected, actual } + } + + it("scope-effect-input.ts: an Effect passed to an exported function", { timeout }, async () => { + const { expected, actual } = await importer( + "scope-effect-input.ts", + (module) => module.main(methodsOf("test/ScopeEffectInput")) + ) + assert.deepStrictEqual(expected, ["read", "unused"]) + assert.deepStrictEqual(actual, expected) + }) + + it("scope-layer-input.ts: a Layer passed to an exported function", { timeout }, async () => { + const { expected, actual } = await importer("scope-layer-input.ts", async (module) => { + let seen: ReadonlyArray = [] + const input = Layer.effectDiscard( + Effect.map(methodsOf("test/ScopeLayerInput"), (methods) => { + seen = methods + }) + ) + await module.main(input) + return seen + }) + assert.deepStrictEqual(expected, ["read", "unused"]) + assert.deepStrictEqual(actual, expected) + }) + + it("scope-transformer.ts: an exported Effect.provide transformer", { timeout }, async () => { + const { expected, actual } = await importer( + "scope-transformer.ts", + (module) => Effect.runPromise(module.supply(methodsOf("test/ScopeTransformer"))) + ) + assert.deepStrictEqual(expected, ["read", "unused"]) + assert.deepStrictEqual(actual, expected) + }) + + it("scope-exported-effect.ts: an exported Effect run with the importer's logger", { timeout }, async () => { + const { expected, actual } = await importer("scope-exported-effect.ts", async (module) => { + const seen: Array = [] + const logger = Logger.make((options) => { + const services: ReadonlyMap = Reflect.get(Reflect.get(options.fiber, "context"), "mapUnsafe") + seen.push(typeof Reflect.get(services.get("test/ScopeExportedEffect")!, "unused")) + }) + await Effect.runPromise(Effect.provide(module.program, Logger.layer([logger]))) + return seen + }) + assert.deepStrictEqual(expected, ["function"]) + assert.deepStrictEqual(actual, expected) + }) + }) +}) diff --git a/packages/tools/bundle/tsconfig.fixtures.json b/packages/tools/bundle/tsconfig.fixtures.json index e137b36daf6..2612050548e 100644 --- a/packages/tools/bundle/tsconfig.fixtures.json +++ b/packages/tools/bundle/tsconfig.fixtures.json @@ -4,7 +4,8 @@ "include": ["fixtures"], "compilerOptions": { "rootDir": "fixtures", - "noEmit": true + "noEmit": true, + "types": ["node"] }, "references": [ { "path": "../../effect" }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index d2f3f3d7df3..041d3afbba3 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -802,6 +802,9 @@ importers: glob: specifier: ^14.0.3 version: 14.0.3 + rolldown: + specifier: ^1.2.16 + version: 1.2.16 rollup: specifier: ^4.67.3 version: 4.67.3