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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/filesystem-pure-annotations.md
Original file line number Diff line number Diff line change
@@ -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.
4 changes: 2 additions & 2 deletions packages/effect/src/FileSystem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand All @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
@@ -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<Store>("test/ArgumentsConsumer")
const Released = Context.Service<Store>("test/ArgumentsRelease")

const main = () => {
const log: Array<string> = []
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))
27 changes: 27 additions & 0 deletions packages/tools/bundle/fixtures/service-shaking/async-factory.ts
Original file line number Diff line number Diff line change
@@ -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<Promise<Store>>("test/Async")

async function make(): Promise<Store> {
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))
20 changes: 20 additions & 0 deletions packages/tools/bundle/fixtures/service-shaking/bailout-escape.ts
Original file line number Diff line number Diff line change
@@ -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<string, any>)[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<string> =>
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))
14 changes: 14 additions & 0 deletions packages/tools/bundle/fixtures/service-shaking/bailout-inspect.ts
Original file line number Diff line number Diff line change
@@ -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<string> => 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))
Original file line number Diff line number Diff line change
@@ -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<FileSystem.FileSystem>()
const fs = Context.getOrUndefinedUnsafe<FileSystem.FileSystem>(context, "effect/FileSystem")!

Check failure on line 8 in packages/tools/bundle/fixtures/service-shaking/bailout-unsafe-key.ts

View workflow job for this annotation

GitHub Actions / Build

Property 'getOrUndefinedUnsafe' does not exist on type 'typeof import("/home/runner/work/effect/effect/packages/effect/dist/Context")'. Did you mean 'getOrUndefined'?

Check failure on line 8 in packages/tools/bundle/fixtures/service-shaking/bailout-unsafe-key.ts

View workflow job for this annotation

GitHub Actions / Bundle

Property 'getOrUndefinedUnsafe' does not exist on type 'typeof import("/home/runner/work/effect/effect/packages/effect/dist/Context")'. Did you mean 'getOrUndefined'?

Check failure on line 8 in packages/tools/bundle/fixtures/service-shaking/bailout-unsafe-key.ts

View workflow job for this annotation

GitHub Actions / Snapshot

Property 'getOrUndefinedUnsafe' does not exist on type 'typeof import("/home/runner/work/effect/effect/packages/effect/dist/Context")'. Did you mean 'getOrUndefined'?
const bytes = yield* fs.readFile(path)
return `${bytes.length} copy: ${typeof fs.copy}`
})

const main = (path: string): Promise<string> => Effect.runPromise(Effect.provide(program(path), NodeFileSystem.layer))

Check failure on line 13 in packages/tools/bundle/fixtures/service-shaking/bailout-unsafe-key.ts

View workflow job for this annotation

GitHub Actions / Build

This Effect requires a service that is missing from the expected Effect context: `unknown`. effect(missingEffectContext)

Check failure on line 13 in packages/tools/bundle/fixtures/service-shaking/bailout-unsafe-key.ts

View workflow job for this annotation

GitHub Actions / Build

Argument of type 'Effect<string, unknown, unknown>' is not assignable to parameter of type 'Effect<string, unknown, never>' with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined' to the types of the target's properties.

Check failure on line 13 in packages/tools/bundle/fixtures/service-shaking/bailout-unsafe-key.ts

View workflow job for this annotation

GitHub Actions / Bundle

This Effect requires a service that is missing from the expected Effect context: `unknown`. effect(missingEffectContext)

Check failure on line 13 in packages/tools/bundle/fixtures/service-shaking/bailout-unsafe-key.ts

View workflow job for this annotation

GitHub Actions / Bundle

Argument of type 'Effect<string, unknown, unknown>' is not assignable to parameter of type 'Effect<string, unknown, never>' with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined' to the types of the target's properties.

Check failure on line 13 in packages/tools/bundle/fixtures/service-shaking/bailout-unsafe-key.ts

View workflow job for this annotation

GitHub Actions / Snapshot

This Effect requires a service that is missing from the expected Effect context: `unknown`. effect(missingEffectContext)

Check failure on line 13 in packages/tools/bundle/fixtures/service-shaking/bailout-unsafe-key.ts

View workflow job for this annotation

GitHub Actions / Snapshot

Argument of type 'Effect<string, unknown, unknown>' is not assignable to parameter of type 'Effect<string, unknown, never>' with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined' to the types of the target's properties.

// A closed program: it exports nothing and prints its result.
main(process.argv[2]!).then((output) => console.log(output))
15 changes: 15 additions & 0 deletions packages/tools/bundle/fixtures/service-shaking/combinators.ts
Original file line number Diff line number Diff line change
@@ -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<string> => 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))
85 changes: 85 additions & 0 deletions packages/tools/bundle/fixtures/service-shaking/constructor-gen.ts
Original file line number Diff line number Diff line change
@@ -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<Store>("test/ConstructorGenStore")
const Dependency = Context.Service<Dependency>("test/ConstructorGenDependency")
const Audit = Context.Service<Audit>("test/ConstructorGenAudit")

const log: Array<string> = []

// 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<string, string>()
}

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))
52 changes: 52 additions & 0 deletions packages/tools/bundle/fixtures/service-shaking/constructor-map.ts
Original file line number Diff line number Diff line change
@@ -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<Store>("test/ConstructorMapStore")
const Dependency = Context.Service<Dependency>("test/ConstructorMapDependency")

const log: Array<string> = []

// 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))
15 changes: 15 additions & 0 deletions packages/tools/bundle/fixtures/service-shaking/context.ts
Original file line number Diff line number Diff line change
@@ -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<FileSystem.FileSystem>().pipe(
Effect.flatMap((context) => Context.get(context, FileSystem.FileSystem).readFile(path)),
Effect.map((bytes) => `${bytes.length}`)
)

const main = (path: string): Promise<string> => 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))
16 changes: 16 additions & 0 deletions packages/tools/bundle/fixtures/service-shaking/exported-layer.ts
Original file line number Diff line number Diff line change
@@ -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<Store>("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))
Original file line number Diff line number Diff line change
@@ -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<string, any>)["~effect/Fiber/currentFiber"]
return typeof fiber.context.mapUnsafe.get("test/ExternalModule").unused
}
20 changes: 20 additions & 0 deletions packages/tools/bundle/fixtures/service-shaking/external-module.ts
Original file line number Diff line number Diff line change
@@ -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<Store>("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))
14 changes: 14 additions & 0 deletions packages/tools/bundle/fixtures/service-shaking/generator.ts
Original file line number Diff line number Diff line change
@@ -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<string> => 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))
Loading
Loading